opencode-swarm 7.125.5 → 7.126.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.opencode/skills/brainstorm/SKILL.md +19 -14
  2. package/.opencode/skills/execute/SKILL.md +5 -0
  3. package/.opencode/skills/phase-wrap/SKILL.md +2 -0
  4. package/.opencode/skills/plan/SKILL.md +22 -15
  5. package/.opencode/skills/specify/SKILL.md +18 -14
  6. package/.opencode/skills/swarm-pr-feedback/SKILL.md +1 -0
  7. package/dist/agents/architect.d.ts +9 -7
  8. package/dist/cli/{curation-policy-62w2pwfz.js → curation-policy-dptr1rfe.js} +2 -2
  9. package/dist/cli/{curator-mhhvx2pw.js → curator-23hynz78.js} +9 -9
  10. package/dist/cli/{curator-llm-factory-av2tcfy9.js → curator-llm-factory-r648jn8e.js} +9 -9
  11. package/dist/cli/{guardrail-explain-kqx2bczn.js → guardrail-explain-6atsd4vr.js} +10 -10
  12. package/dist/cli/{hive-promoter-6mhnhrbx.js → hive-promoter-bnkhzd46.js} +9 -9
  13. package/dist/cli/{index-s6hskqg6.js → index-0ff5cm9j.js} +85 -40
  14. package/dist/cli/{index-4b1e5m0d.js → index-16z6txq3.js} +1 -1
  15. package/dist/cli/{index-gbnpz7rh.js → index-2bnfwmk3.js} +1 -1
  16. package/dist/cli/{index-1012f47p.js → index-2yd75hms.js} +3 -3
  17. package/dist/cli/{index-0cdq55k0.js → index-68fpa7ff.js} +10 -10
  18. package/dist/cli/{index-74xejn4v.js → index-a1c9az5e.js} +117 -19
  19. package/dist/cli/{index-0f45t7xy.js → index-bcgfhxzv.js} +4 -4
  20. package/dist/cli/{index-e315gwc9.js → index-cdx337js.js} +1 -1
  21. package/dist/cli/{index-yq4s3q43.js → index-kwnsatzq.js} +2 -2
  22. package/dist/cli/{index-1htanqp1.js → index-mgrsx5hn.js} +1 -1
  23. package/dist/cli/{index-ccfkfrew.js → index-y4ry07h8.js} +1 -1
  24. package/dist/cli/{index-gd5w3ef8.js → index-yfzn5r9s.js} +3 -3
  25. package/dist/cli/index.js +9 -9
  26. package/dist/cli/{knowledge-escalator-h3hg7ek7.js → knowledge-escalator-4hc8w7sd.js} +3 -3
  27. package/dist/cli/{knowledge-events-jtr66wxz.js → knowledge-events-kyqjv1f8.js} +1 -1
  28. package/dist/cli/{knowledge-store-69ttjjjs.js → knowledge-store-06k0p1gs.js} +1 -1
  29. package/dist/cli/{knowledge-validator-yn06rh13.js → knowledge-validator-42xjmcmh.js} +4 -4
  30. package/dist/cli/{scan-cursor-r0w2p5gz.js → scan-cursor-gjcvpyta.js} +2 -2
  31. package/dist/cli/{skill-generator-a7xfyddq.js → skill-generator-t6j93mwt.js} +5 -5
  32. package/dist/commands/turbo-constants.d.ts +6 -0
  33. package/dist/config/constants.d.ts +1 -1
  34. package/dist/config/loader.d.ts +26 -0
  35. package/dist/index.js +30 -63
  36. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.125.5",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer"]},quality_budget:{description:"code quality budget check",agents:["architect"]},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","test_engineer"]},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"]},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"]},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"]},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES),TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.126.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer"]},quality_budget:{description:"code quality budget check",agents:["architect"]},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","test_engineer"]},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"]},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"]},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"]},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES),TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -6,7 +6,7 @@ While Turbo Mode is active:
6
6
  - **Stage A gates** (lint, imports, pre_check_batch) are still REQUIRED for ALL tasks
7
7
  - **Tier 3 tasks** (security-sensitive files matching: architect*.ts, delegation*.ts, guardrails*.ts, adversarial*.ts, sanitiz*.ts, auth*, permission*, crypto*, secret*, security) still require FULL review (Stage B)
8
8
  - **Tier 0-2 tasks** can skip Stage B (reviewer, test_engineer) to speed up execution
9
- - **Phase completion gates** (completion-verify and drift verification gate) are automatically bypassed phase_complete will succeed without drift verification evidence when turbo is active. Note: turbo bypass is session-scoped; one session's turbo does not affect other sessions.
9
+ - **Phase completion gates** (Gates 1–5: completion-verify, drift-verifier, hallucination-guard, mutation-gate, phase-council) are automatically bypassed via the orchestrator short-circuit at \`src/tools/phase-complete.ts:774–827\` when turbo is active; Gate 5b (architecture-supervisor), Gate 6 (final-council), and Gate 7 (full-auto) remain enforced. Note: turbo bypass is session-scoped; one session's turbo does not affect other sessions.
10
10
 
11
11
  Classification still determines the pipeline:
12
12
  - TIER 0 (metadata): lint + diff only — no change
@@ -155,7 +155,7 @@ Audit (no architect needed): \`/swarm epic status | last | decide | calibration\
155
155
 
156
156
  `)}doc.write("payload.value = newResult;"),doc.write("return payload;");let fn2=doc.compile();return(payload,ctx)=>fn2(shape,payload,ctx)},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;if(jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0){if(!fastpass)fastpass=generateFastpass(def.shape);if(payload=fastpass(payload,ctx),!catchall)return payload;return handleCatchall([],input,payload,ctx,value,inst)}return superParse(payload,ctx)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),defineLazy(inst._zod,"optout",()=>def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),defineLazy(inst._zod,"values",()=>{if(def.options.every((o)=>o._zod.values))return new Set(def.options.flatMap((option)=>Array.from(option._zod.values)));return}),defineLazy(inst._zod,"pattern",()=>{if(def.options.every((o)=>o._zod.pattern)){let patterns=def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${patterns.map((p)=>cleanRegex(p.source)).join("|")})$`)}return});let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleUnionResults(results2,payload,inst,ctx)})}});$ZodXor=$constructor("$ZodXor",(inst,def)=>{$ZodUnion.init(inst,def),def.inclusive=!1;let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else results.push(result)}if(!async)return handleExclusiveUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleExclusiveUnionResults(results2,payload,inst,ctx)})}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k,v]of Object.entries(pv)){if(!propValues[k])propValues[k]=new Set;for(let val of v)propValues[k].add(val)}}return propValues});let disc=cached(()=>{let opts=def.options,map=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v of values){if(map.has(v))throw Error(`Duplicate discriminator value "${String(v)}"`);map.set(v,o)}}return map});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);if(opt)return opt._zod.run(payload,ctx);if(def.unionFallback)return _super(payload,ctx);return payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,input,path:[def.discriminator],inst}),payload}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);if(left instanceof Promise||right instanceof Promise)return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults(payload,left2,right2)});return handleIntersectionResults(payload,left,right)}});$ZodTuple=$constructor("$ZodTuple",(inst,def)=>{$ZodType.init(inst,def);let items=def.items;inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({input,inst,expected:"tuple",code:"invalid_type"}),payload;payload.value=[];let proms=[],reversedIndex=[...items].reverse().findIndex((item)=>item._zod.optin!=="optional"),optStart=reversedIndex===-1?0:items.length-reversedIndex;if(!def.rest){let tooBig=input.length>items.length,tooSmall=input.length<optStart-1;if(tooBig||tooSmall)return payload.issues.push({...tooBig?{code:"too_big",maximum:items.length,inclusive:!0}:{code:"too_small",minimum:items.length},input,inst,origin:"array"}),payload}let i=-1;for(let item of items){if(i++,i>=input.length){if(i>=optStart)continue}let result=item._zod.run({value:input[i],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult(result2,payload,i)));else handleTupleResult(result,payload,i)}if(def.rest){let rest=input.slice(items.length);for(let el of rest){i++;let result=def.rest._zod.run({value:el,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult(result2,payload,i)));else handleTupleResult(result,payload,i)}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values){payload.value={};let recordKeys=new Set;for(let key of values)if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){recordKeys.add(typeof key==="number"?key.toString():key);let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[key]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[key]=result.value}}let unrecognized;for(let key in input)if(!recordKeys.has(key))unrecognized=unrecognized??[],unrecognized.push(key);if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof key==="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(retryResult.issues.length===0)keyResult=retryResult}if(keyResult.issues.length){if(def.mode==="loose")payload.value[key]=input[key];else payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues(key,result2.issues));payload.value[keyResult.value]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues(key,result.issues));payload.value[keyResult.value]=result.value}}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}}),$ZodMap=$constructor("$ZodMap",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Map))return payload.issues.push({expected:"map",code:"invalid_type",input,inst}),payload;let proms=[];payload.value=new Map;for(let[key,value]of input){let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx),valueResult=def.valueType._zod.run({value,issues:[]},ctx);if(keyResult instanceof Promise||valueResult instanceof Promise)proms.push(Promise.all([keyResult,valueResult]).then(([keyResult2,valueResult2])=>{handleMapResult(keyResult2,valueResult2,payload,key,input,inst,ctx)}));else handleMapResult(keyResult,valueResult,payload,key,input,inst,ctx)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodSet=$constructor("$ZodSet",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Set))return payload.issues.push({input,inst,expected:"set",code:"invalid_type"}),payload;let proms=[];payload.value=new Set;for(let item of input){let result=def.valueType._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleSetResult(result2,payload)));else handleSetResult(result,payload)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter((k)=>propertyKeyTypes.has(typeof k)).map((o)=>typeof o==="string"?escapeRegex(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(valuesSet.has(input))return payload;return payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{if($ZodType.init(inst,def),def.values.length===0)throw Error("Cannot create literal schema with no valid values");let values=new Set(def.values);inst._zod.values=values,inst._zod.pattern=new RegExp(`^(${def.values.map((o)=>typeof o==="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(values.has(input))return payload;return payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodFile=$constructor("$ZodFile",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(input instanceof File)return payload;return payload.issues.push({expected:"file",code:"invalid_type",input,inst}),payload}}),$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then((output2)=>{return payload.value=output2,payload});if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0}),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((r)=>handleOptionalResult(r,payload.value));return handleOptionalResult(result,payload.value)}if(payload.value===void 0)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>{return def.innerType._zod.run(payload,ctx)}}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleDefaultResult(result2,def));return handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)payload.value=def.defaultValue;return def.innerType._zod.run(payload,ctx)}}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter((x)=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleNonOptionalResult(result2,inst));return handleNonOptionalResult(result,inst)}});$ZodSuccess=$constructor("$ZodSuccess",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError("ZodSuccess");let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{return payload.value=result2.issues.length===0,payload});return payload.value=result.issues.length===0,payload}}),$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{if(payload.value=result2.value,result2.issues.length)payload.value=def.catchValue({...payload,error:{issues:result2.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[];return payload});if(payload.value=result.value,result.issues.length)payload.value=def.catchValue({...payload,error:{issues:result.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[];return payload}}),$ZodNaN=$constructor("$ZodNaN",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="number"||!Number.isNaN(payload.value))return payload.issues.push({input:payload.value,inst,expected:"nan",code:"invalid_type"}),payload;return payload}}),$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handlePipeResult(right2,def.in,ctx));return handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handlePipeResult(left2,def.out,ctx));return handlePipeResult(left,def.out,ctx)}});$ZodCodec=$constructor("$ZodCodec",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"values",()=>def.in._zod.values),defineLazy(inst._zod,"optin",()=>def.in._zod.optin),defineLazy(inst._zod,"optout",()=>def.out._zod.optout),defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if((ctx.direction||"forward")==="forward"){let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handleCodecAResult(left2,def,ctx));return handleCodecAResult(left,def,ctx)}else{let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handleCodecAResult(right2,def,ctx));return handleCodecAResult(right,def,ctx)}}});$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy(inst._zod,"values",()=>def.innerType._zod.values),defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin),defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then(handleReadonlyResult);return handleReadonlyResult(result)}});$ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(inst,def)=>{$ZodType.init(inst,def);let regexParts=[];for(let part of def.parts)if(typeof part==="object"&&part!==null){if(!part._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);let source=part._zod.pattern instanceof RegExp?part._zod.pattern.source:part._zod.pattern;if(!source)throw Error(`Invalid template literal part: ${part._zod.traits}`);let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;regexParts.push(source.slice(start,end))}else if(part===null||primitiveTypes.has(typeof part))regexParts.push(escapeRegex(`${part}`));else throw Error(`Invalid template literal part: ${part}`);inst._zod.pattern=new RegExp(`^${regexParts.join("")}$`),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="string")return payload.issues.push({input:payload.value,inst,expected:"string",code:"invalid_type"}),payload;if(inst._zod.pattern.lastIndex=0,!inst._zod.pattern.test(payload.value))return payload.issues.push({input:payload.value,inst,code:"invalid_format",format:def.format??"template_literal",pattern:inst._zod.pattern.source}),payload;return payload}}),$ZodFunction=$constructor("$ZodFunction",(inst,def)=>{return $ZodType.init(inst,def),inst._def=def,inst._zod.def=def,inst.implement=(func)=>{if(typeof func!=="function")throw Error("implement() must be called with a function");return function(...args2){let parsedArgs=inst._def.input?parse(inst._def.input,args2):args2,result=Reflect.apply(func,this,parsedArgs);if(inst._def.output)return parse(inst._def.output,result);return result}},inst.implementAsync=(func)=>{if(typeof func!=="function")throw Error("implementAsync() must be called with a function");return async function(...args2){let parsedArgs=inst._def.input?await parseAsync(inst._def.input,args2):args2,result=await Reflect.apply(func,this,parsedArgs);if(inst._def.output)return await parseAsync(inst._def.output,result);return result}},inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="function")return payload.issues.push({code:"invalid_type",expected:"function",input:payload.value,inst}),payload;if(inst._def.output&&inst._def.output._zod.def.type==="promise")payload.value=inst.implementAsync(payload.value);else payload.value=inst.implement(payload.value);return payload},inst.input=(...args2)=>{let F=inst.constructor;if(Array.isArray(args2[0]))return new F({type:"function",input:new $ZodTuple({type:"tuple",items:args2[0],rest:args2[1]}),output:inst._def.output});return new F({type:"function",input:args2[0],output:inst._def.output})},inst.output=(output)=>{return new inst.constructor({type:"function",input:inst._def.input,output})},inst}),$ZodPromise=$constructor("$ZodPromise",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{return Promise.resolve(payload.value).then((inner)=>def.innerType._zod.run({value:inner,issues:[]},ctx))}}),$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,"innerType",()=>def.getter()),defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern),defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues),defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0),defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0),inst._zod.parse=(payload,ctx)=>{return inst._zod.innerType._zod.run(payload,ctx)}}),$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>{return payload},inst._zod.check=(payload)=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then((r2)=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst);return}})});function ar_default(){return{localeError:error()}}var error=()=>{let Sizable={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${issue2.expected}، ولكن تم إدخال ${received}`;return`مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`}case"invalid_value":if(issue2.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue2.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return` أكبر من اللازم: يفترض أن تكون ${issue2.origin??"القيمة"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${issue2.origin??"القيمة"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${issue2.prefix}"`;if(_issue.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;if(_issue.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;if(_issue.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${issue2.divisor}`;case"unrecognized_keys":return`معرف${issue2.keys.length>1?"ات":""} غريب${issue2.keys.length>1?"ة":""}: ${joinValues(issue2.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${issue2.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${issue2.origin}`;default:return"مدخل غير مقبول"}}};var init_ar=__esm(()=>{init_util()});function az_default(){return{localeError:error2()}}var error2=()=>{let Sizable={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Yanlış dəyər: gözlənilən instanceof ${issue2.expected}, daxil olan ${received}`;return`Yanlış dəyər: gözlənilən ${expected}, daxil olan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue2.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Çox böyük: gözlənilən ${issue2.origin??"dəyər"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`Çox böyük: gözlənilən ${issue2.origin??"dəyər"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`;if(_issue.format==="ends_with")return`Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`;if(_issue.format==="includes")return`Yanlış mətn: "${_issue.includes}" daxil olmalıdır`;if(_issue.format==="regex")return`Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Yanlış ədəd: ${issue2.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${issue2.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};var init_az=__esm(()=>{init_util()});function getBelarusianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function be_default(){return{localeError:error3()}}var error3=()=>{let Sizable={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},TypeDictionary={nan:"NaN",number:"лік",array:"масіў"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Няправільны ўвод: чакаўся instanceof ${issue2.expected}, атрымана ${received}`;return`Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`}case"invalid_value":if(issue2.values.length===1)return`Няправільны ўвод: чакалася ${stringifyPrimitive(issue2.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getBelarusianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта вялікі: чакалася, што ${issue2.origin??"значэнне"} павінна ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`}return`Занадта вялікі: чакалася, што ${issue2.origin??"значэнне"} павінна быць ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getBelarusianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта малы: чакалася, што ${issue2.origin} павінна ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`}return`Занадта малы: чакалася, што ${issue2.origin} павінна быць ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;if(_issue.format==="includes")return`Няправільны радок: павінен змяшчаць "${_issue.includes}"`;if(_issue.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;return`Няправільны ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${issue2.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${issue2.keys.length>1?"ключы":"ключ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${issue2.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${issue2.origin}`;default:return"Няправільны ўвод"}}};var init_be=__esm(()=>{init_util()});function bg_default(){return{localeError:error4()}}var error4=()=>{let Sizable={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},TypeDictionary={nan:"NaN",number:"число",array:"масив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Невалиден вход: очакван instanceof ${issue2.expected}, получен ${received}`;return`Невалиден вход: очакван ${expected}, получен ${received}`}case"invalid_value":if(issue2.values.length===1)return`Невалиден вход: очакван ${stringifyPrimitive(issue2.values[0])}`;return`Невалидна опция: очаквано едно от ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Твърде голямо: очаква се ${issue2.origin??"стойност"} да съдържа ${adj}${issue2.maximum.toString()} ${sizing.unit??"елемента"}`;return`Твърде голямо: очаква се ${issue2.origin??"стойност"} да бъде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Твърде малко: очаква се ${issue2.origin} да съдържа ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Твърде малко: очаква се ${issue2.origin} да бъде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Невалиден низ: трябва да започва с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Невалиден низ: трябва да завършва с "${_issue.suffix}"`;if(_issue.format==="includes")return`Невалиден низ: трябва да включва "${_issue.includes}"`;if(_issue.format==="regex")return`Невалиден низ: трябва да съвпада с ${_issue.pattern}`;let invalid_adj="Невалиден";if(_issue.format==="emoji")invalid_adj="Невалидно";if(_issue.format==="datetime")invalid_adj="Невалидно";if(_issue.format==="date")invalid_adj="Невалидна";if(_issue.format==="time")invalid_adj="Невалидно";if(_issue.format==="duration")invalid_adj="Невалидна";return`${invalid_adj} ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${issue2.divisor}`;case"unrecognized_keys":return`Неразпознат${issue2.keys.length>1?"и":""} ключ${issue2.keys.length>1?"ове":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${issue2.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${issue2.origin}`;default:return"Невалиден вход"}}};var init_bg=__esm(()=>{init_util()});function ca_default(){return{localeError:error5()}}var error5=()=>{let Sizable={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Tipus invàlid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;return`Tipus invàlid: s'esperava ${expected}, s'ha rebut ${received}`}case"invalid_value":if(issue2.values.length===1)return`Valor invàlid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;return`Opció invàlida: s'esperava una de ${joinValues(issue2.values," o ")}`;case"too_big":{let adj=issue2.inclusive?"com a màxim":"menys de",sizing=getSizing(issue2.origin);if(sizing)return`Massa gran: s'esperava que ${issue2.origin??"el valor"} contingués ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Massa gran: s'esperava que ${issue2.origin??"el valor"} fos ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"com a mínim":"més de",sizing=getSizing(issue2.origin);if(sizing)return`Massa petit: s'esperava que ${issue2.origin} contingués ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Format invàlid: ha de començar amb "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Format invàlid: ha d'acabar amb "${_issue.suffix}"`;if(_issue.format==="includes")return`Format invàlid: ha d'incloure "${_issue.includes}"`;if(_issue.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;return`Format invàlid per a ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clau${issue2.keys.length>1?"s":""} no reconeguda${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${issue2.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${issue2.origin}`;default:return"Entrada invàlida"}}};var init_ca=__esm(()=>{init_util()});function cs_default(){return{localeError:error6()}}var error6=()=>{let Sizable={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},TypeDictionary={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Neplatný vstup: očekáváno instanceof ${issue2.expected}, obdrženo ${received}`;return`Neplatný vstup: očekáváno ${expected}, obdrženo ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neplatný vstup: očekáváno ${stringifyPrimitive(issue2.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Hodnota je příliš velká: ${issue2.origin??"hodnota"} musí mít ${adj}${issue2.maximum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš velká: ${issue2.origin??"hodnota"} musí být ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Hodnota je příliš malá: ${issue2.origin??"hodnota"} musí mít ${adj}${issue2.minimum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš malá: ${issue2.origin??"hodnota"} musí být ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Neplatný řetězec: musí začínat na "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neplatný řetězec: musí končit na "${_issue.suffix}"`;if(_issue.format==="includes")return`Neplatný řetězec: musí obsahovat "${_issue.includes}"`;if(_issue.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;return`Neplatný formát ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${issue2.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${issue2.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${issue2.origin}`;default:return"Neplatný vstup"}}};var init_cs=__esm(()=>{init_util()});function da_default(){return{localeError:error7()}}var error7=()=>{let Sizable={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;return`Ugyldigt input: forventede ${expected}, fik ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig værdi: forventede ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For stor: forventede ${origin??"value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor: forventede ${origin??"value"} havde ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: skal starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: skal ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: skal indeholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${issue2.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${issue2.origin}`;default:return"Ugyldigt input"}}};var init_da=__esm(()=>{init_util()});function de_default(){return{localeError:error8()}}var error8=()=>{let Sizable={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},TypeDictionary={nan:"NaN",number:"Zahl",array:"Array"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ungültige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;return`Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ungültige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;return`Ungültige Option: erwartet eine von ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Zu groß: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ist`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ungültiger String: muss mit "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ungültiger String: muss mit "${_issue.suffix}" enden`;if(_issue.format==="includes")return`Ungültiger String: muss "${_issue.includes}" enthalten`;if(_issue.format==="regex")return`Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;return`Ungültig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;case"unrecognized_keys":return`${issue2.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${issue2.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${issue2.origin}`;default:return"Ungültige Eingabe"}}};var init_de=__esm(()=>{init_util()});function en_default(){return{localeError:error9()}}var error9=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Invalid string: must start with "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}};var init_en=__esm(()=>{init_util()});function eo_default(){return{localeError:error10()}}var error10=()=>{let Sizable={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},TypeDictionary={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Nevalida enigo: atendiĝis instanceof ${issue2.expected}, riceviĝis ${received}`;return`Nevalida enigo: atendiĝis ${expected}, riceviĝis ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nevalida enigo: atendiĝis ${stringifyPrimitive(issue2.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Tro granda: atendiĝis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Tro malgranda: atendiĝis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Tro malgranda: atendiĝis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`;if(_issue.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;if(_issue.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;return`Nevalida ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${issue2.divisor}`;case"unrecognized_keys":return`Nekonata${issue2.keys.length>1?"j":""} ŝlosilo${issue2.keys.length>1?"j":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${issue2.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${issue2.origin}`;default:return"Nevalida enigo"}}};var init_eo=__esm(()=>{init_util()});function es_default(){return{localeError:error11()}}var error11=()=>{let Sizable={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrada inválida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;return`Entrada inválida: se esperaba ${expected}, recibido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inválida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;return`Opción inválida: se esperaba una de ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado grande: se esperaba que ${origin??"valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${origin??"valor"} fuera ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Cadena inválida: debe comenzar con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Cadena inválida: debe terminar en "${_issue.suffix}"`;if(_issue.format==="includes")return`Cadena inválida: debe incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;return`Inválido ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Llave${issue2.keys.length>1?"s":""} desconocida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Llave inválida en ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return"Entrada inválida"}}};var init_es=__esm(()=>{init_util()});function fa_default(){return{localeError:error12()}}var error12=()=>{let Sizable={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},TypeDictionary={nan:"NaN",number:"عدد",array:"آرایه"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ورودی نامعتبر: می‌بایست instanceof ${issue2.expected} می‌بود، ${received} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${expected} می‌بود، ${received} دریافت شد`}case"invalid_value":if(issue2.values.length===1)return`ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue2.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue2.values,"|")} می‌بود`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`خیلی بزرگ: ${issue2.origin??"مقدار"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${issue2.origin??"مقدار"} باید ${adj}${issue2.maximum.toString()} باشد`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} باشد`;return`خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} باشد`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;if(_issue.format==="ends_with")return`رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;if(_issue.format==="includes")return`رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;if(_issue.format==="regex")return`رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;return`${FormatDictionary[_issue.format]??issue2.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${issue2.divisor} باشد`;case"unrecognized_keys":return`کلید${issue2.keys.length>1?"های":""} ناشناس: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${issue2.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${issue2.origin}`;default:return"ورودی نامعتبر"}}};var init_fa=__esm(()=>{init_util()});function fi_default(){return{localeError:error13()}}var error13=()=>{let Sizable={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;return`Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`}case"invalid_value":if(issue2.values.length===1)return`Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue2.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();return`Liian suuri: arvon täytyy olla ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();return`Liian pieni: arvon täytyy olla ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;if(_issue.format==="includes")return`Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;if(_issue.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;return`Virheellinen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${issue2.divisor} monikerta`;case"unrecognized_keys":return`${issue2.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};var init_fi=__esm(()=>{init_util()});function fr_default(){return{localeError:error14()}}var error14=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},TypeDictionary={nan:"NaN",number:"nombre",array:"tableau"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrée invalide : instanceof ${issue2.expected} attendu, ${received} reçu`;return`Entrée invalide : ${expected} attendu, ${received} reçu`}case"invalid_value":if(issue2.values.length===1)return`Entrée invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;return`Option invalide : une valeur parmi ${joinValues(issue2.values,"|")} attendue`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : ${issue2.origin??"valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"élément(s)"}`;return`Trop grand : ${issue2.origin??"valeur"} doit être ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : ${issue2.origin} doit être ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clé${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue2.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entrée invalide"}}};var init_fr=__esm(()=>{init_util()});function fr_CA_default(){return{localeError:error15()}}var error15=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Entrée invalide : attendu instanceof ${issue2.expected}, reçu ${received}`;return`Entrée invalide : attendu ${expected}, reçu ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrée invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"≤":"<",sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : attendu que ${issue2.origin??"la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`Trop grand : attendu que ${issue2.origin??"la valeur"} soit ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"≥":">",sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clé${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue2.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return"Entrée invalide"}}};var init_fr_CA=__esm(()=>{init_util()});function he_default(){return{localeError:error16()}}var error16=()=>{let TypeNames={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},Sizable={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},typeEntry=(t)=>t?TypeNames[t]:void 0,typeLabel=(t)=>{let e=typeEntry(t);if(e)return e.label;return t??TypeNames.unknown.label},withDefinite=(t)=>`ה${typeLabel(t)}`,verbFor=(t)=>{return(typeEntry(t)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},getSizing=(origin)=>{if(!origin)return null;return Sizable[origin]??null},FormatDictionary={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expectedKey=issue2.expected,expected=TypeDictionary[expectedKey??""]??typeLabel(expectedKey),receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??TypeNames[receivedType]?.label??receivedType;if(/^[A-Z]/.test(issue2.expected))return`קלט לא תקין: צריך להיות instanceof ${issue2.expected}, התקבל ${received}`;return`קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`}case"invalid_value":{if(issue2.values.length===1)return`ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue2.values[0])}`;let stringified=issue2.values.map((v)=>stringifyPrimitive(v));if(issue2.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;let lastValue=stringified[stringified.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${stringified.slice(0,-1).join(", ")} או ${lastValue}`}case"too_big":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.longLabel??"ארוך"} מדי: ${subject} צריכה להכיל ${issue2.maximum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"או פחות":"לכל היותר"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`קטן או שווה ל-${issue2.maximum}`:`קטן מ-${issue2.maximum}`;return`גדול מדי: ${subject} צריך להיות ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"צריכה":"צריך",comparison=issue2.inclusive?`${issue2.maximum} ${sizing?.unit??""} או פחות`:`פחות מ-${issue2.maximum} ${sizing?.unit??""}`;return`גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim()}let adj=issue2.inclusive?"<=":"<",be=verbFor(issue2.origin??"value");if(sizing?.unit)return`${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`${sizing?.longLabel??"גדול"} מדי: ${subject} ${be} ${adj}${issue2.maximum.toString()}`}case"too_small":{let sizing=getSizing(issue2.origin),subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string")return`${sizing?.shortLabel??"קצר"} מדי: ${subject} צריכה להכיל ${issue2.minimum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"או יותר":"לפחות"}`.trim();if(issue2.origin==="number"){let comparison=issue2.inclusive?`גדול או שווה ל-${issue2.minimum}`:`גדול מ-${issue2.minimum}`;return`קטן מדי: ${subject} צריך להיות ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){let verb=issue2.origin==="set"?"צריכה":"צריך";if(issue2.minimum===1&&issue2.inclusive){let singularPhrase=issue2.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`}let comparison=issue2.inclusive?`${issue2.minimum} ${sizing?.unit??""} או יותר`:`יותר מ-${issue2.minimum} ${sizing?.unit??""}`;return`קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim()}let adj=issue2.inclusive?">=":">",be=verbFor(issue2.origin??"value");if(sizing?.unit)return`${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`${sizing?.shortLabel??"קטן"} מדי: ${subject} ${be} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${_issue.prefix}"`;if(_issue.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${_issue.suffix}"`;if(_issue.format==="includes")return`המחרוזת חייבת לכלול "${_issue.includes}"`;if(_issue.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`;let nounEntry=FormatDictionary[_issue.format],noun=nounEntry?.label??_issue.format,adjective=(nounEntry?.gender??"m")==="f"?"תקינה":"תקין";return`${noun} לא ${adjective}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${issue2.divisor}`;case"unrecognized_keys":return`מפתח${issue2.keys.length>1?"ות":""} לא מזוה${issue2.keys.length>1?"ים":"ה"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${withDefinite(issue2.origin??"array")}`;default:return"קלט לא תקין"}}};var init_he=__esm(()=>{init_util()});function hu_default(){return{localeError:error17()}}var error17=()=>{let Sizable={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},TypeDictionary={nan:"NaN",number:"szám",array:"tömb"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Érvénytelen bemenet: a várt érték instanceof ${issue2.expected}, a kapott érték ${received}`;return`Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`}case"invalid_value":if(issue2.values.length===1)return`Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue2.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Túl nagy: ${issue2.origin??"érték"} mérete túl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${issue2.origin??"érték"} túl nagy: ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Túl kicsi: a bemeneti érték ${issue2.origin} mérete túl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Túl kicsi: a bemeneti érték ${issue2.origin} túl kicsi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;if(_issue.format==="ends_with")return`Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;if(_issue.format==="includes")return`Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;if(_issue.format==="regex")return`Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;return`Érvénytelen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Érvénytelen szám: ${issue2.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${issue2.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${issue2.origin}`;default:return"Érvénytelen bemenet"}}};var init_hu=__esm(()=>{init_util()});function getArmenianPlural(count,one,many){return Math.abs(count)===1?one:many}function withDefiniteArticle(word){if(!word)return"";let vowels=["ա","ե","ը","ի","ո","ու","օ"],lastChar=word[word.length-1];return word+(vowels.includes(lastChar)?"ն":"ը")}function hy_default(){return{localeError:error18()}}var error18=()=>{let Sizable={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},TypeDictionary={nan:"NaN",number:"թիվ",array:"զանգված"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${issue2.expected}, ստացվել է ${received}`;return`Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`}case"invalid_value":if(issue2.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${stringifyPrimitive(issue2.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getArmenianPlural(maxValue,sizing.unit.one,sizing.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin??"արժեք")} կունենա ${adj}${issue2.maximum.toString()} ${unit}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin??"արժեք")} լինի ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getArmenianPlural(minValue,sizing.unit.one,sizing.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} կունենա ${adj}${issue2.minimum.toString()} ${unit}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue2.origin)} լինի ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${_issue.prefix}"-ով`;if(_issue.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${_issue.suffix}"-ով`;if(_issue.format==="includes")return`Սխալ տող․ պետք է պարունակի "${_issue.includes}"`;if(_issue.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${_issue.pattern} ձևաչափին`;return`Սխալ ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${issue2.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${issue2.keys.length>1?"ներ":""}. ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${withDefiniteArticle(issue2.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${withDefiniteArticle(issue2.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};var init_hy=__esm(()=>{init_util()});function id_default(){return{localeError:error19()}}var error19=()=>{let Sizable={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;return`Input tidak valid: diharapkan ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: diharapkan ${issue2.origin??"value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: diharapkan ${issue2.origin??"value"} menjadi ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`String tidak valid: harus dimulai dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak valid: harus berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak valid: harus menyertakan "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak valid: harus sesuai pola ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${issue2.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${issue2.origin}`;default:return"Input tidak valid"}}};var init_id=__esm(()=>{init_util()});function is_default(){return{localeError:error20()}}var error20=()=>{let Sizable={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},TypeDictionary={nan:"NaN",number:"númer",array:"fylki"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue2.expected}`;return`Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue2.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Of stórt: gert er ráð fyrir að ${issue2.origin??"gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${issue2.origin??"gildi"} sé ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Of lítið: gert er ráð fyrir að ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Of lítið: gert er ráð fyrir að ${issue2.origin} sé ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ógildur strengur: verður að byrja á "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ógildur strengur: verður að enda á "${_issue.suffix}"`;if(_issue.format==="includes")return`Ógildur strengur: verður að innihalda "${_issue.includes}"`;if(_issue.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;return`Rangt ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${issue2.divisor}`;case"unrecognized_keys":return`Óþekkt ${issue2.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${issue2.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${issue2.origin}`;default:return"Rangt gildi"}}};var init_is=__esm(()=>{init_util()});function it_default(){return{localeError:error21()}}var error21=()=>{let Sizable={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"numero",array:"vettore"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;return`Input non valido: atteso ${expected}, ricevuto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;return`Opzione non valida: atteso uno tra ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Troppo grande: ${issue2.origin??"valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementi"}`;return`Troppo grande: ${issue2.origin??"valore"} deve essere ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Stringa non valida: deve iniziare con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Stringa non valida: deve terminare con "${_issue.suffix}"`;if(_issue.format==="includes")return`Stringa non valida: deve includere "${_issue.includes}"`;if(_issue.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${issue2.divisor}`;case"unrecognized_keys":return`Chiav${issue2.keys.length>1?"i":"e"} non riconosciut${issue2.keys.length>1?"e":"a"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${issue2.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${issue2.origin}`;default:return"Input non valido"}}};var init_it=__esm(()=>{init_util()});function ja_default(){return{localeError:error22()}}var error22=()=>{let Sizable={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},TypeDictionary={nan:"NaN",number:"数値",array:"配列"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`無効な入力: instanceof ${issue2.expected}が期待されましたが、${received}が入力されました`;return`無効な入力: ${expected}が期待されましたが、${received}が入力されました`}case"invalid_value":if(issue2.values.length===1)return`無効な入力: ${stringifyPrimitive(issue2.values[0])}が期待されました`;return`無効な選択: ${joinValues(issue2.values,"、")}のいずれかである必要があります`;case"too_big":{let adj=issue2.inclusive?"以下である":"より小さい",sizing=getSizing(issue2.origin);if(sizing)return`大きすぎる値: ${issue2.origin??"値"}は${issue2.maximum.toString()}${sizing.unit??"要素"}${adj}必要があります`;return`大きすぎる値: ${issue2.origin??"値"}は${issue2.maximum.toString()}${adj}必要があります`}case"too_small":{let adj=issue2.inclusive?"以上である":"より大きい",sizing=getSizing(issue2.origin);if(sizing)return`小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${sizing.unit}${adj}必要があります`;return`小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${adj}必要があります`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`無効な文字列: "${_issue.prefix}"で始まる必要があります`;if(_issue.format==="ends_with")return`無効な文字列: "${_issue.suffix}"で終わる必要があります`;if(_issue.format==="includes")return`無効な文字列: "${_issue.includes}"を含む必要があります`;if(_issue.format==="regex")return`無効な文字列: パターン${_issue.pattern}に一致する必要があります`;return`無効な${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`無効な数値: ${issue2.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${issue2.keys.length>1?"群":""}: ${joinValues(issue2.keys,"、")}`;case"invalid_key":return`${issue2.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${issue2.origin}内の無効な値`;default:return"無効な入力"}}};var init_ja=__esm(()=>{init_util()});function ka_default(){return{localeError:error23()}}var error23=()=>{let Sizable={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},TypeDictionary={nan:"NaN",number:"რიცხვი",string:"სტრინგი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${issue2.expected}, მიღებული ${received}`;return`არასწორი შეყვანა: მოსალოდნელი ${expected}, მიღებული ${received}`}case"invalid_value":if(issue2.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue2.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue2.values,"|")}-დან`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ზედმეტად დიდი: მოსალოდნელი ${issue2.origin??"მნიშვნელობა"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${issue2.origin??"მნიშვნელობა"} იყოს ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} იყოს ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;if(_issue.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;if(_issue.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;if(_issue.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;return`არასწორი ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${issue2.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${issue2.keys.length>1?"ები":"ი"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${issue2.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${issue2.origin}-ში`;default:return"არასწორი შეყვანა"}}};var init_ka=__esm(()=>{init_util()});function km_default(){return{localeError:error24()}}var error24=()=>{let Sizable={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},TypeDictionary={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue2.expected} ប៉ុន្តែទទួលបាន ${received}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`}case"invalid_value":if(issue2.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue2.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ធំពេក៖ ត្រូវការ ${issue2.origin??"តម្លៃ"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${issue2.origin??"តម្លៃ"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;if(_issue.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;if(_issue.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;if(_issue.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;return`មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue2.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};var init_km=__esm(()=>{init_util()});function kh_default(){return km_default()}var init_kh=__esm(()=>{init_km()});function ko_default(){return{localeError:error25()}}var error25=()=>{let Sizable={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`잘못된 입력: 예상 타입은 instanceof ${issue2.expected}, 받은 타입은 ${received}입니다`;return`잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`}case"invalid_value":if(issue2.values.length===1)return`잘못된 입력: 값은 ${stringifyPrimitive(issue2.values[0])} 이어야 합니다`;return`잘못된 옵션: ${joinValues(issue2.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let adj=issue2.inclusive?"이하":"미만",suffix=adj==="미만"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue2.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue2.origin??"값"}이 너무 큽니다: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"값"}이 너무 큽니다: ${issue2.maximum.toString()} ${adj}${suffix}`}case"too_small":{let adj=issue2.inclusive?"이상":"초과",suffix=adj==="이상"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue2.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue2.origin??"값"}이 너무 작습니다: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"값"}이 너무 작습니다: ${issue2.minimum.toString()} ${adj}${suffix}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;if(_issue.format==="ends_with")return`잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;if(_issue.format==="includes")return`잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;if(_issue.format==="regex")return`잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`잘못된 숫자: ${issue2.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`잘못된 키: ${issue2.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${issue2.origin}`;default:return"잘못된 입력"}}};var init_ko=__esm(()=>{init_util()});function getUnitTypeFromNumber(number2){let abs=Math.abs(number2),last=abs%10,last2=abs%100;if(last2>=11&&last2<=19||last===0)return"many";if(last===1)return"one";return"few"}function lt_default(){return{localeError:error26()}}var capitalizeFirstCharacter=(text)=>{return text.charAt(0).toUpperCase()+text.slice(1)},error26=()=>{let Sizable={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function getSizing(origin,unitType,inclusive,targetShouldBe){let result=Sizable[origin]??null;if(result===null)return result;return{unit:result.unit[unitType],verb:result.verb[targetShouldBe][inclusive?"inclusive":"notInclusive"]}}let FormatDictionary={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},TypeDictionary={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Gautas tipas ${received}, o tikėtasi - instanceof ${issue2.expected}`;return`Gautas tipas ${received}, o tikėtasi - ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Privalo būti ${stringifyPrimitive(issue2.values[0])}`;return`Privalo būti vienas iš ${joinValues(issue2.values,"|")} pasirinkimų`;case"too_big":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.maximum)),issue2.inclusive??!1,"smaller");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit??"elementų"}`;let adj=issue2.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi būti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`}case"too_small":{let origin=TypeDictionary[issue2.origin]??issue2.origin,sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.minimum)),issue2.inclusive??!1,"bigger");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit??"elementų"}`;let adj=issue2.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi būti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Eilutė privalo prasidėti "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Eilutė privalo pasibaigti "${_issue.suffix}"`;if(_issue.format==="includes")return`Eilutė privalo įtraukti "${_issue.includes}"`;if(_issue.format==="regex")return`Eilutė privalo atitikti ${_issue.pattern}`;return`Neteisingas ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Skaičius privalo būti ${issue2.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${issue2.keys.length>1?"i":"as"} rakt${issue2.keys.length>1?"ai":"as"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let origin=TypeDictionary[issue2.origin]??issue2.origin;return`${capitalizeFirstCharacter(origin??issue2.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};var init_lt=__esm(()=>{init_util()});function mk_default(){return{localeError:error27()}}var error27=()=>{let Sizable={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},TypeDictionary={nan:"NaN",number:"број",array:"низа"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Грешен внес: се очекува instanceof ${issue2.expected}, примено ${received}`;return`Грешен внес: се очекува ${expected}, примено ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Грешана опција: се очекува една ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Премногу голем: се очекува ${issue2.origin??"вредноста"} да има ${adj}${issue2.maximum.toString()} ${sizing.unit??"елементи"}`;return`Премногу голем: се очекува ${issue2.origin??"вредноста"} да биде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Премногу мал: се очекува ${issue2.origin} да има ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Премногу мал: се очекува ${issue2.origin} да биде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неважечка низа: мора да започнува со "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неважечка низа: мора да завршува со "${_issue.suffix}"`;if(_issue.format==="includes")return`Неважечка низа: мора да вклучува "${_issue.includes}"`;if(_issue.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${issue2.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${issue2.origin}`;default:return"Грешен внес"}}};var init_mk=__esm(()=>{init_util()});function ms_default(){return{localeError:error28()}}var error28=()=>{let Sizable={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"nombor"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;return`Input tidak sah: dijangka ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: dijangka ${issue2.origin??"nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: dijangka ${issue2.origin??"nilai"} adalah ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`String tidak sah: mesti bermula dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak sah: mesti mengandungi "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${issue2.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${issue2.origin}`;default:return"Input tidak sah"}}};var init_ms=__esm(()=>{init_util()});function nl_default(){return{localeError:error29()}}var error29=()=>{let Sizable={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},TypeDictionary={nan:"NaN",number:"getal"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;return`Ongeldige invoer: verwacht ${expected}, ontving ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;return`Ongeldige optie: verwacht één van ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin),longName=issue2.origin==="date"?"laat":issue2.origin==="string"?"lang":"groot";if(sizing)return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementen"} ${sizing.verb}`;return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} is`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin),shortName=issue2.origin==="date"?"vroeg":issue2.origin==="string"?"kort":"klein";if(sizing)return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;if(_issue.format==="includes")return`Ongeldige tekst: moet "${_issue.includes}" bevatten`;if(_issue.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;return`Ongeldig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${issue2.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${issue2.origin}`;default:return"Ongeldige invoer"}}};var init_nl=__esm(()=>{init_util()});function no_default(){return{localeError:error30()}}var error30=()=>{let Sizable={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"tall",array:"liste"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;return`Ugyldig input: forventet ${expected}, fikk ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldig valg: forventet en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`For stor(t): forventet ${issue2.origin??"value"} til å ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor(t): forventet ${issue2.origin??"value"} til å ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: må starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: må ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: må inneholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: må matche mønsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${issue2.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${issue2.origin}`;default:return"Ugyldig input"}}};var init_no=__esm(()=>{init_util()});function ota_default(){return{localeError:error31()}}var error31=()=>{let Sizable={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},TypeDictionary={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Fâsit giren: umulan instanceof ${issue2.expected}, alınan ${received}`;return`Fâsit giren: umulan ${expected}, alınan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Fâsit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;return`Fâsit tercih: mûteberler ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Fazla büyük: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} olmalıydı.`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;return`Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmalıydı.`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Fâsit metin: "${_issue.prefix}" ile başlamalı.`;if(_issue.format==="ends_with")return`Fâsit metin: "${_issue.suffix}" ile bitmeli.`;if(_issue.format==="includes")return`Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;if(_issue.format==="regex")return`Fâsit metin: ${_issue.pattern} nakşına uymalı.`;return`Fâsit ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Fâsit sayı: ${issue2.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${issue2.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};var init_ota=__esm(()=>{init_util()});function ps_default(){return{localeError:error32()}}var error32=()=>{let Sizable={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},TypeDictionary={nan:"NaN",number:"عدد",array:"ارې"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ناسم ورودي: باید instanceof ${issue2.expected} وای, مګر ${received} ترلاسه شو`;return`ناسم ورودي: باید ${expected} وای, مګر ${received} ترلاسه شو`}case"invalid_value":if(issue2.values.length===1)return`ناسم ورودي: باید ${stringifyPrimitive(issue2.values[0])} وای`;return`ناسم انتخاب: باید یو له ${joinValues(issue2.values,"|")} څخه وای`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`ډیر لوی: ${issue2.origin??"ارزښت"} باید ${adj}${issue2.maximum.toString()} ${sizing.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${issue2.origin??"ارزښت"} باید ${adj}${issue2.maximum.toString()} وي`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} ولري`;return`ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} وي`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;if(_issue.format==="ends_with")return`ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;if(_issue.format==="includes")return`ناسم متن: باید "${_issue.includes}" ولري`;if(_issue.format==="regex")return`ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;return`${FormatDictionary[_issue.format]??issue2.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${issue2.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${issue2.keys.length>1?"کلیډونه":"کلیډ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${issue2.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${issue2.origin} کې`;default:return"ناسمه ورودي"}}};var init_ps=__esm(()=>{init_util()});function pl_default(){return{localeError:error33()}}var error33=()=>{let Sizable={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},TypeDictionary={nan:"NaN",number:"liczba",array:"tablica"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Za duża wartość: oczekiwano, że ${issue2.origin??"wartość"} będzie mieć ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${issue2.origin??"wartość"} będzie wynosić ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Za mała wartość: oczekiwano, że ${issue2.origin??"wartość"} będzie mieć ${adj}${issue2.minimum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${issue2.origin??"wartość"} będzie wynosić ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;if(_issue.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;if(_issue.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;return`Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${issue2.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${issue2.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${issue2.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};var init_pl=__esm(()=>{init_util()});function pt_default(){return{localeError:error34()}}var error34=()=>{let Sizable={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},TypeDictionary={nan:"NaN",number:"número",null:"nulo"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Tipo inválido: esperado instanceof ${issue2.expected}, recebido ${received}`;return`Tipo inválido: esperado ${expected}, recebido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inválida: esperado ${stringifyPrimitive(issue2.values[0])}`;return`Opção inválida: esperada uma das ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Muito grande: esperado que ${issue2.origin??"valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Muito grande: esperado que ${issue2.origin??"valor"} fosse ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Texto inválido: deve começar com "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Texto inválido: deve terminar com "${_issue.suffix}"`;if(_issue.format==="includes")return`Texto inválido: deve incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Chave${issue2.keys.length>1?"s":""} desconhecida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chave inválida em ${issue2.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${issue2.origin}`;default:return"Campo inválido"}}};var init_pt=__esm(()=>{init_util()});function getRussianPlural(count,one,few,many){let absCount=Math.abs(count),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function ru_default(){return{localeError:error35()}}var error35=()=>{let Sizable={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},TypeDictionary={nan:"NaN",number:"число",array:"массив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Неверный ввод: ожидалось instanceof ${issue2.expected}, получено ${received}`;return`Неверный ввод: ожидалось ${expected}, получено ${received}`}case"invalid_value":if(issue2.values.length===1)return`Неверный ввод: ожидалось ${stringifyPrimitive(issue2.values[0])}`;return`Неверный вариант: ожидалось одно из ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing){let maxValue=Number(issue2.maximum),unit=getRussianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком большое значение: ожидалось, что ${issue2.origin??"значение"} будет иметь ${adj}${issue2.maximum.toString()} ${unit}`}return`Слишком большое значение: ожидалось, что ${issue2.origin??"значение"} будет ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing){let minValue=Number(issue2.minimum),unit=getRussianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком маленькое значение: ожидалось, что ${issue2.origin} будет иметь ${adj}${issue2.minimum.toString()} ${unit}`}return`Слишком маленькое значение: ожидалось, что ${issue2.origin} будет ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неверная строка: должна начинаться с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неверная строка: должна заканчиваться на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неверная строка: должна содержать "${_issue.includes}"`;if(_issue.format==="regex")return`Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;return`Неверный ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${issue2.divisor}`;case"unrecognized_keys":return`Нераспознанн${issue2.keys.length>1?"ые":"ый"} ключ${issue2.keys.length>1?"и":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${issue2.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${issue2.origin}`;default:return"Неверные входные данные"}}};var init_ru=__esm(()=>{init_util()});function sl_default(){return{localeError:error36()}}var error36=()=>{let Sizable={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},TypeDictionary={nan:"NaN",number:"število",array:"tabela"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Neveljaven vnos: pričakovano instanceof ${issue2.expected}, prejeto ${received}`;return`Neveljaven vnos: pričakovano ${expected}, prejeto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neveljaven vnos: pričakovano ${stringifyPrimitive(issue2.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Preveliko: pričakovano, da bo ${issue2.origin??"vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${issue2.origin??"vrednost"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Premajhno: pričakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Premajhno: pričakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Neveljaven niz: mora se začeti z "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neveljaven niz: mora se končati z "${_issue.suffix}"`;if(_issue.format==="includes")return`Neveljaven niz: mora vsebovati "${_issue.includes}"`;if(_issue.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;return`Neveljaven ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznan${issue2.keys.length>1?"i ključi":" ključ"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${issue2.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${issue2.origin}`;default:return"Neveljaven vnos"}}};var init_sl=__esm(()=>{init_util()});function sv_default(){return{localeError:error37()}}var error37=()=>{let Sizable={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},TypeDictionary={nan:"NaN",number:"antal",array:"lista"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ogiltig inmatning: förväntat instanceof ${issue2.expected}, fick ${received}`;return`Ogiltig inmatning: förväntat ${expected}, fick ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ogiltig inmatning: förväntat ${stringifyPrimitive(issue2.values[0])}`;return`Ogiltigt val: förväntade en av ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`För stor(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`För stor(t): förväntat ${issue2.origin??"värdet"} att ha ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`För lite(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`För lite(t): förväntade ${issue2.origin??"värdet"} att ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ogiltig sträng: måste börja med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ogiltig sträng: måste sluta med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ogiltig sträng: måste innehålla "${_issue.includes}"`;if(_issue.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;return`Ogiltig(t) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${issue2.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${issue2.origin??"värdet"}`;default:return"Ogiltig input"}}};var init_sv=__esm(()=>{init_util()});function ta_default(){return{localeError:error38()}}var error38=()=>{let Sizable={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue2.expected}, பெறப்பட்டது ${received}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`}case"invalid_value":if(issue2.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue2.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue2.values,"|")} இல் ஒன்று`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin??"மதிப்பு"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue2.origin??"மதிப்பு"} ${adj}${issue2.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;if(_issue.format==="ends_with")return`தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;if(_issue.format==="includes")return`தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;if(_issue.format==="regex")return`தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`தவறான எண்: ${issue2.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${issue2.keys.length>1?"கள்":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${issue2.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};var init_ta=__esm(()=>{init_util()});function th_default(){return{localeError:error39()}}var error39=()=>{let Sizable={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},TypeDictionary={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue2.expected} แต่ได้รับ ${received}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`}case"invalid_value":if(issue2.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue2.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"ไม่เกิน":"น้อยกว่า",sizing=getSizing(issue2.origin);if(sizing)return`เกินกำหนด: ${issue2.origin??"ค่า"} ควรมี${adj} ${issue2.maximum.toString()} ${sizing.unit??"รายการ"}`;return`เกินกำหนด: ${issue2.origin??"ค่า"} ควรมี${adj} ${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?"อย่างน้อย":"มากกว่า",sizing=getSizing(issue2.origin);if(sizing)return`น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()} ${sizing.unit}`;return`น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;if(_issue.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;if(_issue.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;if(_issue.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;return`รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue2.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${issue2.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${issue2.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};var init_th=__esm(()=>{init_util()});function tr_default(){return{localeError:error40()}}var error40=()=>{let Sizable={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Geçersiz değer: beklenen instanceof ${issue2.expected}, alınan ${received}`;return`Geçersiz değer: beklenen ${expected}, alınan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Geçersiz değer: beklenen ${stringifyPrimitive(issue2.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Çok büyük: beklenen ${issue2.origin??"değer"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"öğe"}`;return`Çok büyük: beklenen ${issue2.origin??"değer"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Geçersiz metin: "${_issue.prefix}" ile başlamalı`;if(_issue.format==="ends_with")return`Geçersiz metin: "${_issue.suffix}" ile bitmeli`;if(_issue.format==="includes")return`Geçersiz metin: "${_issue.includes}" içermeli`;if(_issue.format==="regex")return`Geçersiz metin: ${_issue.pattern} desenine uymalı`;return`Geçersiz ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Geçersiz sayı: ${issue2.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${issue2.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};var init_tr=__esm(()=>{init_util()});function uk_default(){return{localeError:error41()}}var error41=()=>{let Sizable={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},TypeDictionary={nan:"NaN",number:"число",array:"масив"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Неправильні вхідні дані: очікується instanceof ${issue2.expected}, отримано ${received}`;return`Неправильні вхідні дані: очікується ${expected}, отримано ${received}`}case"invalid_value":if(issue2.values.length===1)return`Неправильні вхідні дані: очікується ${stringifyPrimitive(issue2.values[0])}`;return`Неправильна опція: очікується одне з ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Занадто велике: очікується, що ${issue2.origin??"значення"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"елементів"}`;return`Занадто велике: очікується, що ${issue2.origin??"значення"} буде ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Занадто мале: очікується, що ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Занадто мале: очікується, що ${issue2.origin} буде ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Неправильний рядок: повинен починатися з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неправильний рядок: повинен містити "${_issue.includes}"`;if(_issue.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;return`Неправильний ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${issue2.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${issue2.keys.length>1?"і":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${issue2.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${issue2.origin}`;default:return"Неправильні вхідні дані"}}};var init_uk=__esm(()=>{init_util()});function ua_default(){return uk_default()}var init_ua=__esm(()=>{init_uk()});function ur_default(){return{localeError:error42()}}var error42=()=>{let Sizable={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},TypeDictionary={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`غلط ان پٹ: instanceof ${issue2.expected} متوقع تھا، ${received} موصول ہوا`;return`غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`}case"invalid_value":if(issue2.values.length===1)return`غلط ان پٹ: ${stringifyPrimitive(issue2.values[0])} متوقع تھا`;return`غلط آپشن: ${joinValues(issue2.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`بہت بڑا: ${issue2.origin??"ویلیو"} کے ${adj}${issue2.maximum.toString()} ${sizing.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${issue2.origin??"ویلیو"} کا ${adj}${issue2.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`بہت چھوٹا: ${issue2.origin} کے ${adj}${issue2.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${issue2.origin} کا ${adj}${issue2.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;if(_issue.format==="ends_with")return`غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;if(_issue.format==="includes")return`غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;if(_issue.format==="regex")return`غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;return`غلط ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`غلط نمبر: ${issue2.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${issue2.keys.length>1?"ز":""}: ${joinValues(issue2.keys,"، ")}`;case"invalid_key":return`${issue2.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${issue2.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};var init_ur=__esm(()=>{init_util()});function uz_default(){return{localeError:error43()}}var error43=()=>{let Sizable={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},TypeDictionary={nan:"NaN",number:"raqam",array:"massiv"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;return`Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Noto‘g‘ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;if(_issue.format==="ends_with")return`Noto‘g‘ri satr: "${_issue.suffix}" bilan tugashi kerak`;if(_issue.format==="includes")return`Noto‘g‘ri satr: "${_issue.includes}" ni o‘z ichiga olishi kerak`;if(_issue.format==="regex")return`Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${issue2.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${issue2.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};var init_uz=__esm(()=>{init_util()});function vi_default(){return{localeError:error44()}}var error44=()=>{let Sizable={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},TypeDictionary={nan:"NaN",number:"số",array:"mảng"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${issue2.expected}, nhận được ${received}`;return`Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`}case"invalid_value":if(issue2.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue2.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Quá lớn: mong đợi ${issue2.origin??"giá trị"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"phần tử"}`;return`Quá lớn: mong đợi ${issue2.origin??"giá trị"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Quá nhỏ: mong đợi ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Quá nhỏ: mong đợi ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;if(_issue.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;if(_issue.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${issue2.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${issue2.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${issue2.origin}`;default:return"Đầu vào không hợp lệ"}}};var init_vi=__esm(()=>{init_util()});function zh_CN_default(){return{localeError:error45()}}var error45=()=>{let Sizable={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},TypeDictionary={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`无效输入:期望 instanceof ${issue2.expected},实际接收 ${received}`;return`无效输入:期望 ${expected},实际接收 ${received}`}case"invalid_value":if(issue2.values.length===1)return`无效输入:期望 ${stringifyPrimitive(issue2.values[0])}`;return`无效选项:期望以下之一 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`数值过大:期望 ${issue2.origin??"值"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"个元素"}`;return`数值过大:期望 ${issue2.origin??"值"} ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`数值过小:期望 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`数值过小:期望 ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`无效字符串:必须以 "${_issue.prefix}" 开头`;if(_issue.format==="ends_with")return`无效字符串:必须以 "${_issue.suffix}" 结尾`;if(_issue.format==="includes")return`无效字符串:必须包含 "${_issue.includes}"`;if(_issue.format==="regex")return`无效字符串:必须满足正则表达式 ${_issue.pattern}`;return`无效${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`无效数字:必须是 ${issue2.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${issue2.origin} 中包含无效值(value)`;default:return"无效输入"}}};var init_zh_CN=__esm(()=>{init_util()});function zh_TW_default(){return{localeError:error46()}}var error46=()=>{let Sizable={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},TypeDictionary={nan:"NaN"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`無效的輸入值:預期為 instanceof ${issue2.expected},但收到 ${received}`;return`無效的輸入值:預期為 ${expected},但收到 ${received}`}case"invalid_value":if(issue2.values.length===1)return`無效的輸入值:預期為 ${stringifyPrimitive(issue2.values[0])}`;return`無效的選項:預期為以下其中之一 ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`數值過大:預期 ${issue2.origin??"值"} 應為 ${adj}${issue2.maximum.toString()} ${sizing.unit??"個元素"}`;return`數值過大:預期 ${issue2.origin??"值"} 應為 ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`數值過小:預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`數值過小:預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`無效的字串:必須以 "${_issue.prefix}" 開頭`;if(_issue.format==="ends_with")return`無效的字串:必須以 "${_issue.suffix}" 結尾`;if(_issue.format==="includes")return`無效的字串:必須包含 "${_issue.includes}"`;if(_issue.format==="regex")return`無效的字串:必須符合格式 ${_issue.pattern}`;return`無效的 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`無效的數字:必須為 ${issue2.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${issue2.keys.length>1?"們":""}:${joinValues(issue2.keys,"、")}`;case"invalid_key":return`${issue2.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${issue2.origin} 中有無效的值`;default:return"無效的輸入值"}}};var init_zh_TW=__esm(()=>{init_util()});function yo_default(){return{localeError:error47()}}var error47=()=>{let Sizable={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},TypeDictionary={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(issue2)=>{switch(issue2.code){case"invalid_type":{let expected=TypeDictionary[issue2.expected]??issue2.expected,receivedType=parsedType(issue2.input),received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${issue2.expected}, àmọ̀ a rí ${received}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${expected}, àmọ̀ a rí ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue2.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);if(sizing)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${issue2.origin??"iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue2.maximum}`}case"too_small":{let adj=issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);if(sizing)return`Kéré ju: a ní láti jẹ́ pé ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;return`Kéré ju: a ní láti jẹ́ ${adj}${issue2.minimum}`}case"invalid_format":{let _issue=issue2;if(_issue.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`;if(_issue.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`;if(_issue.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;return`Aṣìṣe: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue2.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${issue2.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${issue2.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};var init_yo=__esm(()=>{init_util()});var exports_locales={};__export(exports_locales,{zhTW:()=>zh_TW_default,zhCN:()=>zh_CN_default,yo:()=>yo_default,vi:()=>vi_default,uz:()=>uz_default,ur:()=>ur_default,uk:()=>uk_default,ua:()=>ua_default,tr:()=>tr_default,th:()=>th_default,ta:()=>ta_default,sv:()=>sv_default,sl:()=>sl_default,ru:()=>ru_default,pt:()=>pt_default,ps:()=>ps_default,pl:()=>pl_default,ota:()=>ota_default,no:()=>no_default,nl:()=>nl_default,ms:()=>ms_default,mk:()=>mk_default,lt:()=>lt_default,ko:()=>ko_default,km:()=>km_default,kh:()=>kh_default,ka:()=>ka_default,ja:()=>ja_default,it:()=>it_default,is:()=>is_default,id:()=>id_default,hy:()=>hy_default,hu:()=>hu_default,he:()=>he_default,frCA:()=>fr_CA_default,fr:()=>fr_default,fi:()=>fi_default,fa:()=>fa_default,es:()=>es_default,eo:()=>eo_default,en:()=>en_default,de:()=>de_default,da:()=>da_default,cs:()=>cs_default,ca:()=>ca_default,bg:()=>bg_default,be:()=>be_default,az:()=>az_default,ar:()=>ar_default});var init_locales=__esm(()=>{init_ar();init_az();init_be();init_bg();init_ca();init_cs();init_da();init_de();init_en();init_eo();init_es();init_fa();init_fi();init_fr();init_fr_CA();init_he();init_hu();init_hy();init_id();init_is();init_it();init_ja();init_ka();init_kh();init_km();init_ko();init_lt();init_mk();init_ms();init_nl();init_no();init_ota();init_ps();init_pl();init_pt();init_ru();init_sl();init_sv();init_ta();init_th();init_tr();init_ua();init_uk();init_ur();init_uz();init_vi();init_zh_CN();init_zh_TW();init_yo()});class $ZodRegistry{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];if(this._map.set(schema,meta),meta&&typeof meta==="object"&&"id"in meta)this._idmap.set(meta.id,schema);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);if(meta&&typeof meta==="object"&&"id"in meta)this._idmap.delete(meta.id);return this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry(){return new $ZodRegistry}var _a,$output,$input,globalRegistry;var init_registries=__esm(()=>{$output=Symbol("ZodOutput"),$input=Symbol("ZodInput");(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry});function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:!0,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:!0,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType;return new Class2({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...normalizeParams(hasRest?_params:_paramsOrRest)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value,params){return new Class2({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn2){return new Class2({type:"transform",transform:fn2})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn2,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn:fn2,...norm})}function _refine(Class2,fn2,_params){return new Class2({type:"custom",check:"custom",fn:fn2,...normalizeParams(_params)})}function _superRefine(fn2){let ch=_check((payload)=>{return payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn2(payload.value,payload)});return ch}function _check(fn2,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn2,ch}function describe(description){let ch=new $ZodCheck({check:"describe"});return ch._zod.onattach=[(inst)=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch._zod.check=()=>{},ch}function meta(metadata){let ch=new $ZodCheck({check:"meta"});return ch._zod.onattach=[(inst)=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch._zod.check=()=>{},ch}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive")truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v),falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,stringSchema=new(Classes.String??$ZodString)({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data))return!0;else if(falsySet.has(data))return!1;else return payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:!1}),{}},reverseTransform:(input,_payload)=>{if(input===!0)return truthyArray[0]||"true";else return falsyArray[0]||"false"},error:params.error});return codec}function _stringFormat(Class2,format,fnOrRegex,_params={}){let params=normalizeParams(_params),def={...normalizeParams(_params),check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp)def.pattern=fnOrRegex;return new Class2(def)}var TimePrecision;var init_api=__esm(()=>{init_checks();init_registries();init_schemas();init_util();TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process2(schema,ctx,_params={path:[],schemaPath:[]}){var _a2;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen){if(seen.count++,_params.schemaPath.includes(schema))seen.cycle=_params.path;return seen.schema}let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;process2(parent,ctx,params),ctx.seen.get(parent).isParent=!0}}let meta2=ctx.metadataRegistry.get(schema);if(meta2)Object.assign(result.schema,meta2);if(ctx.io==="input"&&isTransforming(schema))delete result.schema.examples,delete result.schema.default;if(ctx.io==="input"&&result.schema._prefault)(_a2=result.schema).default??(_a2.default=result.schema._prefault);return delete result.schema._prefault,ctx.seen.get(schema).schema}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=(entry)=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??((id2)=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:"#"};let defUriPrefix=`${"#"}/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=(entry)=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);if(seen.def={...seen.schema},defId)seen.defId=defId;let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
157
157
 
158
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema);if(Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var init_to_json_schema=__esm(()=>{init_registries()});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;process2(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time")delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(regexes.length>1)json.allOf=[...regexes.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}},numberProcessor=(schema,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";if(typeof exclusiveMinimum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json.minimum=minimum,typeof exclusiveMinimum==="number"&&ctx.target!=="draft-04")if(exclusiveMinimum>=minimum)delete json.minimum;else delete json.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json.maximum=maximum,typeof exclusiveMaximum==="number"&&ctx.target!=="draft-04")if(exclusiveMaximum<=maximum)delete json.maximum;else delete json.exclusiveMaximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(ctx.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file.minLength=minimum;if(maximum!==void 0)file.maxLength=maximum;if(mime)if(mime.length===1)file.contentMediaType=mime[0],Object.assign(_json,file);else Object.assign(_json,file),_json.anyOf=mime.map((m)=>({contentMediaType:m}));else Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(ctx.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,rest)json.items=rest}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(json.minItems=prefixItems.length,!rest)json.maxItems=prefixItems.length}else if(json.items=prefixItems,rest)json.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum},recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12")json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,innerType=ctx.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors;var init_json_schema_processors=__esm(()=>{init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}});class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}var init_json_schema_generator=__esm(()=>{init_json_schema_processors();init_to_json_schema()});var exports_json_schema={};var init_json_schema=()=>{};var exports_core2={};__export(exports_core2,{version:()=>version,util:()=>exports_util,treeifyError:()=>treeifyError,toJSONSchema:()=>toJSONSchema,toDotPath:()=>toDotPath,safeParseAsync:()=>safeParseAsync,safeParse:()=>safeParse,safeEncodeAsync:()=>safeEncodeAsync,safeEncode:()=>safeEncode,safeDecodeAsync:()=>safeDecodeAsync,safeDecode:()=>safeDecode,registry:()=>registry,regexes:()=>exports_regexes,process:()=>process2,prettifyError:()=>prettifyError,parseAsync:()=>parseAsync,parse:()=>parse,meta:()=>meta,locales:()=>exports_locales,isValidJWT:()=>isValidJWT,isValidBase64URL:()=>isValidBase64URL,isValidBase64:()=>isValidBase64,initializeContext:()=>initializeContext,globalRegistry:()=>globalRegistry,globalConfig:()=>globalConfig,formatError:()=>formatError,flattenError:()=>flattenError,finalize:()=>finalize,extractDefs:()=>extractDefs,encodeAsync:()=>encodeAsync,encode:()=>encode,describe:()=>describe,decodeAsync:()=>decodeAsync,decode:()=>decode,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,config:()=>config,clone:()=>clone,_xor:()=>_xor,_xid:()=>_xid,_void:()=>_void,_uuidv7:()=>_uuidv7,_uuidv6:()=>_uuidv6,_uuidv4:()=>_uuidv4,_uuid:()=>_uuid,_url:()=>_url,_uppercase:()=>_uppercase,_unknown:()=>_unknown,_union:()=>_union,_undefined:()=>_undefined2,_ulid:()=>_ulid,_uint64:()=>_uint64,_uint32:()=>_uint32,_tuple:()=>_tuple,_trim:()=>_trim,_transform:()=>_transform,_toUpperCase:()=>_toUpperCase,_toLowerCase:()=>_toLowerCase,_templateLiteral:()=>_templateLiteral,_symbol:()=>_symbol,_superRefine:()=>_superRefine,_success:()=>_success,_stringbool:()=>_stringbool,_stringFormat:()=>_stringFormat,_string:()=>_string,_startsWith:()=>_startsWith,_slugify:()=>_slugify,_size:()=>_size,_set:()=>_set,_safeParseAsync:()=>_safeParseAsync,_safeParse:()=>_safeParse,_safeEncodeAsync:()=>_safeEncodeAsync,_safeEncode:()=>_safeEncode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeDecode:()=>_safeDecode,_regex:()=>_regex,_refine:()=>_refine,_record:()=>_record,_readonly:()=>_readonly,_property:()=>_property,_promise:()=>_promise,_positive:()=>_positive,_pipe:()=>_pipe,_parseAsync:()=>_parseAsync,_parse:()=>_parse,_overwrite:()=>_overwrite,_optional:()=>_optional,_number:()=>_number,_nullable:()=>_nullable,_null:()=>_null2,_normalize:()=>_normalize,_nonpositive:()=>_nonpositive,_nonoptional:()=>_nonoptional,_nonnegative:()=>_nonnegative,_never:()=>_never,_negative:()=>_negative,_nativeEnum:()=>_nativeEnum,_nanoid:()=>_nanoid,_nan:()=>_nan,_multipleOf:()=>_multipleOf,_minSize:()=>_minSize,_minLength:()=>_minLength,_min:()=>_gte,_mime:()=>_mime,_maxSize:()=>_maxSize,_maxLength:()=>_maxLength,_max:()=>_lte,_map:()=>_map,_mac:()=>_mac,_lte:()=>_lte,_lt:()=>_lt,_lowercase:()=>_lowercase,_literal:()=>_literal,_length:()=>_length,_lazy:()=>_lazy,_ksuid:()=>_ksuid,_jwt:()=>_jwt,_isoTime:()=>_isoTime,_isoDuration:()=>_isoDuration,_isoDateTime:()=>_isoDateTime,_isoDate:()=>_isoDate,_ipv6:()=>_ipv6,_ipv4:()=>_ipv4,_intersection:()=>_intersection,_int64:()=>_int64,_int32:()=>_int32,_int:()=>_int,_includes:()=>_includes,_guid:()=>_guid,_gte:()=>_gte,_gt:()=>_gt,_float64:()=>_float64,_float32:()=>_float32,_file:()=>_file,_enum:()=>_enum,_endsWith:()=>_endsWith,_encodeAsync:()=>_encodeAsync,_encode:()=>_encode,_emoji:()=>_emoji2,_email:()=>_email,_e164:()=>_e164,_discriminatedUnion:()=>_discriminatedUnion,_default:()=>_default,_decodeAsync:()=>_decodeAsync,_decode:()=>_decode,_date:()=>_date,_custom:()=>_custom,_cuid2:()=>_cuid2,_cuid:()=>_cuid,_coercedString:()=>_coercedString,_coercedNumber:()=>_coercedNumber,_coercedDate:()=>_coercedDate,_coercedBoolean:()=>_coercedBoolean,_coercedBigint:()=>_coercedBigint,_cidrv6:()=>_cidrv6,_cidrv4:()=>_cidrv4,_check:()=>_check,_catch:()=>_catch,_boolean:()=>_boolean,_bigint:()=>_bigint,_base64url:()=>_base64url,_base64:()=>_base64,_array:()=>_array,_any:()=>_any,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,JSONSchemaGenerator:()=>JSONSchemaGenerator,JSONSchema:()=>exports_json_schema,Doc:()=>Doc,$output:()=>$output,$input:()=>$input,$constructor:()=>$constructor,$brand:()=>$brand,$ZodXor:()=>$ZodXor,$ZodXID:()=>$ZodXID,$ZodVoid:()=>$ZodVoid,$ZodUnknown:()=>$ZodUnknown,$ZodUnion:()=>$ZodUnion,$ZodUndefined:()=>$ZodUndefined,$ZodUUID:()=>$ZodUUID,$ZodURL:()=>$ZodURL,$ZodULID:()=>$ZodULID,$ZodType:()=>$ZodType,$ZodTuple:()=>$ZodTuple,$ZodTransform:()=>$ZodTransform,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodSymbol:()=>$ZodSymbol,$ZodSuccess:()=>$ZodSuccess,$ZodStringFormat:()=>$ZodStringFormat,$ZodString:()=>$ZodString,$ZodSet:()=>$ZodSet,$ZodRegistry:()=>$ZodRegistry,$ZodRecord:()=>$ZodRecord,$ZodRealError:()=>$ZodRealError,$ZodReadonly:()=>$ZodReadonly,$ZodPromise:()=>$ZodPromise,$ZodPrefault:()=>$ZodPrefault,$ZodPipe:()=>$ZodPipe,$ZodOptional:()=>$ZodOptional,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodObject:()=>$ZodObject,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodNumber:()=>$ZodNumber,$ZodNullable:()=>$ZodNullable,$ZodNull:()=>$ZodNull,$ZodNonOptional:()=>$ZodNonOptional,$ZodNever:()=>$ZodNever,$ZodNanoID:()=>$ZodNanoID,$ZodNaN:()=>$ZodNaN,$ZodMap:()=>$ZodMap,$ZodMAC:()=>$ZodMAC,$ZodLiteral:()=>$ZodLiteral,$ZodLazy:()=>$ZodLazy,$ZodKSUID:()=>$ZodKSUID,$ZodJWT:()=>$ZodJWT,$ZodIntersection:()=>$ZodIntersection,$ZodISOTime:()=>$ZodISOTime,$ZodISODuration:()=>$ZodISODuration,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODate:()=>$ZodISODate,$ZodIPv6:()=>$ZodIPv6,$ZodIPv4:()=>$ZodIPv4,$ZodGUID:()=>$ZodGUID,$ZodFunction:()=>$ZodFunction,$ZodFile:()=>$ZodFile,$ZodExactOptional:()=>$ZodExactOptional,$ZodError:()=>$ZodError,$ZodEnum:()=>$ZodEnum,$ZodEncodeError:()=>$ZodEncodeError,$ZodEmoji:()=>$ZodEmoji,$ZodEmail:()=>$ZodEmail,$ZodE164:()=>$ZodE164,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodDefault:()=>$ZodDefault,$ZodDate:()=>$ZodDate,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCustom:()=>$ZodCustom,$ZodCodec:()=>$ZodCodec,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheck:()=>$ZodCheck,$ZodCatch:()=>$ZodCatch,$ZodCUID2:()=>$ZodCUID2,$ZodCUID:()=>$ZodCUID,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodBoolean:()=>$ZodBoolean,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBigInt:()=>$ZodBigInt,$ZodBase64URL:()=>$ZodBase64URL,$ZodBase64:()=>$ZodBase64,$ZodAsyncError:()=>$ZodAsyncError,$ZodArray:()=>$ZodArray,$ZodAny:()=>$ZodAny});var init_core2=__esm(()=>{init_util();init_regexes();init_locales();init_json_schema_processors();init_json_schema_generator();init_json_schema();init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_registries();init_api();init_to_json_schema()});var exports_checks2={};__export(exports_checks2,{uppercase:()=>_uppercase,trim:()=>_trim,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,regex:()=>_regex,property:()=>_property,positive:()=>_positive,overwrite:()=>_overwrite,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonnegative:()=>_nonnegative,negative:()=>_negative,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,maxSize:()=>_maxSize,maxLength:()=>_maxLength,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,length:()=>_length,includes:()=>_includes,gte:()=>_gte,gt:()=>_gt,endsWith:()=>_endsWith});var init_checks2=__esm(()=>{init_core2()});var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm(()=>{init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})});var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError(inst,mapper)},flatten:{value:(mapper)=>flattenError(inst,mapper)},addIssue:{value:(issue2)=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError,ZodRealError;var init_errors2=__esm(()=>{init_core2();init_core2();init_util();ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm(()=>{init_core2();init_errors2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)});var exports_schemas2={};__export(exports_schemas2,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,url:()=>url,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,transform:()=>transform,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,set:()=>set,refine:()=>refine,record:()=>record,readonly:()=>readonly,promise:()=>promise,preprocess:()=>preprocess,prefault:()=>prefault,pipe:()=>pipe,partialRecord:()=>partialRecord,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,nonoptional:()=>nonoptional,never:()=>never,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,meta:()=>meta2,map:()=>map,mac:()=>mac2,looseRecord:()=>looseRecord,looseObject:()=>looseObject,literal:()=>literal,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,function:()=>_function,float64:()=>float64,float32:()=>float32,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,codec:()=>codec,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIntersection:()=>ZodIntersection,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny});function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:/^https?$/,hostname:exports_regexes.domain,...exports_util.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",exports_regexes.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",exports_regexes.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...exports_util.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...exports_util.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest;return new ZodTuple({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util.normalizeParams(params)})}function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k=clone(keyType);return k._zod.values=void 0,new ZodRecord({type:"record",keyType:k,valueType,...exports_util.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...exports_util.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...exports_util.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...exports_util.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn2){return new ZodTransform({type:"transform",transform:fn2})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...exports_util.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn2){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn2,ch}function custom(fn2,_params){return _custom(ZodCustom,fn2??(()=>!0),_params)}function refine(fn2,_params={}){return _refine(ZodCustom,fn2,_params)}function superRefine(fn2){return _superRefine(fn2)}function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=(payload)=>{if(!(payload.value instanceof cls))payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn2,schema){return pipe(transform(fn2),schema)}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool=(...args2)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args2);var init_schemas2=__esm(()=>{init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>{return $ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks2)=>{return inst.clone(exports_util.mergeDefs(def,{checks:[...def.checks??[],...checks2.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},inst.with=inst.check,inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta2)=>{return reg.add(inst,meta2),inst},inst.parse=(data,params)=>parse3(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),inst.refine=(check,params)=>inst.check(refine(check,params)),inst.superRefine=(refinement)=>inst.check(superRefine(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite(fn2)),inst.optional=()=>optional(inst),inst.exactOptional=()=>exactOptional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=(params)=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=(arg)=>union([inst,arg]),inst.and=(arg)=>intersection(inst,arg),inst.transform=(tx)=>pipe(inst,transform(tx)),inst.default=(def2)=>_default2(inst,def2),inst.prefault=(def2)=>prefault(inst,def2),inst.catch=(params)=>_catch2(inst,params),inst.pipe=(target)=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst.apply=(fn2)=>fn2(inst),inst}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex(...args2)),inst.includes=(...args2)=>inst.check(_includes(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith(...args2)),inst.min=(...args2)=>inst.check(_minLength(...args2)),inst.max=(...args2)=>inst.check(_maxLength(...args2)),inst.length=(...args2)=>inst.check(_length(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase(params)),inst.uppercase=(params)=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args2)=>inst.check(_normalize(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase()),inst.slugify=()=>inst.check(_slugify())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=(params)=>inst.check(_email(ZodEmail,params)),inst.url=(params)=>inst.check(_url(ZodURL,params)),inst.jwt=(params)=>inst.check(_jwt(ZodJWT,params)),inst.emoji=(params)=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.uuid=(params)=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=(params)=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=(params)=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=(params)=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=(params)=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.cuid=(params)=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=(params)=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=(params)=>inst.check(_ulid(ZodULID,params)),inst.base64=(params)=>inst.check(_base64(ZodBase64,params)),inst.base64url=(params)=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=(params)=>inst.check(_xid(ZodXID,params)),inst.ksuid=(params)=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=(params)=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=(params)=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=(params)=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=(params)=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=(params)=>inst.check(_e164(ZodE164,params)),inst.datetime=(params)=>inst.check(datetime2(params)),inst.date=(params)=>inst.check(date2(params)),inst.time=(params)=>inst.check(time2(params)),inst.duration=(params)=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=(params)=>inst.check(int(params)),inst.safe=(params)=>inst.check(int(params)),inst.positive=(params)=>inst.check(_gt(0,params)),inst.nonnegative=(params)=>inst.check(_gte(0,params)),inst.negative=(params)=>inst.check(_lt(0,params)),inst.nonpositive=(params)=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=(params)=>inst.check(_gt(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>symbolProcessor(inst,ctx,json,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>undefinedProcessor(inst,ctx,json,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>voidProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),exports_util.defineLazy(inst,"shape",()=>{return def.shape}),inst.keyof=()=>_enum2(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util.merge(inst,other),inst.pick=(mask)=>exports_util.pick(inst,mask),inst.omit=(mask)=>exports_util.omit(inst,mask),inst.partial=(...args2)=>exports_util.partial(ZodOptional,inst,args2[0]),inst.required=(...args2)=>exports_util.required(ZodNonOptional,inst,args2[0])});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>tupleProcessor(inst,ctx,json,params),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>mapProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>setProcessor(inst,ctx,json,params),inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>fileProcessor(inst,ctx,json,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>successProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nanProcessor(inst,ctx,json,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>templateLiteralProcessor(inst,ctx,json,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>promiseProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>functionProcessor(inst,ctx,json,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});describe2=describe,meta2=meta});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm(()=>{init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if($schema==="http://json-schema.org/draft-07/schema#")return"draft-7";if($schema==="http://json-schema.org/draft-04/schema#")return"draft-4";return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let path=ref.slice(1).split("/").filter(Boolean);if(path.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){let key=path[1];if(!key||!ctx.defs[key])throw Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0)return z.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every((v)=>typeof v==="string"))return z.enum(enumValues);let literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2)return literalSchemas[0];return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map((t)=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0)return z.never();if(typeSchemas.length===1)return typeSchemas[0];return z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;if(format==="email")stringSchema=stringSchema.check(z.email());else if(format==="uri"||format==="uri-reference")stringSchema=stringSchema.check(z.url());else if(format==="uuid"||format==="guid")stringSchema=stringSchema.check(z.uuid());else if(format==="date-time")stringSchema=stringSchema.check(z.iso.datetime());else if(format==="date")stringSchema=stringSchema.check(z.iso.date());else if(format==="time")stringSchema=stringSchema.check(z.iso.time());else if(format==="duration")stringSchema=stringSchema.check(z.iso.duration());else if(format==="ipv4")stringSchema=stringSchema.check(z.ipv4());else if(format==="ipv6")stringSchema=stringSchema.check(z.ipv6());else if(format==="mac")stringSchema=stringSchema.check(z.mac());else if(format==="cidr")stringSchema=stringSchema.check(z.cidrv4());else if(format==="cidr-v6")stringSchema=stringSchema.check(z.cidrv6());else if(format==="base64")stringSchema=stringSchema.check(z.base64());else if(format==="base64url")stringSchema=stringSchema.check(z.base64url());else if(format==="e164")stringSchema=stringSchema.check(z.e164());else if(format==="jwt")stringSchema=stringSchema.check(z.jwt());else if(format==="emoji")stringSchema=stringSchema.check(z.emoji());else if(format==="nanoid")stringSchema=stringSchema.check(z.nanoid());else if(format==="cuid")stringSchema=stringSchema.check(z.cuid());else if(format==="cuid2")stringSchema=stringSchema.check(z.cuid2());else if(format==="ulid")stringSchema=stringSchema.check(z.ulid());else if(format==="xid")stringSchema=stringSchema.check(z.xid());else if(format==="ksuid")stringSchema=stringSchema.check(z.ksuid())}if(typeof schema.minLength==="number")stringSchema=stringSchema.min(schema.minLength);if(typeof schema.maxLength==="number")stringSchema=stringSchema.max(schema.maxLength);if(schema.pattern)stringSchema=stringSchema.regex(new RegExp(schema.pattern));zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number")numberSchema=numberSchema.min(schema.minimum);if(typeof schema.maximum==="number")numberSchema=numberSchema.max(schema.maximum);if(typeof schema.exclusiveMinimum==="number")numberSchema=numberSchema.gt(schema.exclusiveMinimum);else if(schema.exclusiveMinimum===!0&&typeof schema.minimum==="number")numberSchema=numberSchema.gt(schema.minimum);if(typeof schema.exclusiveMaximum==="number")numberSchema=numberSchema.lt(schema.exclusiveMaximum);else if(schema.exclusiveMaximum===!0&&typeof schema.maximum==="number")numberSchema=numberSchema.lt(schema.maximum);if(typeof schema.multipleOf==="number")numberSchema=numberSchema.multipleOf(schema.multipleOf);zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}let objectSchema2=z.object(shape).passthrough(),recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0)schemasToIntersect.push(z.object(shape).passthrough());if(schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z.object(shape);if(schema.additionalProperties===!1)zodSchema=objectSchema.strict();else if(typeof schema.additionalProperties==="object")zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx));else zodSchema=objectSchema.passthrough();break}case"array":{let{prefixItems,items}=schema;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map((item)=>convertSchema(item,ctx)),rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(Array.isArray(items)){let tupleItems=items.map((item)=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);if(typeof schema.minItems==="number")arraySchema=arraySchema.min(schema.minItems);if(typeof schema.maxItems==="number")arraySchema=arraySchema.max(schema.maxItems);zodSchema=arraySchema}else zodSchema=z.array(z.any());break}default:throw Error(`Unsupported type: ${type}`)}if(schema.description)zodSchema=zodSchema.describe(schema.description);if(schema.default!==void 0)zodSchema=zodSchema.default(schema.default);return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map((s)=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map((s)=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}if(schema.nullable===!0&&ctx.version==="openapi-3.0")baseSchema=z.nullable(baseSchema);if(schema.readOnly===!0)baseSchema=z.readonly(baseSchema);let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)if(key in schema)extraMeta[key]=schema[key];let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)if(key in schema)extraMeta[key]=schema[key];for(let key of Object.keys(schema))if(!RECOGNIZED_KEYS.has(key))extraMeta[key]=schema[key];if(Object.keys(extraMeta).length>0)ctx.registry.add(baseSchema,extraMeta);return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean")return schema?z.any():z.never();let version2=detectVersion(schema,params?.defaultTarget),defs=schema.$defs||schema.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:schema,registry:params?.registry??globalRegistry};return convertSchema(schema,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm(()=>{init_registries();init_checks2();init_iso();init_schemas2();z={...exports_schemas2,...exports_checks2,iso:exports_iso},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date4,boolean:()=>boolean3,bigint:()=>bigint3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm(()=>{init_core2();init_schemas2()});var exports_external={};__export(exports_external,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,util:()=>exports_util,url:()=>url,uppercase:()=>_uppercase,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,trim:()=>_trim,treeifyError:()=>treeifyError,transform:()=>transform,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,toJSONSchema:()=>toJSONSchema,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,setErrorMap:()=>setErrorMap,set:()=>set,safeParseAsync:()=>safeParseAsync2,safeParse:()=>safeParse2,safeEncodeAsync:()=>safeEncodeAsync2,safeEncode:()=>safeEncode2,safeDecodeAsync:()=>safeDecodeAsync2,safeDecode:()=>safeDecode2,registry:()=>registry,regexes:()=>exports_regexes,regex:()=>_regex,refine:()=>refine,record:()=>record,readonly:()=>readonly,property:()=>_property,promise:()=>promise,prettifyError:()=>prettifyError,preprocess:()=>preprocess,prefault:()=>prefault,positive:()=>_positive,pipe:()=>pipe,partialRecord:()=>partialRecord,parseAsync:()=>parseAsync2,parse:()=>parse3,overwrite:()=>_overwrite,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonoptional:()=>nonoptional,nonnegative:()=>_nonnegative,never:()=>never,negative:()=>_negative,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,meta:()=>meta2,maxSize:()=>_maxSize,maxLength:()=>_maxLength,map:()=>map,mac:()=>mac2,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,looseRecord:()=>looseRecord,looseObject:()=>looseObject,locales:()=>exports_locales,literal:()=>literal,length:()=>_length,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,iso:()=>exports_iso,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,includes:()=>_includes,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,gte:()=>_gte,gt:()=>_gt,globalRegistry:()=>globalRegistry,getErrorMap:()=>getErrorMap,function:()=>_function,fromJSONSchema:()=>fromJSONSchema,formatError:()=>formatError,float64:()=>float64,float32:()=>float32,flattenError:()=>flattenError,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,endsWith:()=>_endsWith,encodeAsync:()=>encodeAsync2,encode:()=>encode2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,decodeAsync:()=>decodeAsync2,decode:()=>decode2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,core:()=>exports_core2,config:()=>config,coerce:()=>exports_coerce,codec:()=>codec,clone:()=>clone,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodRealError:()=>ZodRealError,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,$output:()=>$output,$input:()=>$input,$brand:()=>$brand});var init_external=__esm(()=>{init_core2();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();config(en_default())});var init_zod=__esm(()=>{init_external();init_external()});var EVIDENCE_MAX_JSON_BYTES=512000,EVIDENCE_MAX_PATCH_BYTES=5242880,EVIDENCE_MAX_TASK_BYTES=20971520,EvidenceTypeSchema,EvidenceVerdictSchema,BaseEvidenceSchema,ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastFindingSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,GateEvidenceBaseSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema,EvidenceSchema,EvidenceBundleSchema;var init_evidence_schema=__esm(()=>{init_zod();EvidenceTypeSchema=exports_external.enum(["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan","mutation-gate","drift-verification","hallucination-verification"]),EvidenceVerdictSchema=exports_external.enum(["pass","fail","warn","skip","approved","rejected","info"]),BaseEvidenceSchema=exports_external.object({task_id:exports_external.string().min(1),type:EvidenceTypeSchema,timestamp:exports_external.string().datetime(),agent:exports_external.string().min(1),verdict:EvidenceVerdictSchema,summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),ReviewEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("review"),risk:exports_external.enum(["low","medium","high","critical"]),issues:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning","info"]),message:exports_external.string().min(1),file:exports_external.string().optional(),line:exports_external.number().int().optional()})).default([])}),TestEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("test"),tests_passed:exports_external.number().int().min(0),tests_failed:exports_external.number().int().min(0),test_file:exports_external.string().optional(),failures:exports_external.array(exports_external.object({name:exports_external.string().min(1),message:exports_external.string().min(1)})).default([])}),DiffEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("diff"),files_changed:exports_external.array(exports_external.string()).default([]),additions:exports_external.number().int().min(0).default(0),deletions:exports_external.number().int().min(0).default(0),patch_path:exports_external.string().optional()}),ApprovalEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("approval")}),NoteEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("note")}),RetrospectiveEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("retrospective"),phase_number:exports_external.number().int().min(1).max(99),total_tool_calls:exports_external.number().int().min(0).max(9999),coder_revisions:exports_external.number().int().min(0).max(999),reviewer_rejections:exports_external.number().int().min(0).max(999),loop_detections:exports_external.number().int().min(0).max(9999).optional(),circuit_breaker_trips:exports_external.number().int().min(0).max(9999).optional(),test_failures:exports_external.number().int().min(0).max(9999),security_findings:exports_external.number().int().min(0).max(999),integration_issues:exports_external.number().int().min(0).max(999),task_count:exports_external.number().int().min(1).max(9999),task_complexity:exports_external.enum(["trivial","simple","moderate","complex"]),top_rejection_reasons:exports_external.array(exports_external.string()).default([]),lessons_learned:exports_external.array(exports_external.string()).max(5).default([]),user_directives:exports_external.array(exports_external.object({directive:exports_external.string().min(1),category:exports_external.enum(["tooling","code_style","architecture","process","other"]),scope:exports_external.enum(["session","project","global"])})).default([]),approaches_tried:exports_external.array(exports_external.object({approach:exports_external.string().min(1),result:exports_external.enum(["success","failure","partial"]),abandoned_reason:exports_external.string().optional()})).max(10).default([]),error_taxonomy:exports_external.array(exports_external.enum(["planning_error","interface_mismatch","logic_error","scope_creep","gate_evasion"])).default([])}),SyntaxEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("syntax"),files_checked:exports_external.number().int(),files_failed:exports_external.number().int(),skipped_count:exports_external.number().int().default(0),files:exports_external.array(exports_external.object({path:exports_external.string(),language:exports_external.string(),ok:exports_external.boolean(),errors:exports_external.array(exports_external.object({line:exports_external.number().int(),column:exports_external.number().int(),message:exports_external.string()})).default([]),skipped_reason:exports_external.string().optional()})).default([])}),PlaceholderEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("placeholder"),findings:exports_external.array(exports_external.object({path:exports_external.string(),line:exports_external.number().int(),kind:exports_external.enum(["comment","string","function_body","other"]),excerpt:exports_external.string(),rule_id:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),files_with_findings:exports_external.number().int(),findings_count:exports_external.number().int()}),SastFindingSchema=exports_external.object({rule_id:exports_external.string(),severity:exports_external.enum(["critical","high","medium","low"]),message:exports_external.string(),location:exports_external.object({file:exports_external.string(),line:exports_external.number().int(),column:exports_external.number().int().optional()}),remediation:exports_external.string().optional()}),SastEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sast"),findings:exports_external.array(SastFindingSchema).default([]),engine:exports_external.enum(["tier_a","tier_a+tier_b"]),files_scanned:exports_external.number().int(),findings_count:exports_external.number().int(),findings_by_severity:exports_external.object({critical:exports_external.number().int(),high:exports_external.number().int(),medium:exports_external.number().int(),low:exports_external.number().int()}),new_findings:exports_external.array(SastFindingSchema).optional(),pre_existing_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional()}),SbomEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sbom"),components:exports_external.array(exports_external.object({name:exports_external.string(),version:exports_external.string(),type:exports_external.enum(["library","framework","application"]),purl:exports_external.string().optional(),license:exports_external.string().optional()})).default([]),metadata:exports_external.object({timestamp:exports_external.string().datetime(),tool:exports_external.string(),tool_version:exports_external.string()}),files:exports_external.array(exports_external.string()),components_count:exports_external.number().int(),output_path:exports_external.string()}),BuildEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("build"),runs:exports_external.array(exports_external.object({kind:exports_external.enum(["build","typecheck","test"]),command:exports_external.string(),cwd:exports_external.string(),exit_code:exports_external.number().int(),duration_ms:exports_external.number().int(),stdout_tail:exports_external.string(),stderr_tail:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),runs_count:exports_external.number().int(),failed_count:exports_external.number().int(),skipped_reason:exports_external.string().optional()}),QualityBudgetEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("quality_budget"),metrics:exports_external.object({complexity_delta:exports_external.number(),public_api_delta:exports_external.number(),duplication_ratio:exports_external.number(),test_to_code_ratio:exports_external.number()}),thresholds:exports_external.object({max_complexity_delta:exports_external.number(),max_public_api_delta:exports_external.number(),max_duplication_ratio:exports_external.number(),min_test_to_code_ratio:exports_external.number()}),violations:exports_external.array(exports_external.object({type:exports_external.enum(["complexity","api","duplication","test_ratio"]),message:exports_external.string(),severity:exports_external.enum(["error","warning"]),files:exports_external.array(exports_external.string())})).default([]),files_analyzed:exports_external.array(exports_external.string())}),SecretscanEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("secretscan"),findings_count:exports_external.number().int().min(0).default(0),scan_directory:exports_external.string().optional(),files_scanned:exports_external.number().int().min(0).default(0),skipped_files:exports_external.number().int().min(0).default(0)}),GateEvidenceBaseSchema=exports_external.object({task_id:exports_external.string().optional(),agent:exports_external.string().optional(),timestamp:exports_external.string().datetime(),summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),MutationGateEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("mutation-gate"),verdict:exports_external.enum(["pass","warn","fail","skip"]),killRate:exports_external.number().min(0).max(1).optional(),adjustedKillRate:exports_external.number().min(0).max(1).optional(),survivedMutants:exports_external.string().optional()}),DriftVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("drift-verification"),verdict:exports_external.enum(["approved","rejected"]),requirementCoverage:exports_external.string().optional()}),HallucinationVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("hallucination-verification"),verdict:exports_external.enum(["approved","rejected"]),findings:exports_external.string().optional()}),EvidenceSchema=exports_external.discriminatedUnion("type",[ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema]),EvidenceBundleSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),task_id:exports_external.string().min(1),entries:exports_external.array(EvidenceSchema).default([]),created_at:exports_external.string().datetime(),updated_at:exports_external.string().datetime()})});function isDebug(){return process.env.OPENCODE_SWARM_DEBUG==="1"}function log(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.log(`[opencode-swarm ${timestamp}] ${message}`,data);else console.log(`[opencode-swarm ${timestamp}] ${message}`)}function warn(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`)}function criticalWarn(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`)}function error48(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`,data);else console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`)}var init_logger=()=>{};function sanitizeBufferedLine(s){return s.replace(/\s+/g," ").replace(CONTROL_CHARS_RE,"").replace(/\s+/g," ").trim()}function addDeferredWarning(warning){let sanitized=sanitizeBufferedLine(warning);if(deferredWarnings.length<MAX_DEFERRED_WARNINGS-1){deferredWarnings.push(sanitized);return}if(!deferredWarningsTruncated)deferredWarnings.push(`[opencode-swarm] ${MAX_DEFERRED_WARNINGS-1} deferred warnings buffered; additional advisories were dropped (cap reached). Run with OPENCODE_SWARM_DEBUG=1 to see all advisories in the debug log.`),deferredWarningsTruncated=!0}function renderAdvisoryDetail(data){if(data===void 0||data===null)return"";let raw;if(typeof data==="string")raw=data;else if(data instanceof Error)raw=data.message;else if(Array.isArray(data)&&data.every((d)=>typeof d==="string"))raw=data.join("; ");else try{raw=JSON.stringify(data)??String(data)}catch{raw=String(data)}let collapsed=sanitizeBufferedLine(raw);if(collapsed==="")return"";return collapsed.length>MAX_ADVISORY_DETAIL_CHARS?`${collapsed.slice(0,MAX_ADVISORY_DETAIL_CHARS-1)}…`:collapsed}function advisoryWarn(message,data){let detail=renderAdvisoryDetail(data);addDeferredWarning(detail?`${message} ${detail}`:message),log(message,data)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0,deferredWarningsTruncated=!1}var deferredWarnings,MAX_DEFERRED_WARNINGS=50,deferredWarningsTruncated=!1,CONTROL_CHARS_RE,MAX_ADVISORY_DETAIL_CHARS=600;var init_warning_buffer=__esm(()=>{init_logger();deferredWarnings=[],CONTROL_CHARS_RE=/[\x00-\x1F\x7F-\x9F]/g});function isActiveStatus(status){return!INACTIVE_STATUSES.has(status??"")}var KNOWLEDGE_SCHEMA_VERSION=3,INACTIVE_STATUSES,OUTCOME_BLOCK_THRESHOLD=-0.3;var init_knowledge_types=__esm(()=>{INACTIVE_STATUSES=new Set(["archived","quarantined","quarantined_unactionable"])});var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,WatchdogConfigSchema:()=>WatchdogConfigSchema,UIReviewConfigSchema:()=>UIReviewConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,ToolFilterConfigSchema:()=>ToolFilterConfigSchema,TokenRatiosSchema:()=>TokenRatiosSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SummaryConfigSchema:()=>SummaryConfigSchema,StandardTurboConfigSchema:()=>StandardTurboConfigSchema,SpecWriterConfigSchema:()=>SpecWriterConfigSchema,SlopDetectorConfigSchema:()=>SlopDetectorConfigSchema,SkillsConfigSchema:()=>SkillsConfigSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,SkillImproverConfigSchema:()=>SkillImproverConfigSchema,SelfReviewConfigSchema:()=>SelfReviewConfigSchema,SecretscanConfigSchema:()=>SecretscanConfigSchema,ScoringWeightsSchema:()=>ScoringWeightsSchema,ScoringConfigSchema:()=>ScoringConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS:()=>GATE_CONFIG_KNOWN_SECTION_KEYS,FALLBACK_MODELS_MAX:()=>FALLBACK_MODELS_MAX,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_EXTERNAL_SKILLS_CONFIG:()=>DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_ARCHITECT_PROFILE:()=>DEFAULT_ARCHITECT_PROFILE,DEFAULT_AGENT_PROFILES:()=>DEFAULT_AGENT_PROFILES,CuratorConfigSchema:()=>CuratorConfigSchema,CouncilConfigSchema:()=>CouncilConfigSchema,ContextMapConfigSchema:()=>ContextMapConfigSchema,ContextBudgetConfigSchema:()=>ContextBudgetConfigSchema,CompactionConfigSchema:()=>CompactionConfigSchema,CompactionAdvisoryConfigSchema:()=>CompactionAdvisoryConfigSchema,CheckpointConfigSchema:()=>CheckpointConfigSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,AuthorityConfigSchema:()=>AuthorityConfigSchema,ArchitecturalSupervisionConfigSchema:()=>ArchitecturalSupervisionConfigSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentThinkingConfigSchema:()=>AgentThinkingConfigSchema,AgentReasoningConfigSchema:()=>AgentReasoningConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AgentAuthorityRuleSchema:()=>AgentAuthorityRuleSchema,AdversarialTestingConfigSchema:()=>AdversarialTestingConfigSchema,AdversarialDetectionConfigSchema:()=>AdversarialDetectionConfigSchema});function isKnownCanonicalRole(role){if(!role)return!1;return CANONICAL_ROLES_SET.has(role)}function getCanonicalAgentRole(agentName,generatedAgentNames){if(!agentName)return agentName;let normalized=agentName.toLowerCase();if(CANONICAL_ROLES_SET.has(normalized))return normalized;if(generatedAgentNames){let registry2=new Set;for(let n of generatedAgentNames)registry2.add(n.toLowerCase());if(!registry2.has(normalized))return agentName}for(let role of CANONICAL_ROLES_LONGEST_FIRST)for(let sep of SEPARATORS){let suffix=sep+role;if(normalized.length>suffix.length&&normalized.endsWith(suffix))return role}return agentName}function resolveGeneratedAgentRole(agentName,generatedAgentNames){return _internals.getCanonicalAgentRole(agentName,generatedAgentNames)}function stripKnownSwarmPrefix(agentName){return getCanonicalAgentRole(agentName)}function resolveGuardrailsConfig(config2,agentName){if(!agentName)return config2;let canonicalName=_internals.stripKnownSwarmPrefix(agentName),hasBuiltInProfile=canonicalName in DEFAULT_AGENT_PROFILES,userProfile=config2.profiles?.[agentName]??config2.profiles?.[canonicalName];if(!hasBuiltInProfile){if(userProfile)return{...config2,...userProfile};return config2}let builtInProfile=DEFAULT_AGENT_PROFILES[canonicalName];return{...config2,...builtInProfile,...userProfile||{}}}function resolveExternalSkillsConfig(input){if(input===void 0||input===null||typeof input!=="object"||Array.isArray(input))return{...DEFAULT_EXTERNAL_SKILLS_CONFIG};let config2=input;return{curation_enabled:config2.curation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.curation_enabled,max_candidates:config2.max_candidates??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates,max_bytes_per_candidate:config2.max_bytes_per_candidate??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_bytes_per_candidate,eviction_policy:config2.eviction_policy??DEFAULT_EXTERNAL_SKILLS_CONFIG.eviction_policy,ttl_days:config2.ttl_days??DEFAULT_EXTERNAL_SKILLS_CONFIG.ttl_days,evaluation_enabled:config2.evaluation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.evaluation_enabled,sources:Array.isArray(config2.sources)?config2.sources:[],max_candidates_per_discovery:config2.max_candidates_per_discovery??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates_per_discovery,max_concurrent_fetches:config2.max_concurrent_fetches??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_concurrent_fetches,fetch_timeout_ms:config2.fetch_timeout_ms??DEFAULT_EXTERNAL_SKILLS_CONFIG.fetch_timeout_ms}}var _internals,SEPARATORS,CANONICAL_ROLES_LONGEST_FIRST,CANONICAL_ROLES_SET,AgentReasoningConfigSchema,AgentThinkingConfigSchema,FALLBACK_MODELS_MAX=3,AgentOverrideConfigSchema,SwarmConfigSchema,ModelPricingConfigSchema,PricingConfigSchema,HooksConfigSchema,ScoringWeightsSchema,DecisionDecaySchema,TokenRatiosSchema,ScoringConfigSchema,ContextBudgetConfigSchema,EvidenceConfigSchema,GateFeatureSchema,PlaceholderScanConfigSchema,QualityBudgetConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS,GateConfigSchema,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,ReviewPassesConfigSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,UIReviewConfigSchema,CompactionAdvisoryConfigSchema,LintConfigSchema,SecretscanConfigSchema,GuardrailsProfileSchema,DEFAULT_AGENT_PROFILES,DEFAULT_ARCHITECT_PROFILE,GuardrailsConfigSchema,WatchdogConfigSchema,SelfReviewConfigSchema,ToolFilterConfigSchema,PlanCursorConfigSchema,ContextMapConfigSchema,RepoGraphConfigSchema,CheckpointConfigSchema,ApplyPatchConfigSchema,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationAudienceSchema,SkillPropagationConfigSchema,SkillImproverConfigSchema,SkillsConfigSchema,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_knowledge_types();init_constants();_internals={stripKnownSwarmPrefix,getCanonicalAgentRole,resolveGuardrailsConfig},SEPARATORS=["_","-"," "],CANONICAL_ROLES_LONGEST_FIRST=[...ALL_AGENT_NAMES].sort((a,b)=>b.length-a.length),CANONICAL_ROLES_SET=new Set(ALL_AGENT_NAMES);AgentReasoningConfigSchema=exports_external.object({effort:exports_external.enum(["low","medium","high","max"]).optional()}),AgentThinkingConfigSchema=exports_external.object({type:exports_external.enum(["enabled","disabled"]).optional(),budget_tokens:exports_external.number().int().positive().optional()}),AgentOverrideConfigSchema=exports_external.object({model:exports_external.string().optional(),variant:exports_external.string().min(1).optional(),temperature:exports_external.number().min(0).max(2).optional(),disabled:exports_external.boolean().optional(),fallback_models:exports_external.array(exports_external.string()).max(FALLBACK_MODELS_MAX).optional(),reasoning:AgentReasoningConfigSchema.optional(),thinking:AgentThinkingConfigSchema.optional()}),SwarmConfigSchema=exports_external.object({name:exports_external.string().optional(),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional()}),ModelPricingConfigSchema=exports_external.object({input_per_million:exports_external.number().min(0),output_per_million:exports_external.number().min(0),reasoning_per_million:exports_external.number().min(0).optional(),cache_per_million:exports_external.number().min(0).optional()}),PricingConfigSchema=exports_external.object({models:exports_external.record(exports_external.string().min(1),ModelPricingConfigSchema).optional().default({})}),HooksConfigSchema=exports_external.object({system_enhancer:exports_external.boolean().default(!0),compaction:exports_external.boolean().default(!0),agent_activity:exports_external.boolean().default(!0),delegation_tracker:exports_external.boolean().default(!1),agent_awareness_max_chars:exports_external.number().min(50).max(2000).default(300),delegation_gate:exports_external.boolean().default(!0),delegation_max_chars:exports_external.number().min(500).max(20000).default(4000),background_subagents:exports_external.boolean().default(!1),background_pending_timeout_minutes:exports_external.number().int().min(1).max(1440).default(30)}),ScoringWeightsSchema=exports_external.object({phase:exports_external.number().min(0).max(5).default(1),current_task:exports_external.number().min(0).max(5).default(2),blocked_task:exports_external.number().min(0).max(5).default(1.5),recent_failure:exports_external.number().min(0).max(5).default(2.5),recent_success:exports_external.number().min(0).max(5).default(0.5),evidence_presence:exports_external.number().min(0).max(5).default(1),decision_recency:exports_external.number().min(0).max(5).default(1.5),dependency_proximity:exports_external.number().min(0).max(5).default(1)}),DecisionDecaySchema=exports_external.object({mode:exports_external.enum(["linear","exponential"]).default("exponential"),half_life_hours:exports_external.number().min(1).max(168).default(24)}),TokenRatiosSchema=exports_external.object({prose:exports_external.number().min(0.1).max(1).default(0.25),code:exports_external.number().min(0.1).max(1).default(0.4),markdown:exports_external.number().min(0.1).max(1).default(0.3),json:exports_external.number().min(0.1).max(1).default(0.35)}),ScoringConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().min(10).max(500).default(100),weights:ScoringWeightsSchema.optional(),decision_decay:DecisionDecaySchema.optional(),token_ratios:TokenRatiosSchema.optional()}),ContextBudgetConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),warn_threshold:exports_external.number().min(0).max(1).default(0.7),critical_threshold:exports_external.number().min(0).max(1).default(0.9),model_limits:exports_external.record(exports_external.string(),exports_external.number().min(1000)).default({default:128000}),max_injection_tokens:exports_external.number().min(100).max(50000).default(4000),unified_injection_tokens:exports_external.number().min(100).max(50000).optional(),tracked_agents:exports_external.array(exports_external.string()).default(["architect"]),scoring:ScoringConfigSchema.optional(),enforce:exports_external.boolean().default(!0),prune_target:exports_external.number().min(0).max(1).default(0.7),preserve_last_n_turns:exports_external.number().min(0).max(100).default(4),recent_window:exports_external.number().min(1).max(100).default(10),enforce_on_agent_switch:exports_external.boolean().default(!0),tool_output_mask_threshold:exports_external.number().min(100).max(1e5).default(2000)}),EvidenceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_age_days:exports_external.number().min(1).max(365).default(90),max_bundles:exports_external.number().min(10).max(1e4).default(1000),auto_archive:exports_external.boolean().default(!1),cache_max_bytes:exports_external.number().min(512).max(52428800).optional(),cache_max_records:exports_external.number().min(10).max(1e5).optional()}),GateFeatureSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),PlaceholderScanConfigSchema=GateFeatureSchema.extend({deny_patterns:exports_external.array(exports_external.string()).default(["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"]),allow_globs:exports_external.array(exports_external.string()).default(["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"]),max_allowed_findings:exports_external.number().min(0).default(0),sentinel_allowlist:exports_external.array(exports_external.string()).default([])}),QualityBudgetConfigSchema=GateFeatureSchema.extend({max_complexity_delta:exports_external.number().default(5),max_public_api_delta:exports_external.number().default(10),max_duplication_ratio:exports_external.number().default(0.05),min_test_to_code_ratio:exports_external.number().default(0.3),enforce_on_globs:exports_external.array(exports_external.string()).default(["src/**"]),exclude_globs:exports_external.array(exports_external.string()).default(["docs/**","tests/**","**/*.test.*"])}),GATE_CONFIG_KNOWN_SECTION_KEYS={syntax_check:["enabled"],placeholder_scan:["enabled","deny_patterns","allow_globs","max_allowed_findings"],sast_scan:["enabled"],sbom_generate:["enabled"],build_check:["enabled"],quality_budget:["enabled","max_complexity_delta","max_public_api_delta","max_duplication_ratio","min_test_to_code_ratio","enforce_on_globs","exclude_globs"]},GateConfigSchema=exports_external.object({syntax_check:GateFeatureSchema.default({enabled:!0}),placeholder_scan:PlaceholderScanConfigSchema.default({enabled:!0,deny_patterns:["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"],allow_globs:["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"],max_allowed_findings:0,sentinel_allowlist:[]}),sast_scan:GateFeatureSchema.default({enabled:!0}),sbom_generate:GateFeatureSchema.default({enabled:!0}),build_check:GateFeatureSchema.default({enabled:!0}),quality_budget:QualityBudgetConfigSchema.default(()=>QualityBudgetConfigSchema.parse({}))}),PipelineConfigSchema=exports_external.object({parallel_precheck:exports_external.boolean().default(!0)}),PhaseCompleteConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),required_agents:exports_external.array(exports_external.enum(["coder","reviewer","test_engineer"])).default(["coder","reviewer","test_engineer"]),require_docs:exports_external.boolean().default(!0),policy:exports_external.enum(["enforce","warn"]).default("enforce"),regression_sweep:exports_external.object({enforce:exports_external.boolean().default(!1)}).optional()}),SummaryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),threshold_bytes:exports_external.number().min(1024).max(1048576).default(16384),max_summary_chars:exports_external.number().min(100).max(5000).default(1000),max_stored_bytes:exports_external.number().min(10240).max(104857600).default(10485760),retention_days:exports_external.number().min(1).max(365).default(7),exempt_tools:exports_external.array(exports_external.string()).default(["retrieve_summary","retrieve_lane_output","task","read"])}),ReviewPassesConfigSchema=exports_external.object({always_security_review:exports_external.boolean().default(!1),security_globs:exports_external.array(exports_external.string()).default(["**/auth/**","**/api/**","**/crypto/**","**/security/**","**/middleware/**","**/session/**","**/token/**"])}),AutoReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger:exports_external.enum(["task_completion","phase_boundary","both"]).default("phase_boundary"),timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000),max_diff_kb:exports_external.number().int().min(16).max(2048).default(256)}),AdversarialDetectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),policy:exports_external.enum(["warn","gate","ignore"]).default("warn"),pairs:exports_external.array(exports_external.tuple([exports_external.string(),exports_external.string()])).default([["coder","reviewer"]])}),AdversarialTestingConfigSchemaBase=exports_external.object({enabled:exports_external.boolean().default(!0),scope:exports_external.enum(["all","security-only"]).default("all")}),AdversarialTestingConfigSchema=AdversarialTestingConfigSchemaBase.default(()=>({enabled:!0,scope:"all"})),IntegrationAnalysisConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),DocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),doc_patterns:exports_external.array(exports_external.string()).default(["README.md","CONTRIBUTING.md","docs/**/*.md","docs/**/*.rst","**/CHANGELOG.md"])}),DesignDocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),out_dir:exports_external.string().default("docs").refine((v)=>v.length>0&&v!=="."&&!v.includes("..")&&!v.startsWith("/")&&!v.startsWith("\\")&&!/^[A-Za-z]:/.test(v),{message:'design_docs.out_dir must be a non-empty project-relative path with no "..", leading slash, or drive letter'}),language:exports_external.string().optional()}),UIReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger_paths:exports_external.array(exports_external.string()).default(["**/pages/**","**/components/**","**/views/**","**/screens/**","**/ui/**","**/layouts/**"]),trigger_keywords:exports_external.array(exports_external.string()).default(["new page","new screen","new component","redesign","layout change","form","modal","dialog","dropdown","sidebar","navbar","dashboard","landing page","signup","login form","settings page","profile page"])}),CompactionAdvisoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),thresholds:exports_external.array(exports_external.number().int().min(10).max(500)).default([50,75,100,125,150]),message:exports_external.string().default("[SWARM HINT] Session has ${totalToolCalls} tool calls. Consider compacting at next phase boundary to maintain context quality.")}),LintConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["check","fix"]).default("check"),linter:exports_external.enum(["biome","eslint","auto"]).default("auto"),patterns:exports_external.array(exports_external.string()).default(["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/biome.json","**/biome.jsonc"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/*.min.js"])}),SecretscanConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),patterns:exports_external.array(exports_external.string()).default(["**/*.{env,properties,yml,yaml,json,js,ts}","**/.env*","**/secrets/**","**/credentials/**","**/config/**/*.ts","**/config/**/*.js"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/test/**","**/tests/**","**/__tests__/**","**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js"]),extensions:exports_external.array(exports_external.string()).default([".env",".properties",".yml",".yaml",".json",".js",".ts",".py",".rb",".go",".java",".cs",".php"])}),GuardrailsProfileSchema=exports_external.object({max_tool_calls:exports_external.number().min(0).max(1000).optional(),max_duration_minutes:exports_external.number().min(0).max(480).optional(),max_repetitions:exports_external.number().min(3).max(50).optional(),max_consecutive_errors:exports_external.number().min(2).max(20).optional(),warning_threshold:exports_external.number().min(0.1).max(0.9).optional(),idle_timeout_minutes:exports_external.number().min(5).max(240).optional(),max_transient_retries:exports_external.number().min(0).max(20).optional()}),DEFAULT_AGENT_PROFILES={architect:{max_tool_calls:0,max_duration_minutes:0,max_consecutive_errors:8,warning_threshold:0.75},coder:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},test_engineer:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},explorer:{max_tool_calls:150,max_duration_minutes:20,max_consecutive_errors:8,warning_threshold:0.75},reviewer:{max_tool_calls:200,max_duration_minutes:30,max_consecutive_errors:8,warning_threshold:0.65},critic:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},sme:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},docs:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.75},designer:{max_tool_calls:150,max_duration_minutes:20,warning_threshold:0.75}},DEFAULT_ARCHITECT_PROFILE=DEFAULT_AGENT_PROFILES.architect,GuardrailsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tool_calls:exports_external.number().min(0).max(1000).default(200),max_duration_minutes:exports_external.number().min(0).max(480).default(30),max_repetitions:exports_external.number().min(3).max(50).default(10),max_consecutive_errors:exports_external.number().min(2).max(20).default(5),max_transient_retries:exports_external.number().min(0).max(20).default(5),warning_threshold:exports_external.number().min(0.1).max(0.9).default(0.75),idle_timeout_minutes:exports_external.number().min(5).max(240).default(60),no_op_warning_threshold:exports_external.number().min(1).max(100).default(15),max_coder_revisions:exports_external.number().int().min(1).max(20).default(5),runaway_output_max_turns:exports_external.number().int().min(1).max(20).default(5),qa_gates:exports_external.object({required_tools:exports_external.array(exports_external.string().min(1)).default(["diff","syntax_check","placeholder_scan","lint","pre_check_batch"]),require_reviewer_test_engineer:exports_external.boolean().default(!0)}).optional(),profiles:exports_external.record(exports_external.string(),GuardrailsProfileSchema).optional(),block_destructive_commands:exports_external.boolean().default(!0),interpreter_allowed_agents:exports_external.array(exports_external.string().min(1)).optional(),shell_audit_log:exports_external.boolean().default(!0)}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!1),delegation_ledger:exports_external.boolean().default(!0)}),SelfReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!0)});ToolFilterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),overrides:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).default({})}),PlanCursorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tokens:exports_external.number().min(500).max(4000).default(1500),lookahead_tasks:exports_external.number().min(0).max(5).default(2)}),ContextMapConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["conservative","balanced","aggressive"]).default("balanced"),max_capsule_tokens:exports_external.number().int().positive().default(2000),invalidate_on_hash_change:exports_external.boolean().default(!0),agent_profiles:exports_external.record(exports_external.string(),exports_external.string()).default({})}),RepoGraphConfigSchema=exports_external.object({exclude_dirs:exports_external.array(exports_external.string().trim().min(1)).default([])}),CheckpointConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),auto_checkpoint_threshold:exports_external.number().int().min(1).max(20).default(3),allow_empty_commits:exports_external.boolean().default(!1)}).strict(),ApplyPatchConfigSchema=exports_external.object({fuzzy_match:exports_external.boolean().default(!1),fuzzy_match_context_aware:exports_external.boolean().default(!1)}).strict(),AutomationModeSchema=exports_external.enum(["manual","hybrid","auto"]),AutomationCapabilitiesSchema=exports_external.object({plan_sync:exports_external.boolean().default(!0),phase_preflight:exports_external.boolean().default(!1),config_doctor_on_startup:exports_external.boolean().default(!1),config_doctor_autofix:exports_external.boolean().default(!1),evidence_auto_summaries:exports_external.boolean().default(!0),decision_drift_detection:exports_external.boolean().default(!0)}),AutomationConfigSchemaBase=exports_external.object({mode:AutomationModeSchema.default("manual"),capabilities:AutomationCapabilitiesSchema.default({plan_sync:!0,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!0,decision_drift_detection:!0})}),AutomationConfigSchema=AutomationConfigSchemaBase,KnowledgeConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),swarm_max_entries:exports_external.number().min(1).max(1e4).default(100),hive_max_entries:exports_external.number().min(1).max(1e5).default(200),auto_promote_days:exports_external.number().min(1).max(3650).default(90),max_inject_count:exports_external.number().min(0).max(50).default(5),delegate_max_inject_count:exports_external.number().min(0).max(50).default(8),inject_char_budget:exports_external.number().min(200).max(1e4).default(2000),context_budget_threshold:exports_external.number().int().positive().optional(),max_lesson_display_chars:exports_external.number().min(40).max(280).default(120),dedup_threshold:exports_external.number().min(0).max(1).default(0.6),scope_filter:exports_external.array(exports_external.string()).default(["global"]),hive_enabled:exports_external.boolean().default(!0),rejected_max_entries:exports_external.number().min(1).max(1000).default(20),validation_enabled:exports_external.boolean().default(!0),evergreen_confidence:exports_external.number().min(0).max(1).default(0.9),evergreen_utility:exports_external.number().min(0).max(1).default(0.8),low_utility_threshold:exports_external.number().min(0).max(1).default(0.3),min_retrievals_for_utility:exports_external.number().min(1).max(100).default(3),schema_version:exports_external.number().int().min(1).default(1),directive_min_confidence:exports_external.number().min(0).max(1).default(0.75),same_project_weight:exports_external.number().min(0).max(5).default(1),cross_project_weight:exports_external.number().min(0).max(5).default(0.5),min_encounter_score:exports_external.number().min(0).max(1).default(0.1),initial_encounter_score:exports_external.number().min(0).max(5).default(1),encounter_increment:exports_external.number().min(0).max(1).default(0.1),max_encounter_score:exports_external.number().min(1).max(20).default(10),default_max_phases:exports_external.number().int().positive().default(10),todo_max_phases:exports_external.number().int().positive().default(3),sweep_enabled:exports_external.boolean().default(!0),confidence_floor_action:exports_external.enum(["none","demote","quarantine"]).default("demote"),confidence_floor_min_outcomes:exports_external.number().int().min(0).default(3),confidence_floor_signal_threshold:exports_external.number().min(-1).max(1).default(0),contradiction_threshold_action:exports_external.enum(["tag_only","quarantine"]).default("quarantine"),contradiction_quarantine_threshold:exports_external.number().int().positive().default(3),contradiction_quarantine_window_days:exports_external.number().int().positive().default(30),promoted_demotion_min_negative_phases:exports_external.number().int().positive().default(3),promoted_demotion_signal_threshold:exports_external.number().min(-1).max(1).default(OUTCOME_BLOCK_THRESHOLD),promotion_min_terminal_applications:exports_external.number().min(0).max(100).default(0),promotion_min_distinct_cohorts:exports_external.number().min(0).max(50).default(0),realtime_learning_nudge:exports_external.object({enabled:exports_external.boolean().default(!0),first_after_tool_calls:exports_external.number().int().min(1).max(1000).default(10),repeat_after_tool_calls:exports_external.number().int().min(1).max(1000).default(25)}).default({enabled:!0,first_after_tool_calls:10,repeat_after_tool_calls:25}),retrieval:exports_external.object({mmr_lambda:exports_external.number().min(0).max(1).default(0.5),cold_start_bonus:exports_external.number().min(0).max(0.5).default(0.08),cold_start_max_age_phases:exports_external.number().int().min(0).max(100).default(3),synonym_min_cooccurrence:exports_external.number().int().min(1).max(100).default(3),synonym_map_max_pairs:exports_external.number().int().min(1).max(1e4).default(500)}).optional(),enrichment:exports_external.object({max_calls_per_day:exports_external.number().int().min(0).max(1000).default(30),quota_window:exports_external.enum(["utc","local"]).default("utc"),batch_size:exports_external.number().int().min(1).max(100).optional()}).default({max_calls_per_day:30,quota_window:"utc"})}),MemoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),provider:exports_external.enum(["local-jsonl","sqlite"]).default("sqlite"),storageDir:exports_external.string().default(".swarm/memory"),sqlite:exports_external.object({path:exports_external.string().default(".swarm/memory/memory.db"),busyTimeoutMs:exports_external.number().int().min(0).max(60000).default(5000)}).default({path:".swarm/memory/memory.db",busyTimeoutMs:5000}),link:exports_external.object({enabled:exports_external.boolean().default(!1)}).default({enabled:!1}),recall:exports_external.object({defaultMaxItems:exports_external.number().int().min(1).max(20).default(8),defaultTokenBudget:exports_external.number().int().min(100).max(5000).default(1200),minScore:exports_external.number().min(0).max(1).default(0.05),injection:exports_external.object({enabled:exports_external.boolean().default(!0),minScore:exports_external.number().min(0).max(1).default(0.25),requireQuerySignal:exports_external.boolean().default(!0),maxItems:exports_external.number().int().min(1).max(20).default(6),tokenBudget:exports_external.number().int().min(100).max(5000).default(1000)}).default({enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000})}).default({defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}}),learning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),propagationFactor:exports_external.number().min(0).max(1).default(0.3),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),propagationTokenOverlapThreshold:exports_external.number().min(0).max(1).default(0.4),propagationEmbeddingCosineThreshold:exports_external.number().min(0).max(1).default(0.7),propagationFanout:exports_external.number().int().min(0).max(1000).default(20),propagationLookbackDays:exports_external.number().int().min(1).max(3650).default(30)}).default({learningRate:0.1,propagationFactor:0.3,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,propagationTokenOverlapThreshold:0.4,propagationEmbeddingCosineThreshold:0.7,propagationFanout:20,propagationLookbackDays:30}),writes:exports_external.object({mode:exports_external.literal("propose").default("propose")}).default({mode:"propose"}),redaction:exports_external.object({rejectDurableSecrets:exports_external.boolean().default(!0)}).default({rejectDurableSecrets:!0}),maintenance:exports_external.object({lowUtilityMaxConfidence:exports_external.number().min(0).max(1).default(0.45),lowUtilityMinAgeDays:exports_external.number().int().min(1).max(3650).default(30),importance:exports_external.object({wRecency:exports_external.number().min(0).max(1).default(0.2),wFrequency:exports_external.number().min(0).max(1).default(0.2),wFreshness:exports_external.number().min(0).max(1).default(0.15),wConfidence:exports_external.number().min(0).max(1).default(0.25),lambda:exports_external.number().min(0).max(10).default(0.05),mu:exports_external.number().min(0).max(10).default(0.01),n:exports_external.number().int().min(1).max(1e5).default(50),threshold:exports_external.number().min(0).max(1).default(0.2)}).default({wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2})}).default({lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,importance:{wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2}}),qLearning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),promotionMinRetrievals:exports_external.number().int().min(0).max(1e5).default(5),propagationFraction:exports_external.number().min(0).max(1).default(0.3),propagationFanoutCap:exports_external.number().int().min(0).max(1e4).default(20),propagationWindowDays:exports_external.number().int().min(0).max(3650).default(30),propagationRelatednessThreshold:exports_external.number().min(0).max(1).default(0.7),explorationRate:exports_external.number().min(0).max(1).default(0.05),verdictPayloadCapBytes:exports_external.number().int().min(0).max(1048576).default(8192),initialQValue:exports_external.number().min(0).max(1).default(0.5)}).default({learningRate:0.1,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,promotionMinRetrievals:5,propagationFraction:0.3,propagationFanoutCap:20,propagationWindowDays:30,propagationRelatednessThreshold:0.7,explorationRate:0.05,verdictPayloadCapBytes:8192,initialQValue:0.5}),consolidation:exports_external.object({enabled:exports_external.boolean().default(!1),maxClustersPerPass:exports_external.number().int().min(1).max(100).default(10),jaccardThreshold:exports_external.number().min(0).max(1).default(0.3),autoApplyMinConfidence:exports_external.number().min(0).max(1).default(0.6),decayHalfLifeDays:exports_external.object({user_preference:exports_external.number().int().min(0).max(36500).default(0),project_fact:exports_external.number().int().min(0).max(36500).default(0),architecture_decision:exports_external.number().int().min(0).max(36500).default(0),repo_convention:exports_external.number().int().min(0).max(36500).default(0),api_finding:exports_external.number().int().min(0).max(36500).default(180),code_pattern:exports_external.number().int().min(0).max(36500).default(90),test_pattern:exports_external.number().int().min(0).max(36500).default(90),failure_pattern:exports_external.number().int().min(0).max(36500).default(90),security_note:exports_external.number().int().min(0).max(36500).default(0),evidence:exports_external.number().int().min(0).max(36500).default(180),todo:exports_external.number().int().min(0).max(36500).default(30),scratch:exports_external.number().int().min(0).max(36500).default(7)}).default({user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7})}).default({enabled:!1,maxClustersPerPass:10,jaccardThreshold:0.3,autoApplyMinConfidence:0.6,decayHalfLifeDays:{user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7}}),hardDelete:exports_external.boolean().default(!1),embeddings:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().default("Xenova/all-MiniLM-L6-v2"),dimension:exports_external.number().int().min(1).default(384),version:exports_external.string().optional(),cacheSize:exports_external.number().int().min(1).default(256)}).default({enabled:!1,model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheSize:256}),retrieval:exports_external.object({rrfK:exports_external.number().int().min(1).default(60),weights:exports_external.object({lexical:exports_external.number().min(0).max(1).default(0.5),dense:exports_external.number().min(0).max(1).default(0.4),metadata:exports_external.number().min(0).max(1).default(0.1)}).default({lexical:0.5,dense:0.4,metadata:0.1}),rerank:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().optional()}).default({enabled:!1}),latencyBudgetMs:exports_external.number().int().min(0).default(250)}).default({rrfK:60,weights:{lexical:0.5,dense:0.4,metadata:0.1},rerank:{enabled:!1},latencyBudgetMs:250})}),CuratorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),init_enabled:exports_external.boolean().default(!0),phase_enabled:exports_external.boolean().default(!0),postmortem_enabled:exports_external.boolean().default(!0),max_summary_tokens:exports_external.number().min(500).max(8000).default(2000),min_knowledge_confidence:exports_external.number().min(0).max(1).default(0.7),compliance_report:exports_external.boolean().default(!0),suppress_warnings:exports_external.boolean().default(!0),drift_inject_max_chars:exports_external.number().min(100).max(2000).default(500),llm_timeout_ms:exports_external.number().int().min(5000).max(600000).default(300000),skill_generation_enabled:exports_external.boolean().default(!0),skill_generation_mode:exports_external.enum(["draft","active"]).default("draft"),min_skill_confidence:exports_external.number().min(0).max(1).default(0.7),min_skill_confirmations:exports_external.number().int().min(1).max(50).default(2)}),ArchitecturalSupervisionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["advisory","gate"]).default("advisory"),run_on:exports_external.enum(["phase_complete"]).default("phase_complete"),summary_model:exports_external.string().min(1).optional(),max_agent_summary_words:exports_external.number().int().min(20).max(500).default(100),max_phase_summary_words:exports_external.number().int().min(50).max(1000).default(250),allow_concerns_to_complete:exports_external.boolean().default(!0),persist_knowledge_recommendations:exports_external.boolean().default(!1),provenance_verify:exports_external.boolean().default(!1)}),KnowledgeApplicationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["warn","enforce"]).default("warn"),min_confidence:exports_external.number().min(0).max(1).default(0.85),critical_requires_ack:exports_external.boolean().default(!0),require_skill_refs:exports_external.boolean().default(!0),high_risk_tools:exports_external.array(exports_external.string()).default(["save_plan","update_task_status","phase_complete","task","Task"]),max_gate_denials:exports_external.number().int().min(1).max(100).default(5),gate_staleness_ms:exports_external.number().int().min(1e4).max(3600000).default(600000)}),SkillPropagationAudienceSchema=exports_external.string().max(64).refine((value)=>value!=="swarm-plugin",{message:"swarm-plugin is reserved for plugin-internal skill routing"}).refine((value)=>!value.startsWith("runner:"),{message:"runner:* values are derived from the active runner"}).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,{message:"audiences must be lowercase domain tokens"}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1),audiences:exports_external.array(SkillPropagationAudienceSchema).max(16).transform((values)=>[...new Set(values)]).default([])}),SkillImproverConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),max_calls_per_day:exports_external.number().int().min(1).max(1000).default(10),trigger:exports_external.enum(["manual","scheduled"]).default("manual"),consolidation_interval_hours:exports_external.number().int().min(1).max(720).default(24),consolidation_max_calls_per_run:exports_external.number().int().min(1).max(100).default(1),targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).default(["skills","spec","architect_prompt","knowledge"]),write_mode:exports_external.enum(["proposal","draft_skills"]).default("proposal"),require_user_approval:exports_external.boolean().default(!0),quota_window:exports_external.enum(["utc","local"]).default("utc"),allow_deterministic_fallback:exports_external.boolean().default(!0)}),SkillsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1)}),SpecWriterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),allow_spec_write:exports_external.boolean().default(!0)}),SlopDetectorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),classThreshold:exports_external.number().int().min(1).default(3),commentStripThreshold:exports_external.number().int().min(1).default(5),diffLineThreshold:exports_external.number().int().min(10).default(200),importHygieneThreshold:exports_external.number().int().min(1).default(2)}),IncrementalVerifyConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),command:exports_external.union([exports_external.string(),exports_external.array(exports_external.string())]).nullable().default(null),timeoutMs:exports_external.number().int().min(1000).max(300000).default(30000),triggerAgents:exports_external.array(exports_external.string()).default(["coder"])}),CompactionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),observationThreshold:exports_external.number().min(1).max(99).default(40),reflectionThreshold:exports_external.number().min(1).max(99).default(60),emergencyThreshold:exports_external.number().min(1).max(99).default(80),preserveLastNTurns:exports_external.number().int().min(1).default(5)}),PrmConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),pattern_thresholds:exports_external.object({repetition_loop:exports_external.number().min(1).default(2),ping_pong:exports_external.number().min(1).default(2),expansion_drift:exports_external.number().min(1).default(3),stuck_on_test:exports_external.number().min(1).default(3),context_thrash:exports_external.number().min(1).default(3)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3})),max_trajectory_lines:exports_external.number().min(10).default(1000),escalation_enabled:exports_external.boolean().default(!0),detection_timeout_ms:exports_external.number().min(10).default(100)}),AgentAuthorityRuleSchema=exports_external.object({readOnly:exports_external.boolean().optional(),blockedExact:exports_external.array(exports_external.string()).optional(),allowedExact:exports_external.array(exports_external.string()).optional(),blockedPrefix:exports_external.array(exports_external.string()).optional(),allowedPrefix:exports_external.array(exports_external.string()).optional(),blockedZones:exports_external.array(exports_external.enum(["production","test","config","generated","docs","build"])).optional(),blockedGlobs:exports_external.array(exports_external.string()).optional(),allowedGlobs:exports_external.array(exports_external.string()).optional(),allowedCaseSensitiveGlobs:exports_external.array(exports_external.string()).optional()}),AuthorityConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),rules:exports_external.record(exports_external.string(),AgentAuthorityRuleSchema).default({}),universal_deny_prefixes:exports_external.array(exports_external.string().min(1)).default([]),verifier_config_paths:exports_external.array(exports_external.string()).optional().describe("Additional glob patterns for verifier config files that are merged into the architect agent's blockedGlobs at plugin init. Writes to matching files are blocked by the authority layer.")}),GeneralCouncilMemberConfigSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),persona:exports_external.string().optional()}).strict(),GeneralCouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),searchProvider:exports_external.enum(["tavily","brave"]).default("tavily"),searchApiKey:exports_external.string().optional(),members:exports_external.array(GeneralCouncilMemberConfigSchema).default([]),presets:exports_external.record(exports_external.string(),exports_external.array(GeneralCouncilMemberConfigSchema)).default({}),deliberate:exports_external.boolean().default(!0),moderator:exports_external.boolean().default(!0),moderatorModel:exports_external.string().optional(),maxSourcesPerMember:exports_external.number().int().min(1).max(20).default(5)}).strict(),CouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxRounds:exports_external.number().int().min(1).max(10).default(3),parallelTimeoutMs:exports_external.number().int().min(5000).max(120000).default(30000),vetoPriority:exports_external.boolean().default(!0),requireAllMembers:exports_external.boolean().default(!1).describe("When true, submit_council_verdicts rejects if fewer than 5 member verdicts are provided. Equivalent to minimumMembers: 5."),minimumMembers:exports_external.number().int().min(1).max(5).default(3).describe("Minimum distinct council member verdicts required for synthesis. Default 3. Set to 1 to disable quorum enforcement. requireAllMembers: true overrides this to 5 (stricter constraint wins)."),escalateOnMaxRounds:exports_external.string().optional().describe("Optional webhook URL or handler name invoked when maxRounds is reached without APPROVE. Declared for forward compatibility; no behavior is implemented yet."),phaseConcernsAllowComplete:exports_external.boolean().default(!0).describe("When true, a phase-level council CONCERNS verdict with only MEDIUM/LOW findings does NOT block phase completion — the advisory notes are logged as warnings and the phase proceeds. When false, CONCERNS blocks like REJECT. Note: HIGH/CRITICAL findings from CONCERNS members are always promoted to requiredFixes and block at the tool level regardless of this setting. Default: true."),general:GeneralCouncilConfigSchema.optional()}).strict(),PrMonitorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),poll_interval_seconds:exports_external.number().int().min(30).max(300).default(60),max_subscriptions:exports_external.number().int().min(1).max(100).default(20),max_prs_per_cycle:exports_external.number().int().min(1).max(20).default(5),max_concurrent_pr_polls:exports_external.number().int().min(1).max(10).default(3),poll_timeout_ms:exports_external.number().int().min(5000).max(120000).default(30000),failure_threshold:exports_external.number().int().min(1).max(20).default(5),cooldown_seconds:exports_external.number().int().min(5).max(600).default(30),max_cooldown_seconds:exports_external.number().int().min(30).max(3600).default(300),cleanup_ttl_days:exports_external.number().int().min(1).max(90).default(7),auto_unsubscribe_on_merge:exports_external.boolean().default(!0),auto_unsubscribe_on_close:exports_external.boolean().default(!0),notify_ci_failure:exports_external.boolean().default(!0),notify_new_comments:exports_external.boolean().default(!0),notify_merge_conflict:exports_external.boolean().default(!0),notify_review_activity:exports_external.boolean().default(!0),notify_merged:exports_external.boolean().default(!0),notify_closed:exports_external.boolean().default(!0),notify_ci_success:exports_external.boolean().default(!1),auto_pr_feedback:exports_external.boolean().default(!1),event_delivery:exports_external.enum(["advisory","prompt"]).default("prompt"),auto_subscribe_on_pr_create:exports_external.boolean().default(!0)}).strict(),ParallelizationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxConcurrentTasks:exports_external.number().int().min(1).max(64).default(1),evidenceLockTimeoutMs:exports_external.number().int().min(1000).max(300000).default(60000),max_coders:exports_external.number().int().min(1).max(16).default(3),max_reviewers:exports_external.number().int().min(1).max(16).default(2)}),WorktreeIsolationConfigSchema=exports_external.object({policy:exports_external.enum(["auto","required","disabled"]).default("auto"),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge"),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).default("skip"),serialization_release_after_dispatches:exports_external.number().int().positive().default(5),serialization_release_after_ms:exports_external.number().int().positive().default(60000),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),LeanTurboConfigSchema=exports_external.object({max_parallel_coders:exports_external.number().int().min(1).max(6).default(4),require_declared_scope:exports_external.boolean().default(!0),conflict_policy:exports_external.enum(["serialize","degrade"]).default("serialize"),degrade_on_risk:exports_external.boolean().default(!0),phase_reviewer:exports_external.boolean().default(!0),phase_critic:exports_external.boolean().default(!0),integrated_diff_required:exports_external.boolean().default(!0),allow_docs_only_without_reviewer:exports_external.boolean().default(!1),worktree_isolation:exports_external.boolean().default(!0),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge").optional(),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).optional(),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),EpicConfigSchema=exports_external.object({cochange:exports_external.object({enabled:exports_external.boolean().default(!1),threshold:exports_external.number().min(-1).max(1).default(0.6),min_co_changes:exports_external.number().int().min(1).default(5)}).strict().optional(),mode:exports_external.object({enabled:exports_external.boolean().default(!1),activation_threshold:exports_external.number().min(0).max(1).default(0.3),min_commits_for_signal:exports_external.number().int().min(1).default(20)}).strict().optional(),calibration:exports_external.object({enabled:exports_external.boolean().default(!0),floor_threshold:exports_external.number().min(0).max(1).default(0.05),tighten_step:exports_external.number().min(0).max(1).default(0.02),loosen_step:exports_external.number().min(0).max(1).default(0.01),loosen_window:exports_external.number().int().min(1).default(10)}).strict().optional()}).strict(),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:EpicConfigSchema.optional()}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:EpicConfigSchema.optional()}),TurboConfigSchema=exports_external.discriminatedUnion("strategy",[StandardTurboConfigSchema,LeanTurboStrategyConfigSchema]),ExternalSkillCandidateSourceTypeSchema=exports_external.enum(["github","url","collection","manual_import"]),ExternalSkillCandidateEvaluationVerdictSchema=exports_external.enum(["pending","in_review","quarantined","passed","rejected","promoted","revoked"]),DiscoverySourceSchema=exports_external.object({type:ExternalSkillCandidateSourceTypeSchema,location:exports_external.string().min(1),enabled:exports_external.boolean().default(!0),trust_level:exports_external.enum(["low","medium","high"]).default("low").optional()}),ExternalSkillCandidateSchema=exports_external.object({id:exports_external.string().uuid(),source_url:exports_external.string().url(),source_type:ExternalSkillCandidateSourceTypeSchema,publisher:exports_external.string().min(1),sha256:exports_external.string().regex(/^[a-f0-9]{64}$/),fetched_at:exports_external.string().datetime(),skill_name:exports_external.string().optional(),skill_description:exports_external.string().optional(),skill_body:exports_external.string(),risk_flags:exports_external.array(exports_external.string()).default([]),evaluation_verdict:ExternalSkillCandidateEvaluationVerdictSchema.default("pending"),evaluation_history:exports_external.array(exports_external.object({verdict:ExternalSkillCandidateEvaluationVerdictSchema,timestamp:exports_external.string().datetime(),actor:exports_external.string(),reason:exports_external.string().optional(),candidate_id:exports_external.string().optional(),original_verdict:ExternalSkillCandidateEvaluationVerdictSchema.optional(),gate_results:exports_external.array(exports_external.object({gate:exports_external.string(),verdict:exports_external.string()})).optional(),risk_assessment:exports_external.object({total_flags:exports_external.number().int().nonnegative(),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning"]),category:exports_external.string()}))}).optional(),risk_flags_count:exports_external.number().int().nonnegative().optional(),provenance_snapshot:exports_external.object({sha256:exports_external.string(),source_url:exports_external.string(),publisher:exports_external.string(),fetched_at:exports_external.string().datetime().optional()}).optional(),target_path:exports_external.string().optional(),promoted_content_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),original_evaluation:exports_external.record(exports_external.string(),exports_external.unknown()).optional()})).default([])}),ExternalSkillsConfigSchema=exports_external.object({curation_enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().int().min(1).max(1e4).default(500),max_bytes_per_candidate:exports_external.number().int().min(1024).max(10485760).default(1048576),eviction_policy:exports_external.enum(["fifo"]).default("fifo"),ttl_days:exports_external.number().int().min(1).max(3650).default(90),evaluation_enabled:exports_external.boolean().default(!1),sources:exports_external.array(DiscoverySourceSchema).default([]),max_candidates_per_discovery:exports_external.number().int().min(1).max(1000).default(50),max_concurrent_fetches:exports_external.number().int().min(1).max(20).default(5),fetch_timeout_ms:exports_external.number().int().min(1000).max(300000).default(30000)}),DEFAULT_EXTERNAL_SKILLS_CONFIG={curation_enabled:!1,max_candidates:500,max_bytes_per_candidate:1048576,eviction_policy:"fifo",ttl_days:90,evaluation_enabled:!1,sources:[],max_candidates_per_discovery:50,max_concurrent_fetches:5,fetch_timeout_ms:30000},DEFAULT_SKILLS_CONFIG={enabled:!1};PluginConfigSchema=exports_external.object({agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional(),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}),auto_select_architect:exports_external.union([exports_external.boolean(),exports_external.string()]).optional().transform((v)=>{if(v===void 0)return;if(typeof v==="boolean")return v;let trimmed=v.trim();return trimmed===""?!1:trimmed}),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional(),max_iterations:exports_external.number().min(1).max(10).default(5),pipeline:PipelineConfigSchema.optional(),phase_complete:PhaseCompleteConfigSchema.optional(),qa_retry_limit:exports_external.number().min(1).max(10).default(3),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced"),inject_phase_reminders:exports_external.boolean().default(!0),hooks:HooksConfigSchema.optional(),gates:GateConfigSchema.optional(),context_budget:ContextBudgetConfigSchema.optional(),pricing:PricingConfigSchema.optional(),guardrails:GuardrailsConfigSchema.optional(),watchdog:WatchdogConfigSchema.optional(),self_review:SelfReviewConfigSchema.optional(),auto_review:AutoReviewConfigSchema.optional(),tool_filter:ToolFilterConfigSchema.optional(),authority:AuthorityConfigSchema.optional(),plan_cursor:PlanCursorConfigSchema.optional(),context_map:ContextMapConfigSchema.optional(),repo_graph:RepoGraphConfigSchema.optional(),evidence:EvidenceConfigSchema.optional(),summaries:SummaryConfigSchema.optional(),review_passes:ReviewPassesConfigSchema.optional(),adversarial_detection:AdversarialDetectionConfigSchema.optional(),adversarial_testing:AdversarialTestingConfigSchema.optional(),integration_analysis:IntegrationAnalysisConfigSchema.optional(),docs:DocsConfigSchema.optional(),design_docs:DesignDocsConfigSchema.optional(),ui_review:UIReviewConfigSchema.optional(),compaction_advisory:CompactionAdvisoryConfigSchema.optional(),lint:LintConfigSchema.optional(),secretscan:SecretscanConfigSchema.optional(),checkpoint:CheckpointConfigSchema.optional(),apply_patch:ApplyPatchConfigSchema.optional(),automation:AutomationConfigSchema.optional(),knowledge:KnowledgeConfigSchema.optional(),memory:MemoryConfigSchema.optional(),curator:CuratorConfigSchema.optional(),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional(),knowledge_application:KnowledgeApplicationConfigSchema.optional(),skillPropagation:SkillPropagationConfigSchema.optional(),skill_improver:SkillImproverConfigSchema.optional(),spec_writer:SpecWriterConfigSchema.optional(),tool_output:exports_external.object({truncation_enabled:exports_external.boolean().default(!0),max_lines:exports_external.number().min(10).max(500).default(150),per_tool:exports_external.record(exports_external.string(),exports_external.number()).optional(),truncation_tools:exports_external.array(exports_external.string()).optional().describe("Tools to apply output truncation to. Defaults to diff, symbols, bash, shell, test_runner, lint, pre_check_batch, complexity_hotspots, pkg_audit, sbom_generate, schema_drift.")}).optional(),slop_detector:SlopDetectorConfigSchema.optional(),todo_gate:exports_external.object({enabled:exports_external.boolean().default(!0),max_high_priority:exports_external.number().int().min(-1).default(0).describe("Max new high-priority TODOs (FIXME/HACK/XXX) before warning. 0 = warn on any. Set to -1 to disable."),block_on_threshold:exports_external.boolean().default(!1).describe("If true, block phase completion when threshold exceeded. Default: advisory only.")}).optional(),incremental_verify:IncrementalVerifyConfigSchema.optional(),compaction_service:CompactionConfigSchema.optional(),prm:PrmConfigSchema.optional(),council:CouncilConfigSchema.optional(),parallelization:ParallelizationConfigSchema.optional(),worktree:WorktreeIsolationConfigSchema.optional(),turbo:TurboConfigSchema.optional(),turbo_mode:exports_external.boolean().default(!1).optional(),quiet:exports_external.boolean().default(!0).optional(),version_check:exports_external.boolean().default(!0).optional(),full_auto:exports_external.object({enabled:exports_external.boolean().default(!1),locked:exports_external.boolean().default(!1),critic_model:exports_external.string().optional(),max_interactions_per_phase:exports_external.number().int().min(5).max(200).default(50),deadlock_threshold:exports_external.number().int().min(2).max(10).default(3),escalation_mode:exports_external.enum(["pause","terminate"]).default("pause"),mode:exports_external.enum(["assisted","supervised","strict"]).default("supervised"),fail_closed:exports_external.boolean().default(!0),permission_policy:exports_external.object({enabled:exports_external.boolean().default(!0),trusted_roots:exports_external.array(exports_external.string()).default(["."]),trusted_domains:exports_external.array(exports_external.string()).default([]),protected_paths:exports_external.array(exports_external.string()).default([".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"]),allow_defaults:exports_external.boolean().default(!0)}).default(()=>({enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0})),denials:exports_external.object({max_consecutive:exports_external.number().int().min(1).max(50).default(3),max_total:exports_external.number().int().min(1).max(500).default(20),on_limit:exports_external.enum(["pause","terminate"]).default("pause")}).default(()=>({max_consecutive:3,max_total:20,on_limit:"pause"})),oversight:exports_external.object({on_plan_change:exports_external.boolean().default(!0),on_task_completion:exports_external.boolean().default(!1),on_phase_boundary:exports_external.boolean().default(!0),on_high_risk_action:exports_external.boolean().default(!0),on_subagent_return_warning:exports_external.boolean().default(!0),every_tool_calls:exports_external.number().int().min(0).max(1e4).default(25),every_architect_turns:exports_external.number().int().min(0).max(1000).default(5),every_minutes:exports_external.number().int().min(0).max(1440).default(20),max_dispatch_retries:exports_external.number().int().min(0).max(10).default(2),max_consecutive_dispatch_failures:exports_external.number().int().min(0).max(50).default(3)}).default(()=>({on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}))}).optional().default(()=>({enabled:!1,locked:!1,max_interactions_per_phase:50,deadlock_threshold:3,escalation_mode:"pause",mode:"supervised",fail_closed:!0,permission_policy:{enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0},denials:{max_consecutive:3,max_total:20,on_limit:"pause"},oversight:{on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional()})});var exports_loader={};__export(exports_loader,{loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,formatZodIssues:()=>formatZodIssues,deepMerge:()=>deepMerge,MAX_MERGE_DEPTH:()=>MAX_MERGE_DEPTH,MAX_CONFIG_FILE_BYTES:()=>MAX_CONFIG_FILE_BYTES});import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path.join(os.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs.statSync(configPath).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=fs.readFileSync(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(!(error49 instanceof Error&&("code"in error49)&&error49.code==="ENOENT")){let errorMessage=error49 instanceof Error?error49.message:String(error49);return advisoryWarn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config load failed. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0}}return{config:null,fileExisted:!1,hadError:!1}}}function migratePresetsConfig(raw){if(raw.presets&&typeof raw.presets==="object"&&!raw.agents){let presetName=raw.preset||"remote",presets=raw.presets,activePreset=presets[presetName]||Object.values(presets)[0];if(activePreset&&typeof activePreset==="object"){let migrated={...raw,agents:activePreset};return delete migrated.preset,delete migrated.presets,delete migrated.swarm_mode,advisoryWarn("[opencode-swarm] Migrated v6.12 presets config to agents format. Consider updating your opencode-swarm.json."),migrated}}return raw}function sanitizeExternalSkillsConfig(raw){if(!("external_skills"in raw)||raw.external_skills===void 0)return raw;let esResult=ExternalSkillsConfigSchema.safeParse(raw.external_skills);if(esResult.success)return{...raw,external_skills:resolveExternalSkillsConfig(esResult.data)};advisoryWarn("[opencode-swarm] external_skills config validation failed:",formatZodIssues(esResult.error)),advisoryWarn("[opencode-swarm] External skills curation disabled due to invalid config. Fix the external_skills section to enable it.");let cleaned={...raw};return delete cleaned.external_skills,cleaned}function sanitizeGatesConfig(raw){if(!("gates"in raw)||raw.gates===void 0)return raw;if(typeof raw.gates!=="object"||raw.gates===null||Array.isArray(raw.gates)){advisoryWarn("[opencode-swarm] gates config validation failed: expected an object. Quality gates will use defaults; other config sections remain active.");let cleaned2={...raw};return delete cleaned2.gates,cleaned2}let gateSchemas=GateConfigSchema.shape,cleanedGates={...raw.gates};for(let[key,value]of Object.entries(cleanedGates)){let schema=gateSchemas[key];if(!schema){advisoryWarn(`[opencode-swarm] Unknown gates config section "gates.${key}" ignored. Other config sections remain active.`),delete cleanedGates[key];continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[key],sectionValue=value;if(knownFields&&typeof value==="object"&&value!==null&&!Array.isArray(value)){let cleanedSection={...value},knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(cleanedSection))if(!knownFieldSet.has(fieldName))advisoryWarn(`[opencode-swarm] Unknown gates config key "gates.${key}.${fieldName}" ignored. Other config sections remain active.`),delete cleanedSection[fieldName];sectionValue=cleanedSection,cleanedGates[key]=cleanedSection}let sectionResult=schema.safeParse(sectionValue);if(!sectionResult.success)advisoryWarn(`[opencode-swarm] gates.${key} config validation failed; that gate section will use defaults and other config sections remain active:`,formatZodIssues(sectionResult.error)),delete cleanedGates[key]}let gatesResult=GateConfigSchema.safeParse(cleanedGates);if(gatesResult.success)return{...raw,gates:gatesResult.data};advisoryWarn("[opencode-swarm] gates config validation failed after section cleanup; quality gates will use defaults and other config sections remain active:",formatZodIssues(gatesResult.error));let cleaned={...raw};return delete cleaned.gates,cleaned}function sanitizeSectionConfigs(raw){return sanitizeGatesConfig(sanitizeExternalSkillsConfig(raw))}function formatZodIssues(error49){if(error49.issues.length===0)return"";return error49.issues.map((issue2)=>{let dotted=issue2.path.map(String).join(".");return dotted?`${dotted}: ${issue2.message}`:issue2.message}).join("; ")}function stripUnrecognizedKeys(raw,error49){let removed=[],cleaned=structuredClone(raw);for(let issue2 of error49.issues){if(issue2.code!=="unrecognized_keys")continue;let keys=issue2.keys??[],node=cleaned;for(let seg of issue2.path)if(node&&typeof node==="object")node=node[seg];else{node=void 0;break}if(!node||typeof node!=="object")continue;for(let key of keys)if(key in node){delete node[key];let dotted=[...issue2.path.map(String),key].join(".");removed.push(dotted)}}return{cleaned,removed}}function parseConfigWithFallback(mergedRaw,rawUserConfig,failedResult,loadedFromFile,configHadErrors){let result=failedResult,secure=(config2)=>loadedFromFile&&configHadErrors?PluginConfigSchema.parse({...config2,guardrails:{enabled:!0}}):config2,{cleaned,removed}=stripUnrecognizedKeys(mergedRaw,result.error);if(removed.length>0){let recovered=PluginConfigSchema.safeParse(cleaned);if(recovered.success)return advisoryWarn(`[opencode-swarm] Ignored ${removed.length} unrecognized config key(s): ${removed.join(", ")}. The rest of your configuration was preserved. Fix or remove these keys.`),secure(recovered.data)}if(rawUserConfig){let userSanitized=sanitizeSectionConfigs(rawUserConfig??{}),userParseResult=PluginConfigSchema.safeParse(userSanitized);if(userParseResult.success)return advisoryWarn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),secure(userParseResult.data);let userStripped=stripUnrecognizedKeys(userSanitized,userParseResult.error);if(userStripped.removed.length>0){let userRecovered=PluginConfigSchema.safeParse(userStripped.cleaned);if(userRecovered.success)return advisoryWarn(`[opencode-swarm] Project config ignored; also ignored ${userStripped.removed.length} unrecognized user-config key(s): ${userStripped.removed.join(", ")}.`),secure(userRecovered.data)}}let offending=stripUnrecognizedKeys(mergedRaw,result.error).removed;if(offending.length>0)advisoryWarn(`[opencode-swarm] Merged config validation failed. Unrecognized key(s): ${offending.join(", ")}.`);else advisoryWarn("[opencode-swarm] Merged config validation failed:",formatZodIssues(result.error));return advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}function rawFullAutoLocked(raw){if(!raw||typeof raw!=="object")return!1;let fullAuto=raw.full_auto;if(!fullAuto||typeof fullAuto!=="object"||Array.isArray(fullAuto))return!1;return fullAuto.locked===!0}function loadPluginConfig(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),rawUserConfig=userResult.config,rawProjectConfig=projectResult.config,loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fullAutoRaw=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fullAutoRaw,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeSectionConfigs(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(result.success){if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}return parseConfigWithFallback(mergedRaw,rawUserConfig,result,loadedFromFile,configHadErrors)}function loadPluginConfigWithMeta(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return{config:loadPluginConfig(directory),loadedFromFile,configHadErrors}}async function loadRawConfigFromPathAsync(configPath){try{if((await fsPromises.stat(configPath)).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=await fsPromises.readFile(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(error49.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return advisoryWarn(`[opencode-swarm] Failed to load config from ${configPath}:`,error49 instanceof Error?error49.message:String(error49)),{config:null,fileExisted:!0,hadError:!0}}}function reduceParsedConfig(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeSectionConfigs(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(result.success){if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}return parseConfigWithFallback(mergedRaw,rawUserConfig,result,loadedFromFile,configHadErrors)}async function loadPluginConfigWithMetaAsync(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),[userResult,projectResult]=await Promise.all([loadRawConfigFromPathAsync(userConfigPath),loadRawConfigFromPathAsync(projectConfigPath)]),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError;return{config:reduceParsedConfig(userResult.config,projectResult.config,loadedFromFile,configHadErrors),loadedFromFile,configHadErrors}}function loadAgentPrompt(agentName){let promptsDir=path.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path.join(promptsDir,`${agentName}.md`);if(fs.existsSync(promptPath))try{result.prompt=fs.readFileSync(promptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error49 instanceof Error?error49.message:String(error49))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error49 instanceof Error?error49.message:String(error49))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{init_warning_buffer();init_schema()});var ExecutionProfileSchema,TaskStatusSchema,TaskSizeSchema,PhaseStatusSchema,MigrationStatusSchema,TaskSchema,PhaseSchema,PlanSchema;var init_plan_schema=__esm(()=>{init_zod();ExecutionProfileSchema=exports_external.object({parallelization_enabled:exports_external.boolean().default(!1),max_concurrent_tasks:exports_external.number().int().min(1).max(64).default(10),council_parallel:exports_external.boolean().default(!0),locked:exports_external.boolean().default(!1),auto_proceed:exports_external.boolean().default(!1)}),TaskStatusSchema=exports_external.enum(["pending","in_progress","completed","blocked","closed"]),TaskSizeSchema=exports_external.enum(["small","medium","large"]),PhaseStatusSchema=exports_external.enum(["pending","in_progress","complete","completed","blocked","closed"]),MigrationStatusSchema=exports_external.enum(["native","migrated","migration_failed"]),TaskSchema=exports_external.object({id:exports_external.string(),phase:exports_external.number().int().min(1),status:TaskStatusSchema.default("pending"),size:TaskSizeSchema.default("small"),description:exports_external.string().min(1),depends:exports_external.array(exports_external.string()).default([]),acceptance:exports_external.string().optional(),files_touched:exports_external.array(exports_external.string()).default([]),evidence_path:exports_external.string().optional(),blocked_reason:exports_external.string().optional(),fr_refs:exports_external.array(exports_external.string()).optional()}),PhaseSchema=exports_external.object({id:exports_external.number().int().min(1),name:exports_external.string().min(1),status:PhaseStatusSchema.default("pending"),tasks:exports_external.array(TaskSchema).default([]),type:exports_external.enum(["code","non-code"]).optional(),required_agents:exports_external.array(exports_external.string()).optional()}),PlanSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),title:exports_external.string().min(1),swarm:exports_external.string().min(1),current_phase:exports_external.number().int().min(1).optional(),phases:exports_external.array(PhaseSchema).min(1),migration_status:MigrationStatusSchema.optional(),specMtime:exports_external.string().optional(),specHash:exports_external.string().optional(),execution_profile:ExecutionProfileSchema.optional()})});function stripCodeBlocks(content){return content.replace(FENCED_BLOCK_PATTERN,"").replace(INLINE_CODE_PATTERN,"")}function getLineNumber(content,position){return(content.substring(0,position).match(/\n/g)||[]).length+1}function validateSpecContent(content){let issues=[];if(!content||content.trim().length===0)return{valid:!1,issues:[{line:1,message:"Content is empty"}]};let strippedContent=stripCodeBlocks(content),frMatches=strippedContent.match(FR_ID_PATTERN);if(!frMatches||frMatches.length===0)issues.push({line:1,message:"No FR-### requirement IDs found in spec content"});let obligationMatches=strippedContent.match(OBLIGATION_PATTERN);if(!obligationMatches||obligationMatches.length===0)issues.push({line:1,message:"No obligation keywords (MUST, SHALL, SHOULD, MAY) found in spec content"});let sectionMatches=strippedContent.match(SECTION_HEADER_PATTERN);if(!sectionMatches||sectionMatches.length===0)issues.push({line:1,message:"No section headers (## Section Name) found in spec content"});let idMatches=strippedContent.matchAll(/\bFR-(\d{3})\b/g);for(let idMatch of idMatches)if(parseInt(idMatch[1],10)===0){let pos=idMatch.index;issues.push({line:getLineNumber(strippedContent,pos),message:`Invalid FR-ID "${idMatch[0]}" — number must be 001-999`})}return{valid:issues.length===0,issues}}var ObligationSchema,SpecRequirementSchema,SpecScenarioSchema,SpecSectionSchema,SwarmSpecSchema,SpecDeltaSchema,DeltaSpecSchema,FENCED_BLOCK_PATTERN,INLINE_CODE_PATTERN,FR_ID_PATTERN,OBLIGATION_PATTERN,SECTION_HEADER_PATTERN;var init_spec_schema=__esm(()=>{init_zod();ObligationSchema=exports_external.enum(["MUST","SHALL","SHOULD","MAY"]),SpecRequirementSchema=exports_external.object({id:exports_external.string().regex(/^FR-(?!000)\d{3}$/,"Requirement ID must match FR-### pattern (e.g., FR-001)"),obligation:ObligationSchema,text:exports_external.string().min(1)}),SpecScenarioSchema=exports_external.object({name:exports_external.string().min(1),given:exports_external.array(exports_external.string()).optional().default([]),when:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "when" clause'),thenClauses:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "then" clause')}),SpecSectionSchema=exports_external.object({name:exports_external.string().min(1),requirements:exports_external.array(SpecRequirementSchema).default([])}),SwarmSpecSchema=exports_external.object({title:exports_external.string().min(1),purpose:exports_external.string().min(1),sections:exports_external.array(SpecSectionSchema).min(1,"Spec must have at least one section")}),SpecDeltaSchema=exports_external.object({added:exports_external.array(SpecRequirementSchema).default([]),modified:exports_external.array(SpecRequirementSchema).default([]),removed:exports_external.array(SpecRequirementSchema).default([])}),DeltaSpecSchema=exports_external.union([SwarmSpecSchema,SpecDeltaSchema]),FENCED_BLOCK_PATTERN=/```[\s\S]*?```/g,INLINE_CODE_PATTERN=/`[^`]*`/g,FR_ID_PATTERN=/\bFR-\d{3}\b/g,OBLIGATION_PATTERN=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SECTION_HEADER_PATTERN=/^##\s+.+$/gm});function resolveWorktreeIsolationConfig(config2){if(config2.worktree)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,...config2.worktree};let lean=config2.turbo?.strategy==="lean"?config2.turbo.lean:void 0;if(lean?.worktree_isolation)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,policy:"auto",merge_strategy:lean.merge_strategy??"merge",worktree_dir:lean.worktree_dir,deps_strategy:lean.deps_strategy??"skip",runtime_isolation:lean.runtime_isolation??DEFAULT_WORKTREE_ISOLATION_CONFIG.runtime_isolation};return DEFAULT_WORKTREE_ISOLATION_CONFIG}var init_worktree_isolation_config=__esm(()=>{init_constants()});var exports_config={};__export(exports_config,{validateSpecContent:()=>validateSpecContent,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,_internals:()=>_internals2,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,TestEvidenceSchema:()=>TestEvidenceSchema,TaskStatusSchema:()=>TaskStatusSchema,TaskSizeSchema:()=>TaskSizeSchema,TaskSchema:()=>TaskSchema,SwarmSpecSchema:()=>SwarmSpecSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SpecSectionSchema:()=>SpecSectionSchema,SpecScenarioSchema:()=>SpecScenarioSchema,SpecRequirementSchema:()=>SpecRequirementSchema,SpecDeltaSchema:()=>SpecDeltaSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,ReviewEvidenceSchema:()=>ReviewEvidenceSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QA_AGENTS:()=>QA_AGENTS,PricingConfigSchema:()=>PricingConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanSchema:()=>PlanSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseStatusSchema:()=>PhaseStatusSchema,PhaseSchema:()=>PhaseSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,PIPELINE_AGENTS:()=>PIPELINE_AGENTS,ObligationSchema:()=>ObligationSchema,ORCHESTRATOR_NAME:()=>ORCHESTRATOR_NAME,NoteEvidenceSchema:()=>NoteEvidenceSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MigrationStatusSchema:()=>MigrationStatusSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,EvidenceVerdictSchema:()=>EvidenceVerdictSchema,EvidenceTypeSchema:()=>EvidenceTypeSchema,EvidenceSchema:()=>EvidenceSchema,EvidenceBundleSchema:()=>EvidenceBundleSchema,EVIDENCE_MAX_TASK_BYTES:()=>EVIDENCE_MAX_TASK_BYTES,EVIDENCE_MAX_PATCH_BYTES:()=>EVIDENCE_MAX_PATCH_BYTES,EVIDENCE_MAX_JSON_BYTES:()=>EVIDENCE_MAX_JSON_BYTES,DiffEvidenceSchema:()=>DiffEvidenceSchema,DeltaSpecSchema:()=>DeltaSpecSchema,DEFAULT_MODELS:()=>DEFAULT_MODELS,BaseEvidenceSchema:()=>BaseEvidenceSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,ApprovalEvidenceSchema:()=>ApprovalEvidenceSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,ALL_SUBAGENT_NAMES:()=>ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES:()=>ALL_AGENT_NAMES});var _internals2;var init_config=__esm(()=>{init_constants();init_evidence_schema();init_loader();init_loader();init_plan_schema();init_schema();init_spec_schema();init_worktree_isolation_config();_internals2={loadPluginConfigWithMeta}});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
158
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=(zodSchema)=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema);if(Object.assign(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached))delete schema2[key]}if(refSchema.$ref&&refSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key]))delete schema2[key]}}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){if(schema2.$ref=parentSeen.schema.$ref,parentSeen.def)for(let key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key]))delete schema2[key]}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(ctx.target==="draft-07")result.$schema="http://json-schema.org/draft-07/schema#";else if(ctx.target==="draft-04")result.$schema="http://json-schema.org/draft-04/schema#";else if(ctx.target==="openapi-3.0");if(ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(ctx.external);else if(Object.keys(defs).length>0)if(ctx.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch(_err){throw Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;if(def.rest&&isTransforming(def.rest,ctx))return!0;return!1}return!1}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{let ctx=initializeContext({...params,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process2(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var init_to_json_schema=__esm(()=>{init_registries()});function toJSONSchema(input,params){if("_idmap"in input){let registry2=input,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;process2(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return process2(input,ctx),extractDefs(ctx,input),finalize(ctx,input)}var formatMap,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){if(json.format=formatMap[format]??format,json.format==="")delete json.format;if(format==="time")delete json.format}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(regexes.length>1)json.allOf=[...regexes.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}},numberProcessor=(schema,ctx,_json,_params)=>{let json=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";if(typeof exclusiveMinimum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0;else json.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json.minimum=minimum,typeof exclusiveMinimum==="number"&&ctx.target!=="draft-04")if(exclusiveMinimum>=minimum)delete json.minimum;else delete json.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0;else json.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json.maximum=maximum,typeof exclusiveMaximum==="number"&&ctx.target!=="draft-04")if(exclusiveMaximum<=maximum)delete json.maximum;else delete json.exclusiveMaximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0")json.type="string",json.nullable=!0,json.enum=[null];else json.type="null"},undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values},literalProcessor=(schema,ctx,json,_params)=>{let def=schema._zod.def,vals=[];for(let val of def.values)if(val===void 0){if(ctx.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(ctx.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0")json.enum=[val];else json.const=val}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}},nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json,_params)=>{let _json=json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json,_params)=>{let _json=json,file={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file.minLength=minimum;if(maximum!==void 0)file.maxLength=maximum;if(mime)if(mime.length===1)file.contentMediaType=mime[0],Object.assign(_json,file);else Object.assign(_json,file),_json.anyOf=mime.map((m)=>({contentMediaType:m}));else Object.assign(_json,file)},successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array",json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})},objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object",json.properties={};let shape=def.shape;for(let key in shape)json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(ctx.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json.additionalProperties=!1;else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=!1}else if(def.catchall)json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive)json.oneOf=options;else json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf},tupleProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>process2(x,ctx,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){if(json.prefixItems=prefixItems,rest)json.items=rest}else if(ctx.target==="openapi-3.0"){if(json.items={anyOf:prefixItems},rest)json.items.anyOf.push(rest);if(json.minItems=prefixItems.length,!rest)json.maxItems=prefixItems.length}else if(json.items=prefixItems,rest)json.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum},recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=keyType._zod.bag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)json.patternProperties[pattern.source]=valueSchema}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12")json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values;if(keyValues){let validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0)json.required=validKeyValues}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process2(def.innerType,ctx,params),seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0")seen.ref=def.innerType,json.nullable=!0;else json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,innerType=ctx.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process2(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;process2(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors;var init_json_schema_processors=__esm(()=>{init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}});class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}}var init_json_schema_generator=__esm(()=>{init_json_schema_processors();init_to_json_schema()});var exports_json_schema={};var init_json_schema=()=>{};var exports_core2={};__export(exports_core2,{version:()=>version,util:()=>exports_util,treeifyError:()=>treeifyError,toJSONSchema:()=>toJSONSchema,toDotPath:()=>toDotPath,safeParseAsync:()=>safeParseAsync,safeParse:()=>safeParse,safeEncodeAsync:()=>safeEncodeAsync,safeEncode:()=>safeEncode,safeDecodeAsync:()=>safeDecodeAsync,safeDecode:()=>safeDecode,registry:()=>registry,regexes:()=>exports_regexes,process:()=>process2,prettifyError:()=>prettifyError,parseAsync:()=>parseAsync,parse:()=>parse,meta:()=>meta,locales:()=>exports_locales,isValidJWT:()=>isValidJWT,isValidBase64URL:()=>isValidBase64URL,isValidBase64:()=>isValidBase64,initializeContext:()=>initializeContext,globalRegistry:()=>globalRegistry,globalConfig:()=>globalConfig,formatError:()=>formatError,flattenError:()=>flattenError,finalize:()=>finalize,extractDefs:()=>extractDefs,encodeAsync:()=>encodeAsync,encode:()=>encode,describe:()=>describe,decodeAsync:()=>decodeAsync,decode:()=>decode,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,config:()=>config,clone:()=>clone,_xor:()=>_xor,_xid:()=>_xid,_void:()=>_void,_uuidv7:()=>_uuidv7,_uuidv6:()=>_uuidv6,_uuidv4:()=>_uuidv4,_uuid:()=>_uuid,_url:()=>_url,_uppercase:()=>_uppercase,_unknown:()=>_unknown,_union:()=>_union,_undefined:()=>_undefined2,_ulid:()=>_ulid,_uint64:()=>_uint64,_uint32:()=>_uint32,_tuple:()=>_tuple,_trim:()=>_trim,_transform:()=>_transform,_toUpperCase:()=>_toUpperCase,_toLowerCase:()=>_toLowerCase,_templateLiteral:()=>_templateLiteral,_symbol:()=>_symbol,_superRefine:()=>_superRefine,_success:()=>_success,_stringbool:()=>_stringbool,_stringFormat:()=>_stringFormat,_string:()=>_string,_startsWith:()=>_startsWith,_slugify:()=>_slugify,_size:()=>_size,_set:()=>_set,_safeParseAsync:()=>_safeParseAsync,_safeParse:()=>_safeParse,_safeEncodeAsync:()=>_safeEncodeAsync,_safeEncode:()=>_safeEncode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeDecode:()=>_safeDecode,_regex:()=>_regex,_refine:()=>_refine,_record:()=>_record,_readonly:()=>_readonly,_property:()=>_property,_promise:()=>_promise,_positive:()=>_positive,_pipe:()=>_pipe,_parseAsync:()=>_parseAsync,_parse:()=>_parse,_overwrite:()=>_overwrite,_optional:()=>_optional,_number:()=>_number,_nullable:()=>_nullable,_null:()=>_null2,_normalize:()=>_normalize,_nonpositive:()=>_nonpositive,_nonoptional:()=>_nonoptional,_nonnegative:()=>_nonnegative,_never:()=>_never,_negative:()=>_negative,_nativeEnum:()=>_nativeEnum,_nanoid:()=>_nanoid,_nan:()=>_nan,_multipleOf:()=>_multipleOf,_minSize:()=>_minSize,_minLength:()=>_minLength,_min:()=>_gte,_mime:()=>_mime,_maxSize:()=>_maxSize,_maxLength:()=>_maxLength,_max:()=>_lte,_map:()=>_map,_mac:()=>_mac,_lte:()=>_lte,_lt:()=>_lt,_lowercase:()=>_lowercase,_literal:()=>_literal,_length:()=>_length,_lazy:()=>_lazy,_ksuid:()=>_ksuid,_jwt:()=>_jwt,_isoTime:()=>_isoTime,_isoDuration:()=>_isoDuration,_isoDateTime:()=>_isoDateTime,_isoDate:()=>_isoDate,_ipv6:()=>_ipv6,_ipv4:()=>_ipv4,_intersection:()=>_intersection,_int64:()=>_int64,_int32:()=>_int32,_int:()=>_int,_includes:()=>_includes,_guid:()=>_guid,_gte:()=>_gte,_gt:()=>_gt,_float64:()=>_float64,_float32:()=>_float32,_file:()=>_file,_enum:()=>_enum,_endsWith:()=>_endsWith,_encodeAsync:()=>_encodeAsync,_encode:()=>_encode,_emoji:()=>_emoji2,_email:()=>_email,_e164:()=>_e164,_discriminatedUnion:()=>_discriminatedUnion,_default:()=>_default,_decodeAsync:()=>_decodeAsync,_decode:()=>_decode,_date:()=>_date,_custom:()=>_custom,_cuid2:()=>_cuid2,_cuid:()=>_cuid,_coercedString:()=>_coercedString,_coercedNumber:()=>_coercedNumber,_coercedDate:()=>_coercedDate,_coercedBoolean:()=>_coercedBoolean,_coercedBigint:()=>_coercedBigint,_cidrv6:()=>_cidrv6,_cidrv4:()=>_cidrv4,_check:()=>_check,_catch:()=>_catch,_boolean:()=>_boolean,_bigint:()=>_bigint,_base64url:()=>_base64url,_base64:()=>_base64,_array:()=>_array,_any:()=>_any,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,JSONSchemaGenerator:()=>JSONSchemaGenerator,JSONSchema:()=>exports_json_schema,Doc:()=>Doc,$output:()=>$output,$input:()=>$input,$constructor:()=>$constructor,$brand:()=>$brand,$ZodXor:()=>$ZodXor,$ZodXID:()=>$ZodXID,$ZodVoid:()=>$ZodVoid,$ZodUnknown:()=>$ZodUnknown,$ZodUnion:()=>$ZodUnion,$ZodUndefined:()=>$ZodUndefined,$ZodUUID:()=>$ZodUUID,$ZodURL:()=>$ZodURL,$ZodULID:()=>$ZodULID,$ZodType:()=>$ZodType,$ZodTuple:()=>$ZodTuple,$ZodTransform:()=>$ZodTransform,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodSymbol:()=>$ZodSymbol,$ZodSuccess:()=>$ZodSuccess,$ZodStringFormat:()=>$ZodStringFormat,$ZodString:()=>$ZodString,$ZodSet:()=>$ZodSet,$ZodRegistry:()=>$ZodRegistry,$ZodRecord:()=>$ZodRecord,$ZodRealError:()=>$ZodRealError,$ZodReadonly:()=>$ZodReadonly,$ZodPromise:()=>$ZodPromise,$ZodPrefault:()=>$ZodPrefault,$ZodPipe:()=>$ZodPipe,$ZodOptional:()=>$ZodOptional,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodObject:()=>$ZodObject,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodNumber:()=>$ZodNumber,$ZodNullable:()=>$ZodNullable,$ZodNull:()=>$ZodNull,$ZodNonOptional:()=>$ZodNonOptional,$ZodNever:()=>$ZodNever,$ZodNanoID:()=>$ZodNanoID,$ZodNaN:()=>$ZodNaN,$ZodMap:()=>$ZodMap,$ZodMAC:()=>$ZodMAC,$ZodLiteral:()=>$ZodLiteral,$ZodLazy:()=>$ZodLazy,$ZodKSUID:()=>$ZodKSUID,$ZodJWT:()=>$ZodJWT,$ZodIntersection:()=>$ZodIntersection,$ZodISOTime:()=>$ZodISOTime,$ZodISODuration:()=>$ZodISODuration,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODate:()=>$ZodISODate,$ZodIPv6:()=>$ZodIPv6,$ZodIPv4:()=>$ZodIPv4,$ZodGUID:()=>$ZodGUID,$ZodFunction:()=>$ZodFunction,$ZodFile:()=>$ZodFile,$ZodExactOptional:()=>$ZodExactOptional,$ZodError:()=>$ZodError,$ZodEnum:()=>$ZodEnum,$ZodEncodeError:()=>$ZodEncodeError,$ZodEmoji:()=>$ZodEmoji,$ZodEmail:()=>$ZodEmail,$ZodE164:()=>$ZodE164,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodDefault:()=>$ZodDefault,$ZodDate:()=>$ZodDate,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodCustom:()=>$ZodCustom,$ZodCodec:()=>$ZodCodec,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheck:()=>$ZodCheck,$ZodCatch:()=>$ZodCatch,$ZodCUID2:()=>$ZodCUID2,$ZodCUID:()=>$ZodCUID,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodBoolean:()=>$ZodBoolean,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBigInt:()=>$ZodBigInt,$ZodBase64URL:()=>$ZodBase64URL,$ZodBase64:()=>$ZodBase64,$ZodAsyncError:()=>$ZodAsyncError,$ZodArray:()=>$ZodArray,$ZodAny:()=>$ZodAny});var init_core2=__esm(()=>{init_util();init_regexes();init_locales();init_json_schema_processors();init_json_schema_generator();init_json_schema();init_core();init_parse();init_errors();init_schemas();init_checks();init_versions();init_registries();init_api();init_to_json_schema()});var exports_checks2={};__export(exports_checks2,{uppercase:()=>_uppercase,trim:()=>_trim,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,regex:()=>_regex,property:()=>_property,positive:()=>_positive,overwrite:()=>_overwrite,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonnegative:()=>_nonnegative,negative:()=>_negative,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,maxSize:()=>_maxSize,maxLength:()=>_maxLength,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,length:()=>_length,includes:()=>_includes,gte:()=>_gte,gt:()=>_gt,endsWith:()=>_endsWith});var init_checks2=__esm(()=>{init_core2()});var exports_iso={};__export(exports_iso,{time:()=>time2,duration:()=>duration2,datetime:()=>datetime2,date:()=>date2,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var ZodISODateTime,ZodISODate,ZodISOTime,ZodISODuration;var init_iso=__esm(()=>{init_core2();init_schemas2();ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)})});var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError(inst,mapper)},flatten:{value:(mapper)=>flattenError(inst,mapper)},addIssue:{value:(issue2)=>{inst.issues.push(issue2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError,ZodRealError;var init_errors2=__esm(()=>{init_core2();init_core2();init_util();ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,{Parent:Error})});var parse3,parseAsync2,safeParse2,safeParseAsync2,encode2,decode2,encodeAsync2,decodeAsync2,safeEncode2,safeDecode2,safeEncodeAsync2,safeDecodeAsync2;var init_parse2=__esm(()=>{init_core2();init_errors2();parse3=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError)});var exports_schemas2={};__export(exports_schemas2,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,url:()=>url,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,transform:()=>transform,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,set:()=>set,refine:()=>refine,record:()=>record,readonly:()=>readonly,promise:()=>promise,preprocess:()=>preprocess,prefault:()=>prefault,pipe:()=>pipe,partialRecord:()=>partialRecord,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,nonoptional:()=>nonoptional,never:()=>never,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,meta:()=>meta2,map:()=>map,mac:()=>mac2,looseRecord:()=>looseRecord,looseObject:()=>looseObject,literal:()=>literal,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,function:()=>_function,float64:()=>float64,float32:()=>float32,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,codec:()=>codec,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIntersection:()=>ZodIntersection,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny});function string2(params){return _string(ZodString,params)}function email2(params){return _email(ZodEmail,params)}function guid2(params){return _guid(ZodGUID,params)}function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:/^https?$/,hostname:exports_regexes.domain,...exports_util.normalizeParams(params)})}function emoji2(params){return _emoji2(ZodEmoji,params)}function nanoid2(params){return _nanoid(ZodNanoID,params)}function cuid3(params){return _cuid(ZodCUID,params)}function cuid22(params){return _cuid2(ZodCUID2,params)}function ulid2(params){return _ulid(ZodULID,params)}function xid2(params){return _xid(ZodXID,params)}function ksuid2(params){return _ksuid(ZodKSUID,params)}function ipv42(params){return _ipv4(ZodIPv4,params)}function mac2(params){return _mac(ZodMAC,params)}function ipv62(params){return _ipv6(ZodIPv6,params)}function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}function base642(params){return _base64(ZodBase64,params)}function base64url2(params){return _base64url(ZodBase64URL,params)}function e1642(params){return _e164(ZodE164,params)}function jwt(params){return _jwt(ZodJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",exports_regexes.hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",exports_regexes.hex,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodNumber,params)}function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}function boolean2(params){return _boolean(ZodBoolean,params)}function bigint2(params){return _bigint(ZodBigInt,params)}function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}function symbol(params){return _symbol(ZodSymbol,params)}function _undefined3(params){return _undefined2(ZodUndefined,params)}function _null3(params){return _null2(ZodNull,params)}function any(){return _any(ZodAny)}function unknown(){return _unknown(ZodUnknown)}function never(params){return _never(ZodNever,params)}function _void2(params){return _void(ZodVoid,params)}function date3(params){return _date(ZodDate,params)}function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}function object(shape,params){let def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...exports_util.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...exports_util.normalizeParams(params)})}function union(options,params){return new ZodUnion({type:"union",options,...exports_util.normalizeParams(params)})}function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...exports_util.normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest;return new ZodTuple({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util.normalizeParams(params)})}function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}function partialRecord(keyType,valueType,params){let k=clone(keyType);return k._zod.values=void 0,new ZodRecord({type:"record",keyType:k,valueType,...exports_util.normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...exports_util.normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...exports_util.normalizeParams(params)})}function set(valueType,params){return new ZodSet({type:"set",valueType,...exports_util.normalizeParams(params)})}function _enum2(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}function file(params){return _file(ZodFile,params)}function transform(fn2){return new ZodTransform({type:"transform",transform:fn2})}function optional(innerType){return new ZodOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util.shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...exports_util.normalizeParams(params)})}function success(innerType){return new ZodSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodNaN,params)}function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...exports_util.normalizeParams(params)})}function lazy(getter){return new ZodLazy({type:"lazy",getter})}function promise(innerType){return new ZodPromise({type:"promise",innerType})}function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}function check(fn2){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn2,ch}function custom(fn2,_params){return _custom(ZodCustom,fn2??(()=>!0),_params)}function refine(fn2,_params={}){return _refine(ZodCustom,fn2,_params)}function superRefine(fn2){return _superRefine(fn2)}function _instanceof(cls,params={}){let inst=new ZodCustom({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=(payload)=>{if(!(payload.value instanceof cls))payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}function json(params){let jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn2,schema){return pipe(transform(fn2),schema)}var ZodType,_ZodString,ZodString,ZodStringFormat,ZodEmail,ZodGUID,ZodUUID,ZodURL,ZodEmoji,ZodNanoID,ZodCUID,ZodCUID2,ZodULID,ZodXID,ZodKSUID,ZodIPv4,ZodMAC,ZodIPv6,ZodCIDRv4,ZodCIDRv6,ZodBase64,ZodBase64URL,ZodE164,ZodJWT,ZodCustomStringFormat,ZodNumber,ZodNumberFormat,ZodBoolean,ZodBigInt,ZodBigIntFormat,ZodSymbol,ZodUndefined,ZodNull,ZodAny,ZodUnknown,ZodNever,ZodVoid,ZodDate,ZodArray,ZodObject,ZodUnion,ZodXor,ZodDiscriminatedUnion,ZodIntersection,ZodTuple,ZodRecord,ZodMap,ZodSet,ZodEnum,ZodLiteral,ZodFile,ZodTransform,ZodOptional,ZodExactOptional,ZodNullable,ZodDefault,ZodPrefault,ZodNonOptional,ZodSuccess,ZodCatch,ZodNaN,ZodPipe,ZodCodec,ZodReadonly,ZodTemplateLiteral,ZodLazy,ZodPromise,ZodFunction,ZodCustom,describe2,meta2,stringbool=(...args2)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args2);var init_schemas2=__esm(()=>{init_core2();init_core2();init_json_schema_processors();init_to_json_schema();init_checks2();init_iso();init_parse2();ZodType=$constructor("ZodType",(inst,def)=>{return $ZodType.init(inst,def),Object.assign(inst["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,"input"),output:createStandardJSONSchemaMethod(inst,"output")}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks2)=>{return inst.clone(exports_util.mergeDefs(def,{checks:[...def.checks??[],...checks2.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},inst.with=inst.check,inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta2)=>{return reg.add(inst,meta2),inst},inst.parse=(data,params)=>parse3(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse2(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync2(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode2(inst,data,params),inst.decode=(data,params)=>decode2(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync2(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync2(inst,data,params),inst.safeEncode=(data,params)=>safeEncode2(inst,data,params),inst.safeDecode=(data,params)=>safeDecode2(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync2(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync2(inst,data,params),inst.refine=(check,params)=>inst.check(refine(check,params)),inst.superRefine=(refinement)=>inst.check(superRefine(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite(fn2)),inst.optional=()=>optional(inst),inst.exactOptional=()=>exactOptional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=(params)=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=(arg)=>union([inst,arg]),inst.and=(arg)=>intersection(inst,arg),inst.transform=(tx)=>pipe(inst,transform(tx)),inst.default=(def2)=>_default2(inst,def2),inst.prefault=(def2)=>prefault(inst,def2),inst.catch=(params)=>_catch2(inst,params),inst.pipe=(target)=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst.apply=(fn2)=>fn2(inst),inst}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex(...args2)),inst.includes=(...args2)=>inst.check(_includes(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith(...args2)),inst.min=(...args2)=>inst.check(_minLength(...args2)),inst.max=(...args2)=>inst.check(_maxLength(...args2)),inst.length=(...args2)=>inst.check(_length(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase(params)),inst.uppercase=(params)=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args2)=>inst.check(_normalize(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase()),inst.slugify=()=>inst.check(_slugify())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=(params)=>inst.check(_email(ZodEmail,params)),inst.url=(params)=>inst.check(_url(ZodURL,params)),inst.jwt=(params)=>inst.check(_jwt(ZodJWT,params)),inst.emoji=(params)=>inst.check(_emoji2(ZodEmoji,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.uuid=(params)=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=(params)=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=(params)=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=(params)=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=(params)=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=(params)=>inst.check(_guid(ZodGUID,params)),inst.cuid=(params)=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=(params)=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=(params)=>inst.check(_ulid(ZodULID,params)),inst.base64=(params)=>inst.check(_base64(ZodBase64,params)),inst.base64url=(params)=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=(params)=>inst.check(_xid(ZodXID,params)),inst.ksuid=(params)=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=(params)=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=(params)=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=(params)=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=(params)=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=(params)=>inst.check(_e164(ZodE164,params)),inst.datetime=(params)=>inst.check(datetime2(params)),inst.date=(params)=>inst.check(date2(params)),inst.time=(params)=>inst.check(time2(params)),inst.duration=(params)=>inst.check(duration2(params))});ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=(params)=>inst.check(int(params)),inst.safe=(params)=>inst.check(int(params)),inst.positive=(params)=>inst.check(_gt(0,params)),inst.nonnegative=(params)=>inst.check(_gte(0,params)),inst.negative=(params)=>inst.check(_lt(0,params)),inst.nonpositive=(params)=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>bigintProcessor(inst,ctx,json,params),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=(params)=>inst.check(_gt(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>symbolProcessor(inst,ctx,json,params)});ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>undefinedProcessor(inst,ctx,json,params)});ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>anyProcessor(inst,ctx,json,params)});ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>voidProcessor(inst,ctx,json,params)});ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>dateProcessor(inst,ctx,json,params),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),exports_util.defineLazy(inst,"shape",()=>{return def.shape}),inst.keyof=()=>_enum2(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util.merge(inst,other),inst.pick=(mask)=>exports_util.pick(inst,mask),inst.omit=(mask)=>exports_util.omit(inst,mask),inst.partial=(...args2)=>exports_util.partial(ZodOptional,inst,args2[0]),inst.required=(...args2)=>exports_util.required(ZodNonOptional,inst,args2[0])});ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});ZodTuple=$constructor("ZodTuple",(inst,def)=>{$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>tupleProcessor(inst,ctx,json,params),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap=$constructor("ZodMap",(inst,def)=>{$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>mapProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodSet=$constructor("ZodSet",(inst,def)=>{$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>setProcessor(inst,ctx,json,params),inst.min=(...args2)=>inst.check(_minSize(...args2)),inst.nonempty=(params)=>inst.check(_minSize(1,params)),inst.max=(...args2)=>inst.check(_maxSize(...args2)),inst.size=(...args2)=>inst.check(_size(...args2))});ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>fileProcessor(inst,ctx,json,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=(issue2)=>{if(typeof issue2==="string")payload.issues.push(exports_util.issue(issue2,payload.value,def));else{let _issue=issue2;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>successProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nanProcessor(inst,ctx,json,params)});ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>templateLiteralProcessor(inst,ctx,json,params)});ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>lazyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>promiseProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>functionProcessor(inst,ctx,json,params)});ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});describe2=describe,meta2=meta});function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodIssueCode,ZodFirstPartyTypeKind;var init_compat=__esm(()=>{init_core2();ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind2){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}))});function detectVersion(schema,defaultTarget){let $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if($schema==="http://json-schema.org/draft-07/schema#")return"draft-7";if($schema==="http://json-schema.org/draft-04/schema#")return"draft-4";return defaultTarget??"draft-2020-12"}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let path=ref.slice(1).split("/").filter(Boolean);if(path.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){let key=path[1];if(!key||!ctx.defs[key])throw Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw Error(`Reference not found: ${ref}`)}function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0)return z.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every((v)=>typeof v==="string"))return z.enum(enumValues);let literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2)return literalSchemas[0];return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map((t)=>{let typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0)return z.never();if(typeSchemas.length===1)return typeSchemas[0];return z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;if(format==="email")stringSchema=stringSchema.check(z.email());else if(format==="uri"||format==="uri-reference")stringSchema=stringSchema.check(z.url());else if(format==="uuid"||format==="guid")stringSchema=stringSchema.check(z.uuid());else if(format==="date-time")stringSchema=stringSchema.check(z.iso.datetime());else if(format==="date")stringSchema=stringSchema.check(z.iso.date());else if(format==="time")stringSchema=stringSchema.check(z.iso.time());else if(format==="duration")stringSchema=stringSchema.check(z.iso.duration());else if(format==="ipv4")stringSchema=stringSchema.check(z.ipv4());else if(format==="ipv6")stringSchema=stringSchema.check(z.ipv6());else if(format==="mac")stringSchema=stringSchema.check(z.mac());else if(format==="cidr")stringSchema=stringSchema.check(z.cidrv4());else if(format==="cidr-v6")stringSchema=stringSchema.check(z.cidrv6());else if(format==="base64")stringSchema=stringSchema.check(z.base64());else if(format==="base64url")stringSchema=stringSchema.check(z.base64url());else if(format==="e164")stringSchema=stringSchema.check(z.e164());else if(format==="jwt")stringSchema=stringSchema.check(z.jwt());else if(format==="emoji")stringSchema=stringSchema.check(z.emoji());else if(format==="nanoid")stringSchema=stringSchema.check(z.nanoid());else if(format==="cuid")stringSchema=stringSchema.check(z.cuid());else if(format==="cuid2")stringSchema=stringSchema.check(z.cuid2());else if(format==="ulid")stringSchema=stringSchema.check(z.ulid());else if(format==="xid")stringSchema=stringSchema.check(z.xid());else if(format==="ksuid")stringSchema=stringSchema.check(z.ksuid())}if(typeof schema.minLength==="number")stringSchema=stringSchema.min(schema.minLength);if(typeof schema.maxLength==="number")stringSchema=stringSchema.max(schema.maxLength);if(schema.pattern)stringSchema=stringSchema.regex(new RegExp(schema.pattern));zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number")numberSchema=numberSchema.min(schema.minimum);if(typeof schema.maximum==="number")numberSchema=numberSchema.max(schema.maximum);if(typeof schema.exclusiveMinimum==="number")numberSchema=numberSchema.gt(schema.exclusiveMinimum);else if(schema.exclusiveMinimum===!0&&typeof schema.minimum==="number")numberSchema=numberSchema.gt(schema.minimum);if(typeof schema.exclusiveMaximum==="number")numberSchema=numberSchema.lt(schema.exclusiveMaximum);else if(schema.exclusiveMaximum===!0&&typeof schema.maximum==="number")numberSchema=numberSchema.lt(schema.maximum);if(typeof schema.multipleOf==="number")numberSchema=numberSchema.multipleOf(schema.multipleOf);zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]);for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);shape[key]=requiredSet.has(key)?propZodSchema:propZodSchema.optional()}if(schema.propertyNames){let keySchema=convertSchema(schema.propertyNames,ctx),valueSchema=schema.additionalProperties&&typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):z.any();if(Object.keys(shape).length===0){zodSchema=z.record(keySchema,valueSchema);break}let objectSchema2=z.object(shape).passthrough(),recordSchema=z.looseRecord(keySchema,valueSchema);zodSchema=z.intersection(objectSchema2,recordSchema);break}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0)schemasToIntersect.push(z.object(shape).passthrough());if(schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++)result=z.intersection(result,schemasToIntersect[i]);zodSchema=result}break}let objectSchema=z.object(shape);if(schema.additionalProperties===!1)zodSchema=objectSchema.strict();else if(typeof schema.additionalProperties==="object")zodSchema=objectSchema.catchall(convertSchema(schema.additionalProperties,ctx));else zodSchema=objectSchema.passthrough();break}case"array":{let{prefixItems,items}=schema;if(prefixItems&&Array.isArray(prefixItems)){let tupleItems=prefixItems.map((item)=>convertSchema(item,ctx)),rest=items&&typeof items==="object"&&!Array.isArray(items)?convertSchema(items,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(Array.isArray(items)){let tupleItems=items.map((item)=>convertSchema(item,ctx)),rest=schema.additionalItems&&typeof schema.additionalItems==="object"?convertSchema(schema.additionalItems,ctx):void 0;if(rest)zodSchema=z.tuple(tupleItems).rest(rest);else zodSchema=z.tuple(tupleItems);if(typeof schema.minItems==="number")zodSchema=zodSchema.check(z.minLength(schema.minItems));if(typeof schema.maxItems==="number")zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);if(typeof schema.minItems==="number")arraySchema=arraySchema.min(schema.minItems);if(typeof schema.maxItems==="number")arraySchema=arraySchema.max(schema.maxItems);zodSchema=arraySchema}else zodSchema=z.array(z.any());break}default:throw Error(`Unsupported type: ${type}`)}if(schema.description)zodSchema=zodSchema.describe(schema.description);if(schema.default!==void 0)zodSchema=zodSchema.default(schema.default);return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map((s)=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map((s)=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++)result=z.intersection(result,convertSchema(schema.allOf[i],ctx));baseSchema=result}if(schema.nullable===!0&&ctx.version==="openapi-3.0")baseSchema=z.nullable(baseSchema);if(schema.readOnly===!0)baseSchema=z.readonly(baseSchema);let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)if(key in schema)extraMeta[key]=schema[key];let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)if(key in schema)extraMeta[key]=schema[key];for(let key of Object.keys(schema))if(!RECOGNIZED_KEYS.has(key))extraMeta[key]=schema[key];if(Object.keys(extraMeta).length>0)ctx.registry.add(baseSchema,extraMeta);return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean")return schema?z.any():z.never();let version2=detectVersion(schema,params?.defaultTarget),defs=schema.$defs||schema.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:schema,registry:params?.registry??globalRegistry};return convertSchema(schema,ctx)}var z,RECOGNIZED_KEYS;var init_from_json_schema=__esm(()=>{init_registries();init_checks2();init_iso();init_schemas2();z={...exports_schemas2,...exports_checks2,iso:exports_iso},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var exports_coerce={};__export(exports_coerce,{string:()=>string3,number:()=>number3,date:()=>date4,boolean:()=>boolean3,bigint:()=>bigint3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var init_coerce=__esm(()=>{init_core2();init_schemas2()});var exports_external={};__export(exports_external,{xor:()=>xor,xid:()=>xid2,void:()=>_void2,uuidv7:()=>uuidv7,uuidv6:()=>uuidv6,uuidv4:()=>uuidv4,uuid:()=>uuid2,util:()=>exports_util,url:()=>url,uppercase:()=>_uppercase,unknown:()=>unknown,union:()=>union,undefined:()=>_undefined3,ulid:()=>ulid2,uint64:()=>uint64,uint32:()=>uint32,tuple:()=>tuple,trim:()=>_trim,treeifyError:()=>treeifyError,transform:()=>transform,toUpperCase:()=>_toUpperCase,toLowerCase:()=>_toLowerCase,toJSONSchema:()=>toJSONSchema,templateLiteral:()=>templateLiteral,symbol:()=>symbol,superRefine:()=>superRefine,success:()=>success,stringbool:()=>stringbool,stringFormat:()=>stringFormat,string:()=>string2,strictObject:()=>strictObject,startsWith:()=>_startsWith,slugify:()=>_slugify,size:()=>_size,setErrorMap:()=>setErrorMap,set:()=>set,safeParseAsync:()=>safeParseAsync2,safeParse:()=>safeParse2,safeEncodeAsync:()=>safeEncodeAsync2,safeEncode:()=>safeEncode2,safeDecodeAsync:()=>safeDecodeAsync2,safeDecode:()=>safeDecode2,registry:()=>registry,regexes:()=>exports_regexes,regex:()=>_regex,refine:()=>refine,record:()=>record,readonly:()=>readonly,property:()=>_property,promise:()=>promise,prettifyError:()=>prettifyError,preprocess:()=>preprocess,prefault:()=>prefault,positive:()=>_positive,pipe:()=>pipe,partialRecord:()=>partialRecord,parseAsync:()=>parseAsync2,parse:()=>parse3,overwrite:()=>_overwrite,optional:()=>optional,object:()=>object,number:()=>number2,nullish:()=>nullish2,nullable:()=>nullable,null:()=>_null3,normalize:()=>_normalize,nonpositive:()=>_nonpositive,nonoptional:()=>nonoptional,nonnegative:()=>_nonnegative,never:()=>never,negative:()=>_negative,nativeEnum:()=>nativeEnum,nanoid:()=>nanoid2,nan:()=>nan,multipleOf:()=>_multipleOf,minSize:()=>_minSize,minLength:()=>_minLength,mime:()=>_mime,meta:()=>meta2,maxSize:()=>_maxSize,maxLength:()=>_maxLength,map:()=>map,mac:()=>mac2,lte:()=>_lte,lt:()=>_lt,lowercase:()=>_lowercase,looseRecord:()=>looseRecord,looseObject:()=>looseObject,locales:()=>exports_locales,literal:()=>literal,length:()=>_length,lazy:()=>lazy,ksuid:()=>ksuid2,keyof:()=>keyof,jwt:()=>jwt,json:()=>json,iso:()=>exports_iso,ipv6:()=>ipv62,ipv4:()=>ipv42,intersection:()=>intersection,int64:()=>int64,int32:()=>int32,int:()=>int,instanceof:()=>_instanceof,includes:()=>_includes,httpUrl:()=>httpUrl,hostname:()=>hostname2,hex:()=>hex2,hash:()=>hash,guid:()=>guid2,gte:()=>_gte,gt:()=>_gt,globalRegistry:()=>globalRegistry,getErrorMap:()=>getErrorMap,function:()=>_function,fromJSONSchema:()=>fromJSONSchema,formatError:()=>formatError,float64:()=>float64,float32:()=>float32,flattenError:()=>flattenError,file:()=>file,exactOptional:()=>exactOptional,enum:()=>_enum2,endsWith:()=>_endsWith,encodeAsync:()=>encodeAsync2,encode:()=>encode2,emoji:()=>emoji2,email:()=>email2,e164:()=>e1642,discriminatedUnion:()=>discriminatedUnion,describe:()=>describe2,decodeAsync:()=>decodeAsync2,decode:()=>decode2,date:()=>date3,custom:()=>custom,cuid2:()=>cuid22,cuid:()=>cuid3,core:()=>exports_core2,config:()=>config,coerce:()=>exports_coerce,codec:()=>codec,clone:()=>clone,cidrv6:()=>cidrv62,cidrv4:()=>cidrv42,check:()=>check,catch:()=>_catch2,boolean:()=>boolean2,bigint:()=>bigint2,base64url:()=>base64url2,base64:()=>base642,array:()=>array,any:()=>any,_function:()=>_function,_default:()=>_default2,_ZodString:()=>_ZodString,ZodXor:()=>ZodXor,ZodXID:()=>ZodXID,ZodVoid:()=>ZodVoid,ZodUnknown:()=>ZodUnknown,ZodUnion:()=>ZodUnion,ZodUndefined:()=>ZodUndefined,ZodUUID:()=>ZodUUID,ZodURL:()=>ZodURL,ZodULID:()=>ZodULID,ZodType:()=>ZodType,ZodTuple:()=>ZodTuple,ZodTransform:()=>ZodTransform,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodSymbol:()=>ZodSymbol,ZodSuccess:()=>ZodSuccess,ZodStringFormat:()=>ZodStringFormat,ZodString:()=>ZodString,ZodSet:()=>ZodSet,ZodRecord:()=>ZodRecord,ZodRealError:()=>ZodRealError,ZodReadonly:()=>ZodReadonly,ZodPromise:()=>ZodPromise,ZodPrefault:()=>ZodPrefault,ZodPipe:()=>ZodPipe,ZodOptional:()=>ZodOptional,ZodObject:()=>ZodObject,ZodNumberFormat:()=>ZodNumberFormat,ZodNumber:()=>ZodNumber,ZodNullable:()=>ZodNullable,ZodNull:()=>ZodNull,ZodNonOptional:()=>ZodNonOptional,ZodNever:()=>ZodNever,ZodNanoID:()=>ZodNanoID,ZodNaN:()=>ZodNaN,ZodMap:()=>ZodMap,ZodMAC:()=>ZodMAC,ZodLiteral:()=>ZodLiteral,ZodLazy:()=>ZodLazy,ZodKSUID:()=>ZodKSUID,ZodJWT:()=>ZodJWT,ZodIssueCode:()=>ZodIssueCode,ZodIntersection:()=>ZodIntersection,ZodISOTime:()=>ZodISOTime,ZodISODuration:()=>ZodISODuration,ZodISODateTime:()=>ZodISODateTime,ZodISODate:()=>ZodISODate,ZodIPv6:()=>ZodIPv6,ZodIPv4:()=>ZodIPv4,ZodGUID:()=>ZodGUID,ZodFunction:()=>ZodFunction,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFile:()=>ZodFile,ZodExactOptional:()=>ZodExactOptional,ZodError:()=>ZodError,ZodEnum:()=>ZodEnum,ZodEmoji:()=>ZodEmoji,ZodEmail:()=>ZodEmail,ZodE164:()=>ZodE164,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodDefault:()=>ZodDefault,ZodDate:()=>ZodDate,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodCustom:()=>ZodCustom,ZodCodec:()=>ZodCodec,ZodCatch:()=>ZodCatch,ZodCUID2:()=>ZodCUID2,ZodCUID:()=>ZodCUID,ZodCIDRv6:()=>ZodCIDRv6,ZodCIDRv4:()=>ZodCIDRv4,ZodBoolean:()=>ZodBoolean,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBigInt:()=>ZodBigInt,ZodBase64URL:()=>ZodBase64URL,ZodBase64:()=>ZodBase64,ZodArray:()=>ZodArray,ZodAny:()=>ZodAny,TimePrecision:()=>TimePrecision,NEVER:()=>NEVER,$output:()=>$output,$input:()=>$input,$brand:()=>$brand});var init_external=__esm(()=>{init_core2();init_core2();init_en();init_core2();init_json_schema_processors();init_from_json_schema();init_locales();init_iso();init_iso();init_coerce();init_schemas2();init_checks2();init_errors2();init_parse2();init_compat();config(en_default())});var init_zod=__esm(()=>{init_external();init_external()});var EVIDENCE_MAX_JSON_BYTES=512000,EVIDENCE_MAX_PATCH_BYTES=5242880,EVIDENCE_MAX_TASK_BYTES=20971520,EvidenceTypeSchema,EvidenceVerdictSchema,BaseEvidenceSchema,ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastFindingSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,GateEvidenceBaseSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema,EvidenceSchema,EvidenceBundleSchema;var init_evidence_schema=__esm(()=>{init_zod();EvidenceTypeSchema=exports_external.enum(["review","test","diff","approval","note","retrospective","syntax","placeholder","sast","sbom","build","quality_budget","secretscan","mutation-gate","drift-verification","hallucination-verification"]),EvidenceVerdictSchema=exports_external.enum(["pass","fail","warn","skip","approved","rejected","info"]),BaseEvidenceSchema=exports_external.object({task_id:exports_external.string().min(1),type:EvidenceTypeSchema,timestamp:exports_external.string().datetime(),agent:exports_external.string().min(1),verdict:EvidenceVerdictSchema,summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),ReviewEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("review"),risk:exports_external.enum(["low","medium","high","critical"]),issues:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning","info"]),message:exports_external.string().min(1),file:exports_external.string().optional(),line:exports_external.number().int().optional()})).default([])}),TestEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("test"),tests_passed:exports_external.number().int().min(0),tests_failed:exports_external.number().int().min(0),test_file:exports_external.string().optional(),failures:exports_external.array(exports_external.object({name:exports_external.string().min(1),message:exports_external.string().min(1)})).default([])}),DiffEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("diff"),files_changed:exports_external.array(exports_external.string()).default([]),additions:exports_external.number().int().min(0).default(0),deletions:exports_external.number().int().min(0).default(0),patch_path:exports_external.string().optional()}),ApprovalEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("approval")}),NoteEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("note")}),RetrospectiveEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("retrospective"),phase_number:exports_external.number().int().min(1).max(99),total_tool_calls:exports_external.number().int().min(0).max(9999),coder_revisions:exports_external.number().int().min(0).max(999),reviewer_rejections:exports_external.number().int().min(0).max(999),loop_detections:exports_external.number().int().min(0).max(9999).optional(),circuit_breaker_trips:exports_external.number().int().min(0).max(9999).optional(),test_failures:exports_external.number().int().min(0).max(9999),security_findings:exports_external.number().int().min(0).max(999),integration_issues:exports_external.number().int().min(0).max(999),task_count:exports_external.number().int().min(1).max(9999),task_complexity:exports_external.enum(["trivial","simple","moderate","complex"]),top_rejection_reasons:exports_external.array(exports_external.string()).default([]),lessons_learned:exports_external.array(exports_external.string()).max(5).default([]),user_directives:exports_external.array(exports_external.object({directive:exports_external.string().min(1),category:exports_external.enum(["tooling","code_style","architecture","process","other"]),scope:exports_external.enum(["session","project","global"])})).default([]),approaches_tried:exports_external.array(exports_external.object({approach:exports_external.string().min(1),result:exports_external.enum(["success","failure","partial"]),abandoned_reason:exports_external.string().optional()})).max(10).default([]),error_taxonomy:exports_external.array(exports_external.enum(["planning_error","interface_mismatch","logic_error","scope_creep","gate_evasion"])).default([])}),SyntaxEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("syntax"),files_checked:exports_external.number().int(),files_failed:exports_external.number().int(),skipped_count:exports_external.number().int().default(0),files:exports_external.array(exports_external.object({path:exports_external.string(),language:exports_external.string(),ok:exports_external.boolean(),errors:exports_external.array(exports_external.object({line:exports_external.number().int(),column:exports_external.number().int(),message:exports_external.string()})).default([]),skipped_reason:exports_external.string().optional()})).default([])}),PlaceholderEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("placeholder"),findings:exports_external.array(exports_external.object({path:exports_external.string(),line:exports_external.number().int(),kind:exports_external.enum(["comment","string","function_body","other"]),excerpt:exports_external.string(),rule_id:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),files_with_findings:exports_external.number().int(),findings_count:exports_external.number().int()}),SastFindingSchema=exports_external.object({rule_id:exports_external.string(),severity:exports_external.enum(["critical","high","medium","low"]),message:exports_external.string(),location:exports_external.object({file:exports_external.string(),line:exports_external.number().int(),column:exports_external.number().int().optional()}),remediation:exports_external.string().optional()}),SastEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sast"),findings:exports_external.array(SastFindingSchema).default([]),engine:exports_external.enum(["tier_a","tier_a+tier_b"]),files_scanned:exports_external.number().int(),findings_count:exports_external.number().int(),findings_by_severity:exports_external.object({critical:exports_external.number().int(),high:exports_external.number().int(),medium:exports_external.number().int(),low:exports_external.number().int()}),new_findings:exports_external.array(SastFindingSchema).optional(),pre_existing_findings:exports_external.array(SastFindingSchema).optional(),baseline_used:exports_external.boolean().optional()}),SbomEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("sbom"),components:exports_external.array(exports_external.object({name:exports_external.string(),version:exports_external.string(),type:exports_external.enum(["library","framework","application"]),purl:exports_external.string().optional(),license:exports_external.string().optional()})).default([]),metadata:exports_external.object({timestamp:exports_external.string().datetime(),tool:exports_external.string(),tool_version:exports_external.string()}),files:exports_external.array(exports_external.string()),components_count:exports_external.number().int(),output_path:exports_external.string()}),BuildEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("build"),runs:exports_external.array(exports_external.object({kind:exports_external.enum(["build","typecheck","test"]),command:exports_external.string(),cwd:exports_external.string(),exit_code:exports_external.number().int(),duration_ms:exports_external.number().int(),stdout_tail:exports_external.string(),stderr_tail:exports_external.string()})).default([]),files_scanned:exports_external.number().int(),runs_count:exports_external.number().int(),failed_count:exports_external.number().int(),skipped_reason:exports_external.string().optional()}),QualityBudgetEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("quality_budget"),metrics:exports_external.object({complexity_delta:exports_external.number(),public_api_delta:exports_external.number(),duplication_ratio:exports_external.number(),test_to_code_ratio:exports_external.number()}),thresholds:exports_external.object({max_complexity_delta:exports_external.number(),max_public_api_delta:exports_external.number(),max_duplication_ratio:exports_external.number(),min_test_to_code_ratio:exports_external.number()}),violations:exports_external.array(exports_external.object({type:exports_external.enum(["complexity","api","duplication","test_ratio"]),message:exports_external.string(),severity:exports_external.enum(["error","warning"]),files:exports_external.array(exports_external.string())})).default([]),files_analyzed:exports_external.array(exports_external.string())}),SecretscanEvidenceSchema=BaseEvidenceSchema.extend({type:exports_external.literal("secretscan"),findings_count:exports_external.number().int().min(0).default(0),scan_directory:exports_external.string().optional(),files_scanned:exports_external.number().int().min(0).default(0),skipped_files:exports_external.number().int().min(0).default(0)}),GateEvidenceBaseSchema=exports_external.object({task_id:exports_external.string().optional(),agent:exports_external.string().optional(),timestamp:exports_external.string().datetime(),summary:exports_external.string().min(1),metadata:exports_external.record(exports_external.string(),exports_external.unknown()).optional()}),MutationGateEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("mutation-gate"),verdict:exports_external.enum(["pass","warn","fail","skip"]),killRate:exports_external.number().min(0).max(1).optional(),adjustedKillRate:exports_external.number().min(0).max(1).optional(),survivedMutants:exports_external.string().optional()}),DriftVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("drift-verification"),verdict:exports_external.enum(["approved","rejected"]),requirementCoverage:exports_external.string().optional()}),HallucinationVerificationEvidenceSchema=GateEvidenceBaseSchema.extend({type:exports_external.literal("hallucination-verification"),verdict:exports_external.enum(["approved","rejected"]),findings:exports_external.string().optional()}),EvidenceSchema=exports_external.discriminatedUnion("type",[ReviewEvidenceSchema,TestEvidenceSchema,DiffEvidenceSchema,ApprovalEvidenceSchema,NoteEvidenceSchema,RetrospectiveEvidenceSchema,SyntaxEvidenceSchema,PlaceholderEvidenceSchema,SastEvidenceSchema,SbomEvidenceSchema,BuildEvidenceSchema,QualityBudgetEvidenceSchema,SecretscanEvidenceSchema,MutationGateEvidenceSchema,DriftVerificationEvidenceSchema,HallucinationVerificationEvidenceSchema]),EvidenceBundleSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),task_id:exports_external.string().min(1),entries:exports_external.array(EvidenceSchema).default([]),created_at:exports_external.string().datetime(),updated_at:exports_external.string().datetime()})});function isDebug(){return process.env.OPENCODE_SWARM_DEBUG==="1"}function log(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.log(`[opencode-swarm ${timestamp}] ${message}`,data);else console.log(`[opencode-swarm ${timestamp}] ${message}`)}function warn(message,data){if(!isDebug())return;let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] WARN: ${message}`)}function criticalWarn(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`,data);else console.warn(`[opencode-swarm ${timestamp}] CRITICAL-WARN: ${message}`)}function error48(message,data){let timestamp=new Date().toISOString();if(data!==void 0)console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`,data);else console.error(`[opencode-swarm ${timestamp}] ERROR: ${message}`)}var init_logger=()=>{};function sanitizeBufferedLine(s){return s.replace(/\s+/g," ").replace(CONTROL_CHARS_RE,"").replace(/\s+/g," ").trim()}function addDeferredWarning(warning){let sanitized=sanitizeBufferedLine(warning);if(deferredWarnings.length<MAX_DEFERRED_WARNINGS-1){deferredWarnings.push(sanitized);return}if(!deferredWarningsTruncated)deferredWarnings.push(`[opencode-swarm] ${MAX_DEFERRED_WARNINGS-1} deferred warnings buffered; additional advisories were dropped (cap reached). Run with OPENCODE_SWARM_DEBUG=1 to see all advisories in the debug log.`),deferredWarningsTruncated=!0}function renderAdvisoryDetail(data){if(data===void 0||data===null)return"";let raw;if(typeof data==="string")raw=data;else if(data instanceof Error)raw=data.message;else if(Array.isArray(data)&&data.every((d)=>typeof d==="string"))raw=data.join("; ");else try{raw=JSON.stringify(data)??String(data)}catch{raw=String(data)}let collapsed=sanitizeBufferedLine(raw);if(collapsed==="")return"";return collapsed.length>MAX_ADVISORY_DETAIL_CHARS?`${collapsed.slice(0,MAX_ADVISORY_DETAIL_CHARS-1)}…`:collapsed}function advisoryWarn(message,data){let detail=renderAdvisoryDetail(data);addDeferredWarning(detail?`${message} ${detail}`:message),log(message,data)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0,deferredWarningsTruncated=!1}var deferredWarnings,MAX_DEFERRED_WARNINGS=50,deferredWarningsTruncated=!1,CONTROL_CHARS_RE,MAX_ADVISORY_DETAIL_CHARS=600;var init_warning_buffer=__esm(()=>{init_logger();deferredWarnings=[],CONTROL_CHARS_RE=/[\x00-\x1F\x7F-\x9F]/g});function isActiveStatus(status){return!INACTIVE_STATUSES.has(status??"")}var KNOWLEDGE_SCHEMA_VERSION=3,INACTIVE_STATUSES,OUTCOME_BLOCK_THRESHOLD=-0.3;var init_knowledge_types=__esm(()=>{INACTIVE_STATUSES=new Set(["archived","quarantined","quarantined_unactionable"])});var exports_schema={};__export(exports_schema,{stripKnownSwarmPrefix:()=>stripKnownSwarmPrefix,resolveGuardrailsConfig:()=>resolveGuardrailsConfig,resolveGeneratedAgentRole:()=>resolveGeneratedAgentRole,resolveExternalSkillsConfig:()=>resolveExternalSkillsConfig,isKnownCanonicalRole:()=>isKnownCanonicalRole,getCanonicalAgentRole:()=>getCanonicalAgentRole,_internals:()=>_internals,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,WatchdogConfigSchema:()=>WatchdogConfigSchema,UIReviewConfigSchema:()=>UIReviewConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,ToolFilterConfigSchema:()=>ToolFilterConfigSchema,TokenRatiosSchema:()=>TokenRatiosSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SummaryConfigSchema:()=>SummaryConfigSchema,StandardTurboConfigSchema:()=>StandardTurboConfigSchema,SpecWriterConfigSchema:()=>SpecWriterConfigSchema,SlopDetectorConfigSchema:()=>SlopDetectorConfigSchema,SkillsConfigSchema:()=>SkillsConfigSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,SkillImproverConfigSchema:()=>SkillImproverConfigSchema,SelfReviewConfigSchema:()=>SelfReviewConfigSchema,SecretscanConfigSchema:()=>SecretscanConfigSchema,ScoringWeightsSchema:()=>ScoringWeightsSchema,ScoringConfigSchema:()=>ScoringConfigSchema,ReviewPassesConfigSchema:()=>ReviewPassesConfigSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QualityBudgetConfigSchema:()=>QualityBudgetConfigSchema,PrmConfigSchema:()=>PrmConfigSchema,PricingConfigSchema:()=>PricingConfigSchema,PrMonitorConfigSchema:()=>PrMonitorConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanCursorConfigSchema:()=>PlanCursorConfigSchema,PlaceholderScanConfigSchema:()=>PlaceholderScanConfigSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,ParallelizationConfigSchema:()=>ParallelizationConfigSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LintConfigSchema:()=>LintConfigSchema,LeanTurboStrategyConfigSchema:()=>LeanTurboStrategyConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,KnowledgeConfigSchema:()=>KnowledgeConfigSchema,KnowledgeApplicationConfigSchema:()=>KnowledgeApplicationConfigSchema,IntegrationAnalysisConfigSchema:()=>IntegrationAnalysisConfigSchema,IncrementalVerifyConfigSchema:()=>IncrementalVerifyConfigSchema,HooksConfigSchema:()=>HooksConfigSchema,GuardrailsProfileSchema:()=>GuardrailsProfileSchema,GuardrailsConfigSchema:()=>GuardrailsConfigSchema,GeneralCouncilConfigSchema:()=>GeneralCouncilConfigSchema,GateFeatureSchema:()=>GateFeatureSchema,GateConfigSchema:()=>GateConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS:()=>GATE_CONFIG_KNOWN_SECTION_KEYS,FALLBACK_MODELS_MAX:()=>FALLBACK_MODELS_MAX,ExternalSkillsConfigSchema:()=>ExternalSkillsConfigSchema,ExternalSkillCandidateSourceTypeSchema:()=>ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateSchema:()=>ExternalSkillCandidateSchema,ExternalSkillCandidateEvaluationVerdictSchema:()=>ExternalSkillCandidateEvaluationVerdictSchema,EvidenceConfigSchema:()=>EvidenceConfigSchema,EpicConfigSchema:()=>EpicConfigSchema,DocsConfigSchema:()=>DocsConfigSchema,DiscoverySourceSchema:()=>DiscoverySourceSchema,DesignDocsConfigSchema:()=>DesignDocsConfigSchema,DecisionDecaySchema:()=>DecisionDecaySchema,DEFAULT_SKILLS_CONFIG:()=>DEFAULT_SKILLS_CONFIG,DEFAULT_EXTERNAL_SKILLS_CONFIG:()=>DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_ARCHITECT_PROFILE:()=>DEFAULT_ARCHITECT_PROFILE,DEFAULT_AGENT_PROFILES:()=>DEFAULT_AGENT_PROFILES,CuratorConfigSchema:()=>CuratorConfigSchema,CouncilConfigSchema:()=>CouncilConfigSchema,ContextMapConfigSchema:()=>ContextMapConfigSchema,ContextBudgetConfigSchema:()=>ContextBudgetConfigSchema,CompactionConfigSchema:()=>CompactionConfigSchema,CompactionAdvisoryConfigSchema:()=>CompactionAdvisoryConfigSchema,CheckpointConfigSchema:()=>CheckpointConfigSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,AutoReviewConfigSchema:()=>AutoReviewConfigSchema,AuthorityConfigSchema:()=>AuthorityConfigSchema,ArchitecturalSupervisionConfigSchema:()=>ArchitecturalSupervisionConfigSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentThinkingConfigSchema:()=>AgentThinkingConfigSchema,AgentReasoningConfigSchema:()=>AgentReasoningConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,AgentAuthorityRuleSchema:()=>AgentAuthorityRuleSchema,AdversarialTestingConfigSchema:()=>AdversarialTestingConfigSchema,AdversarialDetectionConfigSchema:()=>AdversarialDetectionConfigSchema});function isKnownCanonicalRole(role){if(!role)return!1;return CANONICAL_ROLES_SET.has(role)}function getCanonicalAgentRole(agentName,generatedAgentNames){if(!agentName)return agentName;let normalized=agentName.toLowerCase();if(CANONICAL_ROLES_SET.has(normalized))return normalized;if(generatedAgentNames){let registry2=new Set;for(let n of generatedAgentNames)registry2.add(n.toLowerCase());if(!registry2.has(normalized))return agentName}for(let role of CANONICAL_ROLES_LONGEST_FIRST)for(let sep of SEPARATORS){let suffix=sep+role;if(normalized.length>suffix.length&&normalized.endsWith(suffix))return role}return agentName}function resolveGeneratedAgentRole(agentName,generatedAgentNames){return _internals.getCanonicalAgentRole(agentName,generatedAgentNames)}function stripKnownSwarmPrefix(agentName){return getCanonicalAgentRole(agentName)}function resolveGuardrailsConfig(config2,agentName){if(!agentName)return config2;let canonicalName=_internals.stripKnownSwarmPrefix(agentName),hasBuiltInProfile=canonicalName in DEFAULT_AGENT_PROFILES,userProfile=config2.profiles?.[agentName]??config2.profiles?.[canonicalName];if(!hasBuiltInProfile){if(userProfile)return{...config2,...userProfile};return config2}let builtInProfile=DEFAULT_AGENT_PROFILES[canonicalName];return{...config2,...builtInProfile,...userProfile||{}}}function resolveExternalSkillsConfig(input){if(input===void 0||input===null||typeof input!=="object"||Array.isArray(input))return{...DEFAULT_EXTERNAL_SKILLS_CONFIG};let config2=input;return{curation_enabled:config2.curation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.curation_enabled,max_candidates:config2.max_candidates??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates,max_bytes_per_candidate:config2.max_bytes_per_candidate??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_bytes_per_candidate,eviction_policy:config2.eviction_policy??DEFAULT_EXTERNAL_SKILLS_CONFIG.eviction_policy,ttl_days:config2.ttl_days??DEFAULT_EXTERNAL_SKILLS_CONFIG.ttl_days,evaluation_enabled:config2.evaluation_enabled??DEFAULT_EXTERNAL_SKILLS_CONFIG.evaluation_enabled,sources:Array.isArray(config2.sources)?config2.sources:[],max_candidates_per_discovery:config2.max_candidates_per_discovery??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_candidates_per_discovery,max_concurrent_fetches:config2.max_concurrent_fetches??DEFAULT_EXTERNAL_SKILLS_CONFIG.max_concurrent_fetches,fetch_timeout_ms:config2.fetch_timeout_ms??DEFAULT_EXTERNAL_SKILLS_CONFIG.fetch_timeout_ms}}var _internals,SEPARATORS,CANONICAL_ROLES_LONGEST_FIRST,CANONICAL_ROLES_SET,AgentReasoningConfigSchema,AgentThinkingConfigSchema,FALLBACK_MODELS_MAX=3,AgentOverrideConfigSchema,SwarmConfigSchema,ModelPricingConfigSchema,PricingConfigSchema,HooksConfigSchema,ScoringWeightsSchema,DecisionDecaySchema,TokenRatiosSchema,ScoringConfigSchema,ContextBudgetConfigSchema,EvidenceConfigSchema,GateFeatureSchema,PlaceholderScanConfigSchema,QualityBudgetConfigSchema,GATE_CONFIG_KNOWN_SECTION_KEYS,GateConfigSchema,PipelineConfigSchema,PhaseCompleteConfigSchema,SummaryConfigSchema,ReviewPassesConfigSchema,AutoReviewConfigSchema,AdversarialDetectionConfigSchema,AdversarialTestingConfigSchemaBase,AdversarialTestingConfigSchema,IntegrationAnalysisConfigSchema,DocsConfigSchema,DesignDocsConfigSchema,UIReviewConfigSchema,CompactionAdvisoryConfigSchema,LintConfigSchema,SecretscanConfigSchema,GuardrailsProfileSchema,DEFAULT_AGENT_PROFILES,DEFAULT_ARCHITECT_PROFILE,GuardrailsConfigSchema,WatchdogConfigSchema,SelfReviewConfigSchema,ToolFilterConfigSchema,PlanCursorConfigSchema,ContextMapConfigSchema,RepoGraphConfigSchema,CheckpointConfigSchema,ApplyPatchConfigSchema,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,SkillPropagationAudienceSchema,SkillPropagationConfigSchema,SkillImproverConfigSchema,SkillsConfigSchema,SpecWriterConfigSchema,SlopDetectorConfigSchema,IncrementalVerifyConfigSchema,CompactionConfigSchema,PrmConfigSchema,AgentAuthorityRuleSchema,AuthorityConfigSchema,GeneralCouncilMemberConfigSchema,GeneralCouncilConfigSchema,CouncilConfigSchema,PrMonitorConfigSchema,ParallelizationConfigSchema,WorktreeIsolationConfigSchema,LeanTurboConfigSchema,EpicConfigSchema,StandardTurboConfigSchema,LeanTurboStrategyConfigSchema,TurboConfigSchema,ExternalSkillCandidateSourceTypeSchema,ExternalSkillCandidateEvaluationVerdictSchema,DiscoverySourceSchema,ExternalSkillCandidateSchema,ExternalSkillsConfigSchema,DEFAULT_EXTERNAL_SKILLS_CONFIG,DEFAULT_SKILLS_CONFIG,PluginConfigSchema;var init_schema=__esm(()=>{init_zod();init_knowledge_types();init_constants();_internals={stripKnownSwarmPrefix,getCanonicalAgentRole,resolveGuardrailsConfig},SEPARATORS=["_","-"," "],CANONICAL_ROLES_LONGEST_FIRST=[...ALL_AGENT_NAMES].sort((a,b)=>b.length-a.length),CANONICAL_ROLES_SET=new Set(ALL_AGENT_NAMES);AgentReasoningConfigSchema=exports_external.object({effort:exports_external.enum(["low","medium","high","max"]).optional()}),AgentThinkingConfigSchema=exports_external.object({type:exports_external.enum(["enabled","disabled"]).optional(),budget_tokens:exports_external.number().int().positive().optional()}),AgentOverrideConfigSchema=exports_external.object({model:exports_external.string().optional(),variant:exports_external.string().min(1).optional(),temperature:exports_external.number().min(0).max(2).optional(),disabled:exports_external.boolean().optional(),fallback_models:exports_external.array(exports_external.string()).max(FALLBACK_MODELS_MAX).optional(),reasoning:AgentReasoningConfigSchema.optional(),thinking:AgentThinkingConfigSchema.optional()}),SwarmConfigSchema=exports_external.object({name:exports_external.string().optional(),agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional()}),ModelPricingConfigSchema=exports_external.object({input_per_million:exports_external.number().min(0),output_per_million:exports_external.number().min(0),reasoning_per_million:exports_external.number().min(0).optional(),cache_per_million:exports_external.number().min(0).optional()}),PricingConfigSchema=exports_external.object({models:exports_external.record(exports_external.string().min(1),ModelPricingConfigSchema).optional().default({})}),HooksConfigSchema=exports_external.object({system_enhancer:exports_external.boolean().default(!0),compaction:exports_external.boolean().default(!0),agent_activity:exports_external.boolean().default(!0),delegation_tracker:exports_external.boolean().default(!1),agent_awareness_max_chars:exports_external.number().min(50).max(2000).default(300),delegation_gate:exports_external.boolean().default(!0),delegation_max_chars:exports_external.number().min(500).max(20000).default(4000),background_subagents:exports_external.boolean().default(!1),background_pending_timeout_minutes:exports_external.number().int().min(1).max(1440).default(30)}),ScoringWeightsSchema=exports_external.object({phase:exports_external.number().min(0).max(5).default(1),current_task:exports_external.number().min(0).max(5).default(2),blocked_task:exports_external.number().min(0).max(5).default(1.5),recent_failure:exports_external.number().min(0).max(5).default(2.5),recent_success:exports_external.number().min(0).max(5).default(0.5),evidence_presence:exports_external.number().min(0).max(5).default(1),decision_recency:exports_external.number().min(0).max(5).default(1.5),dependency_proximity:exports_external.number().min(0).max(5).default(1)}),DecisionDecaySchema=exports_external.object({mode:exports_external.enum(["linear","exponential"]).default("exponential"),half_life_hours:exports_external.number().min(1).max(168).default(24)}),TokenRatiosSchema=exports_external.object({prose:exports_external.number().min(0.1).max(1).default(0.25),code:exports_external.number().min(0.1).max(1).default(0.4),markdown:exports_external.number().min(0.1).max(1).default(0.3),json:exports_external.number().min(0.1).max(1).default(0.35)}),ScoringConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().min(10).max(500).default(100),weights:ScoringWeightsSchema.optional(),decision_decay:DecisionDecaySchema.optional(),token_ratios:TokenRatiosSchema.optional()}),ContextBudgetConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),warn_threshold:exports_external.number().min(0).max(1).default(0.7),critical_threshold:exports_external.number().min(0).max(1).default(0.9),model_limits:exports_external.record(exports_external.string(),exports_external.number().min(1000)).default({default:128000}),max_injection_tokens:exports_external.number().min(100).max(50000).default(4000),unified_injection_tokens:exports_external.number().min(100).max(50000).optional(),tracked_agents:exports_external.array(exports_external.string()).default(["architect"]),scoring:ScoringConfigSchema.optional(),enforce:exports_external.boolean().default(!0),prune_target:exports_external.number().min(0).max(1).default(0.7),preserve_last_n_turns:exports_external.number().min(0).max(100).default(4),recent_window:exports_external.number().min(1).max(100).default(10),enforce_on_agent_switch:exports_external.boolean().default(!0),tool_output_mask_threshold:exports_external.number().min(100).max(1e5).default(2000)}),EvidenceConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_age_days:exports_external.number().min(1).max(365).default(90),max_bundles:exports_external.number().min(10).max(1e4).default(1000),auto_archive:exports_external.boolean().default(!1),cache_max_bytes:exports_external.number().min(512).max(52428800).optional(),cache_max_records:exports_external.number().min(10).max(1e5).optional()}),GateFeatureSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),PlaceholderScanConfigSchema=GateFeatureSchema.extend({deny_patterns:exports_external.array(exports_external.string()).default(["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"]),allow_globs:exports_external.array(exports_external.string()).default(["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"]),max_allowed_findings:exports_external.number().min(0).default(0),sentinel_allowlist:exports_external.array(exports_external.string()).default([])}),QualityBudgetConfigSchema=GateFeatureSchema.extend({max_complexity_delta:exports_external.number().default(5),max_public_api_delta:exports_external.number().default(10),max_duplication_ratio:exports_external.number().default(0.05),min_test_to_code_ratio:exports_external.number().default(0.3),enforce_on_globs:exports_external.array(exports_external.string()).default(["src/**"]),exclude_globs:exports_external.array(exports_external.string()).default(["docs/**","tests/**","**/*.test.*"])}),GATE_CONFIG_KNOWN_SECTION_KEYS={syntax_check:["enabled"],placeholder_scan:["enabled","deny_patterns","allow_globs","max_allowed_findings"],sast_scan:["enabled"],sbom_generate:["enabled"],build_check:["enabled"],quality_budget:["enabled","max_complexity_delta","max_public_api_delta","max_duplication_ratio","min_test_to_code_ratio","enforce_on_globs","exclude_globs"]},GateConfigSchema=exports_external.object({syntax_check:GateFeatureSchema.default({enabled:!0}),placeholder_scan:PlaceholderScanConfigSchema.default({enabled:!0,deny_patterns:["TODO","FIXME","TBD","XXX","placeholder","stub","wip","not implemented"],allow_globs:["docs/**","examples/**","tests/**","**/*.test.*","**/*.spec.*","**/mocks/**","**/__tests__/**"],max_allowed_findings:0,sentinel_allowlist:[]}),sast_scan:GateFeatureSchema.default({enabled:!0}),sbom_generate:GateFeatureSchema.default({enabled:!0}),build_check:GateFeatureSchema.default({enabled:!0}),quality_budget:QualityBudgetConfigSchema.default(()=>QualityBudgetConfigSchema.parse({}))}),PipelineConfigSchema=exports_external.object({parallel_precheck:exports_external.boolean().default(!0)}),PhaseCompleteConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),required_agents:exports_external.array(exports_external.enum(["coder","reviewer","test_engineer"])).default(["coder","reviewer","test_engineer"]),require_docs:exports_external.boolean().default(!0),policy:exports_external.enum(["enforce","warn"]).default("enforce"),regression_sweep:exports_external.object({enforce:exports_external.boolean().default(!1)}).optional()}),SummaryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),threshold_bytes:exports_external.number().min(1024).max(1048576).default(16384),max_summary_chars:exports_external.number().min(100).max(5000).default(1000),max_stored_bytes:exports_external.number().min(10240).max(104857600).default(10485760),retention_days:exports_external.number().min(1).max(365).default(7),exempt_tools:exports_external.array(exports_external.string()).default(["retrieve_summary","retrieve_lane_output","task","read"])}),ReviewPassesConfigSchema=exports_external.object({always_security_review:exports_external.boolean().default(!1),security_globs:exports_external.array(exports_external.string()).default(["**/auth/**","**/api/**","**/crypto/**","**/security/**","**/middleware/**","**/session/**","**/token/**"])}),AutoReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger:exports_external.enum(["task_completion","phase_boundary","both"]).default("phase_boundary"),timeout_ms:exports_external.number().int().min(1e4).max(1800000).default(300000),max_diff_kb:exports_external.number().int().min(16).max(2048).default(256)}),AdversarialDetectionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),policy:exports_external.enum(["warn","gate","ignore"]).default("warn"),pairs:exports_external.array(exports_external.tuple([exports_external.string(),exports_external.string()])).default([["coder","reviewer"]])}),AdversarialTestingConfigSchemaBase=exports_external.object({enabled:exports_external.boolean().default(!0),scope:exports_external.enum(["all","security-only"]).default("all")}),AdversarialTestingConfigSchema=AdversarialTestingConfigSchemaBase.default(()=>({enabled:!0,scope:"all"})),IntegrationAnalysisConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0)}),DocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),doc_patterns:exports_external.array(exports_external.string()).default(["README.md","CONTRIBUTING.md","docs/**/*.md","docs/**/*.rst","**/CHANGELOG.md"])}),DesignDocsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),out_dir:exports_external.string().default("docs").refine((v)=>v.length>0&&v!=="."&&!v.includes("..")&&!v.startsWith("/")&&!v.startsWith("\\")&&!/^[A-Za-z]:/.test(v),{message:'design_docs.out_dir must be a non-empty project-relative path with no "..", leading slash, or drive letter'}),language:exports_external.string().optional()}),UIReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),trigger_paths:exports_external.array(exports_external.string()).default(["**/pages/**","**/components/**","**/views/**","**/screens/**","**/ui/**","**/layouts/**"]),trigger_keywords:exports_external.array(exports_external.string()).default(["new page","new screen","new component","redesign","layout change","form","modal","dialog","dropdown","sidebar","navbar","dashboard","landing page","signup","login form","settings page","profile page"])}),CompactionAdvisoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),thresholds:exports_external.array(exports_external.number().int().min(10).max(500)).default([50,75,100,125,150]),message:exports_external.string().default("[SWARM HINT] Session has ${totalToolCalls} tool calls. Consider compacting at next phase boundary to maintain context quality.")}),LintConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["check","fix"]).default("check"),linter:exports_external.enum(["biome","eslint","auto"]).default("auto"),patterns:exports_external.array(exports_external.string()).default(["**/*.{ts,tsx,js,jsx,mjs,cjs}","**/biome.json","**/biome.jsonc"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/*.min.js"])}),SecretscanConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),patterns:exports_external.array(exports_external.string()).default(["**/*.{env,properties,yml,yaml,json,js,ts}","**/.env*","**/secrets/**","**/credentials/**","**/config/**/*.ts","**/config/**/*.js"]),exclude:exports_external.array(exports_external.string()).default(["**/node_modules/**","**/dist/**","**/.git/**","**/coverage/**","**/test/**","**/tests/**","**/__tests__/**","**/*.test.ts","**/*.test.js","**/*.spec.ts","**/*.spec.js"]),extensions:exports_external.array(exports_external.string()).default([".env",".properties",".yml",".yaml",".json",".js",".ts",".py",".rb",".go",".java",".cs",".php"])}),GuardrailsProfileSchema=exports_external.object({max_tool_calls:exports_external.number().min(0).max(1000).optional(),max_duration_minutes:exports_external.number().min(0).max(480).optional(),max_repetitions:exports_external.number().min(3).max(50).optional(),max_consecutive_errors:exports_external.number().min(2).max(20).optional(),warning_threshold:exports_external.number().min(0.1).max(0.9).optional(),idle_timeout_minutes:exports_external.number().min(5).max(240).optional(),max_transient_retries:exports_external.number().min(0).max(20).optional()}),DEFAULT_AGENT_PROFILES={architect:{max_tool_calls:0,max_duration_minutes:0,max_consecutive_errors:8,warning_threshold:0.75},coder:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},test_engineer:{max_tool_calls:400,max_duration_minutes:45,max_consecutive_errors:8,warning_threshold:0.85},explorer:{max_tool_calls:150,max_duration_minutes:20,max_consecutive_errors:8,warning_threshold:0.75},reviewer:{max_tool_calls:200,max_duration_minutes:30,max_consecutive_errors:8,warning_threshold:0.65},critic:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},sme:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.65},docs:{max_tool_calls:200,max_duration_minutes:30,warning_threshold:0.75},designer:{max_tool_calls:150,max_duration_minutes:20,warning_threshold:0.75}},DEFAULT_ARCHITECT_PROFILE=DEFAULT_AGENT_PROFILES.architect,GuardrailsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tool_calls:exports_external.number().min(0).max(1000).default(200),max_duration_minutes:exports_external.number().min(0).max(480).default(30),max_repetitions:exports_external.number().min(3).max(50).default(10),max_consecutive_errors:exports_external.number().min(2).max(20).default(5),max_transient_retries:exports_external.number().min(0).max(20).default(5),warning_threshold:exports_external.number().min(0.1).max(0.9).default(0.75),idle_timeout_minutes:exports_external.number().min(5).max(240).default(60),no_op_warning_threshold:exports_external.number().min(1).max(100).default(15),max_coder_revisions:exports_external.number().int().min(1).max(20).default(5),runaway_output_max_turns:exports_external.number().int().min(1).max(20).default(5),qa_gates:exports_external.object({required_tools:exports_external.array(exports_external.string().min(1)).default(["diff","syntax_check","placeholder_scan","lint","pre_check_batch"]),require_reviewer_test_engineer:exports_external.boolean().default(!0)}).optional(),profiles:exports_external.record(exports_external.string(),GuardrailsProfileSchema).optional(),block_destructive_commands:exports_external.boolean().default(!0),interpreter_allowed_agents:exports_external.array(exports_external.string().min(1)).optional(),shell_audit_log:exports_external.boolean().default(!0)}),WatchdogConfigSchema=exports_external.object({scope_guard:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!1),delegation_ledger:exports_external.boolean().default(!0)}),SelfReviewConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),skip_in_turbo:exports_external.boolean().default(!0)});ToolFilterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),overrides:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).default({})}),PlanCursorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),max_tokens:exports_external.number().min(500).max(4000).default(1500),lookahead_tasks:exports_external.number().min(0).max(5).default(2)}),ContextMapConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["conservative","balanced","aggressive"]).default("balanced"),max_capsule_tokens:exports_external.number().int().positive().default(2000),invalidate_on_hash_change:exports_external.boolean().default(!0),agent_profiles:exports_external.record(exports_external.string(),exports_external.string()).default({})}),RepoGraphConfigSchema=exports_external.object({exclude_dirs:exports_external.array(exports_external.string().trim().min(1)).default([])}),CheckpointConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),auto_checkpoint_threshold:exports_external.number().int().min(1).max(20).default(3),allow_empty_commits:exports_external.boolean().default(!1)}).strict(),ApplyPatchConfigSchema=exports_external.object({fuzzy_match:exports_external.boolean().default(!1),fuzzy_match_context_aware:exports_external.boolean().default(!1)}).strict(),AutomationModeSchema=exports_external.enum(["manual","hybrid","auto"]),AutomationCapabilitiesSchema=exports_external.object({plan_sync:exports_external.boolean().default(!0),phase_preflight:exports_external.boolean().default(!1),config_doctor_on_startup:exports_external.boolean().default(!1),config_doctor_autofix:exports_external.boolean().default(!1),evidence_auto_summaries:exports_external.boolean().default(!0),decision_drift_detection:exports_external.boolean().default(!0)}),AutomationConfigSchemaBase=exports_external.object({mode:AutomationModeSchema.default("manual"),capabilities:AutomationCapabilitiesSchema.default({plan_sync:!0,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!0,decision_drift_detection:!0})}),AutomationConfigSchema=AutomationConfigSchemaBase,KnowledgeConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),swarm_max_entries:exports_external.number().min(1).max(1e4).default(100),hive_max_entries:exports_external.number().min(1).max(1e5).default(200),auto_promote_days:exports_external.number().min(1).max(3650).default(90),max_inject_count:exports_external.number().min(0).max(50).default(5),delegate_max_inject_count:exports_external.number().min(0).max(50).default(8),inject_char_budget:exports_external.number().min(200).max(1e4).default(2000),context_budget_threshold:exports_external.number().int().positive().optional(),max_lesson_display_chars:exports_external.number().min(40).max(280).default(120),dedup_threshold:exports_external.number().min(0).max(1).default(0.6),scope_filter:exports_external.array(exports_external.string()).default(["global"]),hive_enabled:exports_external.boolean().default(!0),rejected_max_entries:exports_external.number().min(1).max(1000).default(20),validation_enabled:exports_external.boolean().default(!0),evergreen_confidence:exports_external.number().min(0).max(1).default(0.9),evergreen_utility:exports_external.number().min(0).max(1).default(0.8),low_utility_threshold:exports_external.number().min(0).max(1).default(0.3),min_retrievals_for_utility:exports_external.number().min(1).max(100).default(3),schema_version:exports_external.number().int().min(1).default(1),directive_min_confidence:exports_external.number().min(0).max(1).default(0.75),same_project_weight:exports_external.number().min(0).max(5).default(1),cross_project_weight:exports_external.number().min(0).max(5).default(0.5),min_encounter_score:exports_external.number().min(0).max(1).default(0.1),initial_encounter_score:exports_external.number().min(0).max(5).default(1),encounter_increment:exports_external.number().min(0).max(1).default(0.1),max_encounter_score:exports_external.number().min(1).max(20).default(10),default_max_phases:exports_external.number().int().positive().default(10),todo_max_phases:exports_external.number().int().positive().default(3),sweep_enabled:exports_external.boolean().default(!0),confidence_floor_action:exports_external.enum(["none","demote","quarantine"]).default("demote"),confidence_floor_min_outcomes:exports_external.number().int().min(0).default(3),confidence_floor_signal_threshold:exports_external.number().min(-1).max(1).default(0),contradiction_threshold_action:exports_external.enum(["tag_only","quarantine"]).default("quarantine"),contradiction_quarantine_threshold:exports_external.number().int().positive().default(3),contradiction_quarantine_window_days:exports_external.number().int().positive().default(30),promoted_demotion_min_negative_phases:exports_external.number().int().positive().default(3),promoted_demotion_signal_threshold:exports_external.number().min(-1).max(1).default(OUTCOME_BLOCK_THRESHOLD),promotion_min_terminal_applications:exports_external.number().min(0).max(100).default(0),promotion_min_distinct_cohorts:exports_external.number().min(0).max(50).default(0),realtime_learning_nudge:exports_external.object({enabled:exports_external.boolean().default(!0),first_after_tool_calls:exports_external.number().int().min(1).max(1000).default(10),repeat_after_tool_calls:exports_external.number().int().min(1).max(1000).default(25)}).default({enabled:!0,first_after_tool_calls:10,repeat_after_tool_calls:25}),retrieval:exports_external.object({mmr_lambda:exports_external.number().min(0).max(1).default(0.5),cold_start_bonus:exports_external.number().min(0).max(0.5).default(0.08),cold_start_max_age_phases:exports_external.number().int().min(0).max(100).default(3),synonym_min_cooccurrence:exports_external.number().int().min(1).max(100).default(3),synonym_map_max_pairs:exports_external.number().int().min(1).max(1e4).default(500)}).optional(),enrichment:exports_external.object({max_calls_per_day:exports_external.number().int().min(0).max(1000).default(30),quota_window:exports_external.enum(["utc","local"]).default("utc"),batch_size:exports_external.number().int().min(1).max(100).optional()}).default({max_calls_per_day:30,quota_window:"utc"})}),MemoryConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),provider:exports_external.enum(["local-jsonl","sqlite"]).default("sqlite"),storageDir:exports_external.string().default(".swarm/memory"),sqlite:exports_external.object({path:exports_external.string().default(".swarm/memory/memory.db"),busyTimeoutMs:exports_external.number().int().min(0).max(60000).default(5000)}).default({path:".swarm/memory/memory.db",busyTimeoutMs:5000}),link:exports_external.object({enabled:exports_external.boolean().default(!1)}).default({enabled:!1}),recall:exports_external.object({defaultMaxItems:exports_external.number().int().min(1).max(20).default(8),defaultTokenBudget:exports_external.number().int().min(100).max(5000).default(1200),minScore:exports_external.number().min(0).max(1).default(0.05),injection:exports_external.object({enabled:exports_external.boolean().default(!0),minScore:exports_external.number().min(0).max(1).default(0.25),requireQuerySignal:exports_external.boolean().default(!0),maxItems:exports_external.number().int().min(1).max(20).default(6),tokenBudget:exports_external.number().int().min(100).max(5000).default(1000)}).default({enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000})}).default({defaultMaxItems:8,defaultTokenBudget:1200,minScore:0.05,injection:{enabled:!0,minScore:0.25,requireQuerySignal:!0,maxItems:6,tokenBudget:1000}}),learning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),propagationFactor:exports_external.number().min(0).max(1).default(0.3),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),propagationTokenOverlapThreshold:exports_external.number().min(0).max(1).default(0.4),propagationEmbeddingCosineThreshold:exports_external.number().min(0).max(1).default(0.7),propagationFanout:exports_external.number().int().min(0).max(1000).default(20),propagationLookbackDays:exports_external.number().int().min(1).max(3650).default(30)}).default({learningRate:0.1,propagationFactor:0.3,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,propagationTokenOverlapThreshold:0.4,propagationEmbeddingCosineThreshold:0.7,propagationFanout:20,propagationLookbackDays:30}),writes:exports_external.object({mode:exports_external.literal("propose").default("propose")}).default({mode:"propose"}),redaction:exports_external.object({rejectDurableSecrets:exports_external.boolean().default(!0)}).default({rejectDurableSecrets:!0}),maintenance:exports_external.object({lowUtilityMaxConfidence:exports_external.number().min(0).max(1).default(0.45),lowUtilityMinAgeDays:exports_external.number().int().min(1).max(3650).default(30),importance:exports_external.object({wRecency:exports_external.number().min(0).max(1).default(0.2),wFrequency:exports_external.number().min(0).max(1).default(0.2),wFreshness:exports_external.number().min(0).max(1).default(0.15),wConfidence:exports_external.number().min(0).max(1).default(0.25),lambda:exports_external.number().min(0).max(10).default(0.05),mu:exports_external.number().min(0).max(10).default(0.01),n:exports_external.number().int().min(1).max(1e5).default(50),threshold:exports_external.number().min(0).max(1).default(0.2)}).default({wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2})}).default({lowUtilityMaxConfidence:0.45,lowUtilityMinAgeDays:30,importance:{wRecency:0.2,wFrequency:0.2,wFreshness:0.15,wConfidence:0.25,lambda:0.05,mu:0.01,n:50,threshold:0.2}}),qLearning:exports_external.object({learningRate:exports_external.number().min(0).max(1).default(0.1),qValueBoostWeight:exports_external.number().min(0).max(1).default(0.1),suppressionThreshold:exports_external.number().min(0).max(1).default(0.15),promotionThreshold:exports_external.number().min(0).max(1).default(0.85),promotionMinRetrievals:exports_external.number().int().min(0).max(1e5).default(5),propagationFraction:exports_external.number().min(0).max(1).default(0.3),propagationFanoutCap:exports_external.number().int().min(0).max(1e4).default(20),propagationWindowDays:exports_external.number().int().min(0).max(3650).default(30),propagationRelatednessThreshold:exports_external.number().min(0).max(1).default(0.7),explorationRate:exports_external.number().min(0).max(1).default(0.05),verdictPayloadCapBytes:exports_external.number().int().min(0).max(1048576).default(8192),initialQValue:exports_external.number().min(0).max(1).default(0.5)}).default({learningRate:0.1,qValueBoostWeight:0.1,suppressionThreshold:0.15,promotionThreshold:0.85,promotionMinRetrievals:5,propagationFraction:0.3,propagationFanoutCap:20,propagationWindowDays:30,propagationRelatednessThreshold:0.7,explorationRate:0.05,verdictPayloadCapBytes:8192,initialQValue:0.5}),consolidation:exports_external.object({enabled:exports_external.boolean().default(!1),maxClustersPerPass:exports_external.number().int().min(1).max(100).default(10),jaccardThreshold:exports_external.number().min(0).max(1).default(0.3),autoApplyMinConfidence:exports_external.number().min(0).max(1).default(0.6),decayHalfLifeDays:exports_external.object({user_preference:exports_external.number().int().min(0).max(36500).default(0),project_fact:exports_external.number().int().min(0).max(36500).default(0),architecture_decision:exports_external.number().int().min(0).max(36500).default(0),repo_convention:exports_external.number().int().min(0).max(36500).default(0),api_finding:exports_external.number().int().min(0).max(36500).default(180),code_pattern:exports_external.number().int().min(0).max(36500).default(90),test_pattern:exports_external.number().int().min(0).max(36500).default(90),failure_pattern:exports_external.number().int().min(0).max(36500).default(90),security_note:exports_external.number().int().min(0).max(36500).default(0),evidence:exports_external.number().int().min(0).max(36500).default(180),todo:exports_external.number().int().min(0).max(36500).default(30),scratch:exports_external.number().int().min(0).max(36500).default(7)}).default({user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7})}).default({enabled:!1,maxClustersPerPass:10,jaccardThreshold:0.3,autoApplyMinConfidence:0.6,decayHalfLifeDays:{user_preference:0,project_fact:0,architecture_decision:0,repo_convention:0,api_finding:180,code_pattern:90,test_pattern:90,failure_pattern:90,security_note:0,evidence:180,todo:30,scratch:7}}),hardDelete:exports_external.boolean().default(!1),embeddings:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().default("Xenova/all-MiniLM-L6-v2"),dimension:exports_external.number().int().min(1).default(384),version:exports_external.string().optional(),cacheSize:exports_external.number().int().min(1).default(256)}).default({enabled:!1,model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheSize:256}),retrieval:exports_external.object({rrfK:exports_external.number().int().min(1).default(60),weights:exports_external.object({lexical:exports_external.number().min(0).max(1).default(0.5),dense:exports_external.number().min(0).max(1).default(0.4),metadata:exports_external.number().min(0).max(1).default(0.1)}).default({lexical:0.5,dense:0.4,metadata:0.1}),rerank:exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().optional()}).default({enabled:!1}),latencyBudgetMs:exports_external.number().int().min(0).default(250)}).default({rrfK:60,weights:{lexical:0.5,dense:0.4,metadata:0.1},rerank:{enabled:!1},latencyBudgetMs:250})}),CuratorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),init_enabled:exports_external.boolean().default(!0),phase_enabled:exports_external.boolean().default(!0),postmortem_enabled:exports_external.boolean().default(!0),max_summary_tokens:exports_external.number().min(500).max(8000).default(2000),min_knowledge_confidence:exports_external.number().min(0).max(1).default(0.7),compliance_report:exports_external.boolean().default(!0),suppress_warnings:exports_external.boolean().default(!0),drift_inject_max_chars:exports_external.number().min(100).max(2000).default(500),llm_timeout_ms:exports_external.number().int().min(5000).max(600000).default(300000),skill_generation_enabled:exports_external.boolean().default(!0),skill_generation_mode:exports_external.enum(["draft","active"]).default("draft"),min_skill_confidence:exports_external.number().min(0).max(1).default(0.7),min_skill_confirmations:exports_external.number().int().min(1).max(50).default(2)}),ArchitecturalSupervisionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),mode:exports_external.enum(["advisory","gate"]).default("advisory"),run_on:exports_external.enum(["phase_complete"]).default("phase_complete"),summary_model:exports_external.string().min(1).optional(),max_agent_summary_words:exports_external.number().int().min(20).max(500).default(100),max_phase_summary_words:exports_external.number().int().min(50).max(1000).default(250),allow_concerns_to_complete:exports_external.boolean().default(!0),persist_knowledge_recommendations:exports_external.boolean().default(!1),provenance_verify:exports_external.boolean().default(!1)}),KnowledgeApplicationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),mode:exports_external.enum(["warn","enforce"]).default("warn"),min_confidence:exports_external.number().min(0).max(1).default(0.85),critical_requires_ack:exports_external.boolean().default(!0),require_skill_refs:exports_external.boolean().default(!0),high_risk_tools:exports_external.array(exports_external.string()).default(["save_plan","update_task_status","phase_complete","task","Task"]),max_gate_denials:exports_external.number().int().min(1).max(100).default(5),gate_staleness_ms:exports_external.number().int().min(1e4).max(3600000).default(600000)}),SkillPropagationAudienceSchema=exports_external.string().max(64).refine((value)=>value!=="swarm-plugin",{message:"swarm-plugin is reserved for plugin-internal skill routing"}).refine((value)=>!value.startsWith("runner:"),{message:"runner:* values are derived from the active runner"}).regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,{message:"audiences must be lowercase domain tokens"}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1),audiences:exports_external.array(SkillPropagationAudienceSchema).max(16).transform((values)=>[...new Set(values)]).default([])}),SkillImproverConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),max_calls_per_day:exports_external.number().int().min(1).max(1000).default(10),trigger:exports_external.enum(["manual","scheduled"]).default("manual"),consolidation_interval_hours:exports_external.number().int().min(1).max(720).default(24),consolidation_max_calls_per_run:exports_external.number().int().min(1).max(100).default(1),targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).default(["skills","spec","architect_prompt","knowledge"]),write_mode:exports_external.enum(["proposal","draft_skills"]).default("proposal"),require_user_approval:exports_external.boolean().default(!0),quota_window:exports_external.enum(["utc","local"]).default("utc"),allow_deterministic_fallback:exports_external.boolean().default(!0)}),SkillsConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1)}),SpecWriterConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),model:exports_external.string().nullable().default(null),fallback_models:exports_external.array(exports_external.string()).default([]),allow_spec_write:exports_external.boolean().default(!0)}),SlopDetectorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),classThreshold:exports_external.number().int().min(1).default(3),commentStripThreshold:exports_external.number().int().min(1).default(5),diffLineThreshold:exports_external.number().int().min(10).default(200),importHygieneThreshold:exports_external.number().int().min(1).default(2)}),IncrementalVerifyConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),command:exports_external.union([exports_external.string(),exports_external.array(exports_external.string())]).nullable().default(null),timeoutMs:exports_external.number().int().min(1000).max(300000).default(30000),triggerAgents:exports_external.array(exports_external.string()).default(["coder"])}),CompactionConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),observationThreshold:exports_external.number().min(1).max(99).default(40),reflectionThreshold:exports_external.number().min(1).max(99).default(60),emergencyThreshold:exports_external.number().min(1).max(99).default(80),preserveLastNTurns:exports_external.number().int().min(1).default(5)}),PrmConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),pattern_thresholds:exports_external.object({repetition_loop:exports_external.number().min(1).default(2),ping_pong:exports_external.number().min(1).default(2),expansion_drift:exports_external.number().min(1).default(3),stuck_on_test:exports_external.number().min(1).default(3),context_thrash:exports_external.number().min(1).default(3)}).default(()=>({repetition_loop:2,ping_pong:2,expansion_drift:3,stuck_on_test:3,context_thrash:3})),max_trajectory_lines:exports_external.number().min(10).default(1000),escalation_enabled:exports_external.boolean().default(!0),detection_timeout_ms:exports_external.number().min(10).default(100)}),AgentAuthorityRuleSchema=exports_external.object({readOnly:exports_external.boolean().optional(),blockedExact:exports_external.array(exports_external.string()).optional(),allowedExact:exports_external.array(exports_external.string()).optional(),blockedPrefix:exports_external.array(exports_external.string()).optional(),allowedPrefix:exports_external.array(exports_external.string()).optional(),blockedZones:exports_external.array(exports_external.enum(["production","test","config","generated","docs","build"])).optional(),blockedGlobs:exports_external.array(exports_external.string()).optional(),allowedGlobs:exports_external.array(exports_external.string()).optional(),allowedCaseSensitiveGlobs:exports_external.array(exports_external.string()).optional()}),AuthorityConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),rules:exports_external.record(exports_external.string(),AgentAuthorityRuleSchema).default({}),universal_deny_prefixes:exports_external.array(exports_external.string().min(1)).default([]),verifier_config_paths:exports_external.array(exports_external.string()).optional().describe("Additional glob patterns for verifier config files that are merged into the architect agent's blockedGlobs at plugin init. Writes to matching files are blocked by the authority layer.")}),GeneralCouncilMemberConfigSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),persona:exports_external.string().optional()}).strict(),GeneralCouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),searchProvider:exports_external.enum(["tavily","brave"]).default("tavily"),searchApiKey:exports_external.string().optional(),members:exports_external.array(GeneralCouncilMemberConfigSchema).default([]),presets:exports_external.record(exports_external.string(),exports_external.array(GeneralCouncilMemberConfigSchema)).default({}),deliberate:exports_external.boolean().default(!0),moderator:exports_external.boolean().default(!0),moderatorModel:exports_external.string().optional(),maxSourcesPerMember:exports_external.number().int().min(1).max(20).default(5)}).strict(),CouncilConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxRounds:exports_external.number().int().min(1).max(10).default(3),parallelTimeoutMs:exports_external.number().int().min(5000).max(120000).default(30000),vetoPriority:exports_external.boolean().default(!0),requireAllMembers:exports_external.boolean().default(!1).describe("When true, submit_council_verdicts rejects if fewer than 5 member verdicts are provided. Equivalent to minimumMembers: 5."),minimumMembers:exports_external.number().int().min(1).max(5).default(3).describe("Minimum distinct council member verdicts required for synthesis. Default 3. Set to 1 to disable quorum enforcement. requireAllMembers: true overrides this to 5 (stricter constraint wins)."),escalateOnMaxRounds:exports_external.string().optional().describe("Optional webhook URL or handler name invoked when maxRounds is reached without APPROVE. Declared for forward compatibility; no behavior is implemented yet."),phaseConcernsAllowComplete:exports_external.boolean().default(!0).describe("When true, a phase-level council CONCERNS verdict with only MEDIUM/LOW findings does NOT block phase completion — the advisory notes are logged as warnings and the phase proceeds. When false, CONCERNS blocks like REJECT. Note: HIGH/CRITICAL findings from CONCERNS members are always promoted to requiredFixes and block at the tool level regardless of this setting. Default: true."),general:GeneralCouncilConfigSchema.optional()}).strict(),PrMonitorConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),poll_interval_seconds:exports_external.number().int().min(30).max(300).default(60),max_subscriptions:exports_external.number().int().min(1).max(100).default(20),max_prs_per_cycle:exports_external.number().int().min(1).max(20).default(5),max_concurrent_pr_polls:exports_external.number().int().min(1).max(10).default(3),poll_timeout_ms:exports_external.number().int().min(5000).max(120000).default(30000),failure_threshold:exports_external.number().int().min(1).max(20).default(5),cooldown_seconds:exports_external.number().int().min(5).max(600).default(30),max_cooldown_seconds:exports_external.number().int().min(30).max(3600).default(300),cleanup_ttl_days:exports_external.number().int().min(1).max(90).default(7),auto_unsubscribe_on_merge:exports_external.boolean().default(!0),auto_unsubscribe_on_close:exports_external.boolean().default(!0),notify_ci_failure:exports_external.boolean().default(!0),notify_new_comments:exports_external.boolean().default(!0),notify_merge_conflict:exports_external.boolean().default(!0),notify_review_activity:exports_external.boolean().default(!0),notify_merged:exports_external.boolean().default(!0),notify_closed:exports_external.boolean().default(!0),notify_ci_success:exports_external.boolean().default(!1),auto_pr_feedback:exports_external.boolean().default(!1),event_delivery:exports_external.enum(["advisory","prompt"]).default("prompt"),auto_subscribe_on_pr_create:exports_external.boolean().default(!0)}).strict(),ParallelizationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!1),maxConcurrentTasks:exports_external.number().int().min(1).max(64).default(1),evidenceLockTimeoutMs:exports_external.number().int().min(1000).max(300000).default(60000),max_coders:exports_external.number().int().min(1).max(16).default(3),max_reviewers:exports_external.number().int().min(1).max(16).default(2)}),WorktreeIsolationConfigSchema=exports_external.object({policy:exports_external.enum(["auto","required","disabled"]).default("auto"),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge"),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).default("skip"),serialization_release_after_dispatches:exports_external.number().int().positive().default(5),serialization_release_after_ms:exports_external.number().int().positive().default(60000),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),LeanTurboConfigSchema=exports_external.object({max_parallel_coders:exports_external.number().int().min(1).max(6).default(4),require_declared_scope:exports_external.boolean().default(!0),conflict_policy:exports_external.enum(["serialize","degrade"]).default("serialize"),degrade_on_risk:exports_external.boolean().default(!0),phase_reviewer:exports_external.boolean().default(!0),phase_critic:exports_external.boolean().default(!0),integrated_diff_required:exports_external.boolean().default(!0),allow_docs_only_without_reviewer:exports_external.boolean().default(!1),worktree_isolation:exports_external.boolean().default(!0),merge_strategy:exports_external.enum(["merge","rebase","cherry-pick"]).default("merge").optional(),worktree_dir:exports_external.string().optional(),deps_strategy:exports_external.enum(["skip","copy","link"]).optional(),runtime_isolation:exports_external.object({enabled:exports_external.boolean().default(!1),port_base:exports_external.number().int().nonnegative().max(65535).optional(),port_stride:exports_external.number().int().positive().default(1),env_overrides:exports_external.record(exports_external.string(),exports_external.string()).optional(),cache_redirects:exports_external.record(exports_external.string(),exports_external.string()).optional()}).optional()}),EpicConfigSchema=exports_external.object({cochange:exports_external.object({enabled:exports_external.boolean().default(!1),threshold:exports_external.number().min(-1).max(1).default(0.6),min_co_changes:exports_external.number().int().min(1).default(5)}).strict().optional(),mode:exports_external.object({enabled:exports_external.boolean().default(!1),activation_threshold:exports_external.number().min(0).max(1).default(0.3),min_commits_for_signal:exports_external.number().int().min(1).default(20)}).strict().optional(),calibration:exports_external.object({enabled:exports_external.boolean().default(!0),floor_threshold:exports_external.number().min(0).max(1).default(0.05),tighten_step:exports_external.number().min(0).max(1).default(0.02),loosen_step:exports_external.number().min(0).max(1).default(0.01),loosen_window:exports_external.number().int().min(1).default(10)}).strict().optional()}).strict(),StandardTurboConfigSchema=exports_external.object({strategy:exports_external.literal("standard"),lean:LeanTurboConfigSchema.optional(),epic:EpicConfigSchema.optional()}),LeanTurboStrategyConfigSchema=exports_external.object({strategy:exports_external.literal("lean"),lean:LeanTurboConfigSchema,epic:EpicConfigSchema.optional()}),TurboConfigSchema=exports_external.discriminatedUnion("strategy",[StandardTurboConfigSchema,LeanTurboStrategyConfigSchema]),ExternalSkillCandidateSourceTypeSchema=exports_external.enum(["github","url","collection","manual_import"]),ExternalSkillCandidateEvaluationVerdictSchema=exports_external.enum(["pending","in_review","quarantined","passed","rejected","promoted","revoked"]),DiscoverySourceSchema=exports_external.object({type:ExternalSkillCandidateSourceTypeSchema,location:exports_external.string().min(1),enabled:exports_external.boolean().default(!0),trust_level:exports_external.enum(["low","medium","high"]).default("low").optional()}),ExternalSkillCandidateSchema=exports_external.object({id:exports_external.string().uuid(),source_url:exports_external.string().url(),source_type:ExternalSkillCandidateSourceTypeSchema,publisher:exports_external.string().min(1),sha256:exports_external.string().regex(/^[a-f0-9]{64}$/),fetched_at:exports_external.string().datetime(),skill_name:exports_external.string().optional(),skill_description:exports_external.string().optional(),skill_body:exports_external.string(),risk_flags:exports_external.array(exports_external.string()).default([]),evaluation_verdict:ExternalSkillCandidateEvaluationVerdictSchema.default("pending"),evaluation_history:exports_external.array(exports_external.object({verdict:ExternalSkillCandidateEvaluationVerdictSchema,timestamp:exports_external.string().datetime(),actor:exports_external.string(),reason:exports_external.string().optional(),candidate_id:exports_external.string().optional(),original_verdict:ExternalSkillCandidateEvaluationVerdictSchema.optional(),gate_results:exports_external.array(exports_external.object({gate:exports_external.string(),verdict:exports_external.string()})).optional(),risk_assessment:exports_external.object({total_flags:exports_external.number().int().nonnegative(),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["error","warning"]),category:exports_external.string()}))}).optional(),risk_flags_count:exports_external.number().int().nonnegative().optional(),provenance_snapshot:exports_external.object({sha256:exports_external.string(),source_url:exports_external.string(),publisher:exports_external.string(),fetched_at:exports_external.string().datetime().optional()}).optional(),target_path:exports_external.string().optional(),promoted_content_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),original_evaluation:exports_external.record(exports_external.string(),exports_external.unknown()).optional()})).default([])}),ExternalSkillsConfigSchema=exports_external.object({curation_enabled:exports_external.boolean().default(!1),max_candidates:exports_external.number().int().min(1).max(1e4).default(500),max_bytes_per_candidate:exports_external.number().int().min(1024).max(10485760).default(1048576),eviction_policy:exports_external.enum(["fifo"]).default("fifo"),ttl_days:exports_external.number().int().min(1).max(3650).default(90),evaluation_enabled:exports_external.boolean().default(!1),sources:exports_external.array(DiscoverySourceSchema).default([]),max_candidates_per_discovery:exports_external.number().int().min(1).max(1000).default(50),max_concurrent_fetches:exports_external.number().int().min(1).max(20).default(5),fetch_timeout_ms:exports_external.number().int().min(1000).max(300000).default(30000)}),DEFAULT_EXTERNAL_SKILLS_CONFIG={curation_enabled:!1,max_candidates:500,max_bytes_per_candidate:1048576,eviction_policy:"fifo",ttl_days:90,evaluation_enabled:!1,sources:[],max_candidates_per_discovery:50,max_concurrent_fetches:5,fetch_timeout_ms:30000},DEFAULT_SKILLS_CONFIG={enabled:!1};PluginConfigSchema=exports_external.object({agents:exports_external.record(exports_external.string(),AgentOverrideConfigSchema).optional(),default_agent:exports_external.string().optional().transform((v)=>{if(v===void 0)return;let trimmed=v.trim();return trimmed===""?void 0:trimmed}),auto_select_architect:exports_external.union([exports_external.boolean(),exports_external.string()]).optional().transform((v)=>{if(v===void 0)return;if(typeof v==="boolean")return v;let trimmed=v.trim();return trimmed===""?!1:trimmed}),swarms:exports_external.record(exports_external.string().regex(/^[^_]+$/,"Swarm ID must not contain underscores"),SwarmConfigSchema).optional(),max_iterations:exports_external.number().min(1).max(10).default(5),pipeline:PipelineConfigSchema.optional(),phase_complete:PhaseCompleteConfigSchema.optional(),qa_retry_limit:exports_external.number().min(1).max(10).default(3),execution_mode:exports_external.enum(["strict","balanced","fast"]).default("balanced"),inject_phase_reminders:exports_external.boolean().default(!0),hooks:HooksConfigSchema.optional(),gates:GateConfigSchema.optional(),context_budget:ContextBudgetConfigSchema.optional(),pricing:PricingConfigSchema.optional(),guardrails:GuardrailsConfigSchema.optional(),watchdog:WatchdogConfigSchema.optional(),self_review:SelfReviewConfigSchema.optional(),auto_review:AutoReviewConfigSchema.optional(),tool_filter:ToolFilterConfigSchema.optional(),authority:AuthorityConfigSchema.optional(),plan_cursor:PlanCursorConfigSchema.optional(),context_map:ContextMapConfigSchema.optional(),repo_graph:RepoGraphConfigSchema.optional(),evidence:EvidenceConfigSchema.optional(),summaries:SummaryConfigSchema.optional(),review_passes:ReviewPassesConfigSchema.optional(),adversarial_detection:AdversarialDetectionConfigSchema.optional(),adversarial_testing:AdversarialTestingConfigSchema.optional(),integration_analysis:IntegrationAnalysisConfigSchema.optional(),docs:DocsConfigSchema.optional(),design_docs:DesignDocsConfigSchema.optional(),ui_review:UIReviewConfigSchema.optional(),compaction_advisory:CompactionAdvisoryConfigSchema.optional(),lint:LintConfigSchema.optional(),secretscan:SecretscanConfigSchema.optional(),checkpoint:CheckpointConfigSchema.optional(),apply_patch:ApplyPatchConfigSchema.optional(),automation:AutomationConfigSchema.optional(),knowledge:KnowledgeConfigSchema.optional(),memory:MemoryConfigSchema.optional(),curator:CuratorConfigSchema.optional(),architectural_supervision:ArchitecturalSupervisionConfigSchema.optional(),knowledge_application:KnowledgeApplicationConfigSchema.optional(),skillPropagation:SkillPropagationConfigSchema.optional(),skill_improver:SkillImproverConfigSchema.optional(),spec_writer:SpecWriterConfigSchema.optional(),tool_output:exports_external.object({truncation_enabled:exports_external.boolean().default(!0),max_lines:exports_external.number().min(10).max(500).default(150),per_tool:exports_external.record(exports_external.string(),exports_external.number()).optional(),truncation_tools:exports_external.array(exports_external.string()).optional().describe("Tools to apply output truncation to. Defaults to diff, symbols, bash, shell, test_runner, lint, pre_check_batch, complexity_hotspots, pkg_audit, sbom_generate, schema_drift.")}).optional(),slop_detector:SlopDetectorConfigSchema.optional(),todo_gate:exports_external.object({enabled:exports_external.boolean().default(!0),max_high_priority:exports_external.number().int().min(-1).default(0).describe("Max new high-priority TODOs (FIXME/HACK/XXX) before warning. 0 = warn on any. Set to -1 to disable."),block_on_threshold:exports_external.boolean().default(!1).describe("If true, block phase completion when threshold exceeded. Default: advisory only.")}).optional(),incremental_verify:IncrementalVerifyConfigSchema.optional(),compaction_service:CompactionConfigSchema.optional(),prm:PrmConfigSchema.optional(),council:CouncilConfigSchema.optional(),parallelization:ParallelizationConfigSchema.optional(),worktree:WorktreeIsolationConfigSchema.optional(),turbo:TurboConfigSchema.optional(),turbo_mode:exports_external.boolean().default(!1).optional(),quiet:exports_external.boolean().default(!0).optional(),version_check:exports_external.boolean().default(!0).optional(),full_auto:exports_external.object({enabled:exports_external.boolean().default(!1),locked:exports_external.boolean().default(!1),critic_model:exports_external.string().optional(),max_interactions_per_phase:exports_external.number().int().min(5).max(200).default(50),deadlock_threshold:exports_external.number().int().min(2).max(10).default(3),escalation_mode:exports_external.enum(["pause","terminate"]).default("pause"),mode:exports_external.enum(["assisted","supervised","strict"]).default("supervised"),fail_closed:exports_external.boolean().default(!0),permission_policy:exports_external.object({enabled:exports_external.boolean().default(!0),trusted_roots:exports_external.array(exports_external.string()).default(["."]),trusted_domains:exports_external.array(exports_external.string()).default([]),protected_paths:exports_external.array(exports_external.string()).default([".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"]),allow_defaults:exports_external.boolean().default(!0)}).default(()=>({enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0})),denials:exports_external.object({max_consecutive:exports_external.number().int().min(1).max(50).default(3),max_total:exports_external.number().int().min(1).max(500).default(20),on_limit:exports_external.enum(["pause","terminate"]).default("pause")}).default(()=>({max_consecutive:3,max_total:20,on_limit:"pause"})),oversight:exports_external.object({on_plan_change:exports_external.boolean().default(!0),on_task_completion:exports_external.boolean().default(!1),on_phase_boundary:exports_external.boolean().default(!0),on_high_risk_action:exports_external.boolean().default(!0),on_subagent_return_warning:exports_external.boolean().default(!0),every_tool_calls:exports_external.number().int().min(0).max(1e4).default(25),every_architect_turns:exports_external.number().int().min(0).max(1000).default(5),every_minutes:exports_external.number().int().min(0).max(1440).default(20),max_dispatch_retries:exports_external.number().int().min(0).max(10).default(2),max_consecutive_dispatch_failures:exports_external.number().int().min(0).max(50).default(3)}).default(()=>({on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}))}).optional().default(()=>({enabled:!1,locked:!1,max_interactions_per_phase:50,deadlock_threshold:3,escalation_mode:"pause",mode:"supervised",fail_closed:!0,permission_policy:{enabled:!0,trusted_roots:["."],trusted_domains:[],protected_paths:[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","dist"],allow_defaults:!0},denials:{max_consecutive:3,max_total:20,on_limit:"pause"},oversight:{on_plan_change:!0,on_task_completion:!1,on_phase_boundary:!0,on_high_risk_action:!0,on_subagent_return_warning:!0,every_tool_calls:25,every_architect_turns:5,every_minutes:20,max_dispatch_retries:2,max_consecutive_dispatch_failures:3}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional()})});var exports_loader={};__export(exports_loader,{loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,formatZodIssues:()=>formatZodIssues,deepMerge:()=>deepMerge,MAX_MERGE_DEPTH:()=>MAX_MERGE_DEPTH,MAX_CONFIG_FILE_BYTES:()=>MAX_CONFIG_FILE_BYTES});import*as fs from"node:fs";import*as fsPromises from"node:fs/promises";import*as os from"node:os";import*as path from"node:path";function getUserConfigDir(){return process.env.XDG_CONFIG_HOME||path.join(os.homedir(),".config")}function loadRawConfigFromPath(configPath){try{if(fs.statSync(configPath).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=fs.readFileSync(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(!(error49 instanceof Error&&("code"in error49)&&error49.code==="ENOENT")){let errorMessage=error49 instanceof Error?error49.message:String(error49);return advisoryWarn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config load failed. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0}}return{config:null,fileExisted:!1,hadError:!1}}}function migratePresetsConfig(raw){if(raw.presets&&typeof raw.presets==="object"&&!raw.agents){let presetName=raw.preset||"remote",presets=raw.presets,activePreset=presets[presetName]||Object.values(presets)[0];if(activePreset&&typeof activePreset==="object"){let migrated={...raw,agents:activePreset};return delete migrated.preset,delete migrated.presets,delete migrated.swarm_mode,advisoryWarn("[opencode-swarm] Migrated v6.12 presets config to agents format. Consider updating your opencode-swarm.json."),migrated}}return raw}function sanitizeExternalSkillsConfig(raw){if(!("external_skills"in raw)||raw.external_skills===void 0)return raw;let esResult=ExternalSkillsConfigSchema.safeParse(raw.external_skills);if(esResult.success)return{...raw,external_skills:resolveExternalSkillsConfig(esResult.data)};advisoryWarn("[opencode-swarm] external_skills config validation failed:",formatZodIssues(esResult.error)),advisoryWarn("[opencode-swarm] External skills curation disabled due to invalid config. Fix the external_skills section to enable it.");let cleaned={...raw};return delete cleaned.external_skills,cleaned}function sanitizeGatesConfig(raw){if(!("gates"in raw)||raw.gates===void 0)return raw;if(typeof raw.gates!=="object"||raw.gates===null||Array.isArray(raw.gates)){advisoryWarn("[opencode-swarm] gates config validation failed: expected an object. Quality gates will use defaults; other config sections remain active.");let cleaned2={...raw};return delete cleaned2.gates,cleaned2}let gateSchemas=GateConfigSchema.shape,cleanedGates={...raw.gates};for(let[key,value]of Object.entries(cleanedGates)){let schema=gateSchemas[key];if(!schema){advisoryWarn(`[opencode-swarm] Unknown gates config section "gates.${key}" ignored. Other config sections remain active.`),delete cleanedGates[key];continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[key],sectionValue=value;if(knownFields&&typeof value==="object"&&value!==null&&!Array.isArray(value)){let cleanedSection={...value},knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(cleanedSection))if(!knownFieldSet.has(fieldName))advisoryWarn(`[opencode-swarm] Unknown gates config key "gates.${key}.${fieldName}" ignored. Other config sections remain active.`),delete cleanedSection[fieldName];sectionValue=cleanedSection,cleanedGates[key]=cleanedSection}let sectionResult=schema.safeParse(sectionValue);if(!sectionResult.success)advisoryWarn(`[opencode-swarm] gates.${key} config validation failed; that gate section will use defaults and other config sections remain active:`,formatZodIssues(sectionResult.error)),delete cleanedGates[key]}let gatesResult=GateConfigSchema.safeParse(cleanedGates);if(gatesResult.success)return{...raw,gates:gatesResult.data};advisoryWarn("[opencode-swarm] gates config validation failed after section cleanup; quality gates will use defaults and other config sections remain active:",formatZodIssues(gatesResult.error));let cleaned={...raw};return delete cleaned.gates,cleaned}function sanitizeSectionConfigs(raw){return sanitizeGatesConfig(sanitizeExternalSkillsConfig(raw))}function formatZodIssues(error49){if(error49.issues.length===0)return"";return error49.issues.map((issue2)=>{let dotted=issue2.path.map(String).join(".");return dotted?`${dotted}: ${issue2.message}`:issue2.message}).join("; ")}function stripUnrecognizedKeys(raw,error49){let removed=[],cleaned=structuredClone(raw);for(let issue2 of error49.issues){if(issue2.code!=="unrecognized_keys")continue;let keys=issue2.keys??[],node=cleaned;for(let seg of issue2.path)if(node&&typeof node==="object")node=node[seg];else{node=void 0;break}if(!node||typeof node!=="object")continue;for(let key of keys)if(key in node){delete node[key];let dotted=[...issue2.path.map(String),key].join(".");removed.push(dotted)}}return{cleaned,removed}}function parseConfigWithFallback(mergedRaw,rawUserConfig,failedResult,loadedFromFile,configHadErrors){let result=failedResult,secure=(config2)=>loadedFromFile&&configHadErrors?PluginConfigSchema.parse({...config2,guardrails:{enabled:!0}}):config2,{cleaned,removed}=stripUnrecognizedKeys(mergedRaw,result.error);if(removed.length>0){let recovered=PluginConfigSchema.safeParse(cleaned);if(recovered.success){let warning=`Ignored ${removed.length} unrecognized config key(s): ${removed.join(", ")}. The rest of your configuration was preserved. Fix or remove these keys.`;return advisoryWarn(`[opencode-swarm] ${warning}`),{config:secure(recovered.data),recovery:"stripped_keys",removedKeys:removed,warnings:[warning]}}}if(rawUserConfig){let userSanitized=sanitizeSectionConfigs(rawUserConfig??{}),userParseResult=PluginConfigSchema.safeParse(userSanitized);if(userParseResult.success)return advisoryWarn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),{config:secure(userParseResult.data),recovery:"user_only",removedKeys:[],warnings:["Project config ignored due to validation errors. Using user config."]};let userStripped=stripUnrecognizedKeys(userSanitized,userParseResult.error);if(userStripped.removed.length>0){let userRecovered=PluginConfigSchema.safeParse(userStripped.cleaned);if(userRecovered.success){let warning=`Project config ignored; also ignored ${userStripped.removed.length} unrecognized user-config key(s): ${userStripped.removed.join(", ")}.`;return advisoryWarn(`[opencode-swarm] ${warning}`),{config:secure(userRecovered.data),recovery:"user_only",removedKeys:userStripped.removed,warnings:[warning]}}}}let offending=stripUnrecognizedKeys(mergedRaw,result.error).removed,warnings=[];if(offending.length>0){let warning=`Merged config validation failed. Unrecognized key(s): ${offending.join(", ")}.`;advisoryWarn(`[opencode-swarm] ${warning}`),warnings.push(warning)}else advisoryWarn("[opencode-swarm] Merged config validation failed:",formatZodIssues(result.error)),warnings.push("Merged config validation failed.");let securityWarning="⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration.";return advisoryWarn(`[opencode-swarm] ${securityWarning}`),warnings.push(securityWarning),{config:PluginConfigSchema.parse({guardrails:{enabled:!0}}),recovery:"guardrails_defaults",removedKeys:offending,warnings}}function rawFullAutoLocked(raw){if(!raw||typeof raw!=="object")return!1;let fullAuto=raw.full_auto;if(!fullAuto||typeof fullAuto!=="object"||Array.isArray(fullAuto))return!1;return fullAuto.locked===!0}function loadPluginConfig(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),rawUserConfig=userResult.config,rawProjectConfig=projectResult.config,loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fullAutoRaw=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fullAutoRaw,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeSectionConfigs(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(result.success){if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}let{config:config2}=parseConfigWithFallback(mergedRaw,rawUserConfig,result,loadedFromFile,configHadErrors);return config2}function loadPluginConfigWithMeta(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),userResult=loadRawConfigFromPath(userConfigPath),projectResult=loadRawConfigFromPath(projectConfigPath),rawUserConfig=userResult.config,rawProjectConfig=projectResult.config,loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);if(rawFullAutoLocked(rawUserConfig)||rawFullAutoLocked(rawProjectConfig)){let fullAutoRaw=mergedRaw.full_auto&&typeof mergedRaw.full_auto==="object"&&!Array.isArray(mergedRaw.full_auto)?mergedRaw.full_auto:{};mergedRaw={...mergedRaw,full_auto:{...fullAutoRaw,locked:!0}}}mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeSectionConfigs(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(result.success){if(loadedFromFile&&configHadErrors)return{config:PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}}),loadedFromFile,configHadErrors,recovery:"guardrails_defaults",removedKeys:[],warnings:["⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."]};return{config:result.data,loadedFromFile,configHadErrors,recovery:"none",removedKeys:[],warnings:[]}}let{config:config2,recovery,removedKeys,warnings}=parseConfigWithFallback(mergedRaw,rawUserConfig,result,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings}}async function loadRawConfigFromPathAsync(configPath){try{if((await fsPromises.stat(configPath)).size>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let content=await fsPromises.readFile(configPath,"utf-8");if(content.length>MAX_CONFIG_FILE_BYTES)return advisoryWarn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config file exceeds size limit. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};let sanitizedContent=content;if(content.charCodeAt(0)===65279)sanitizedContent=content.slice(1);let rawConfig=JSON.parse(sanitizedContent);if(typeof rawConfig!=="object"||rawConfig===null||Array.isArray(rawConfig))return advisoryWarn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),advisoryWarn("[opencode-swarm] ⚠️ SECURITY: Config format invalid. Falling back to safe defaults with guardrails ENABLED."),{config:null,fileExisted:!0,hadError:!0};return{config:rawConfig,fileExisted:!0,hadError:!1}}catch(error49){if(error49.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return advisoryWarn(`[opencode-swarm] Failed to load config from ${configPath}:`,error49 instanceof Error?error49.message:String(error49)),{config:null,fileExisted:!0,hadError:!0}}}function reduceParsedConfig(rawUserConfig,rawProjectConfig,loadedFromFile,configHadErrors){let mergedRaw=rawUserConfig??{};if(rawProjectConfig)mergedRaw=deepMerge(mergedRaw,rawProjectConfig);mergedRaw=migratePresetsConfig(mergedRaw),mergedRaw=sanitizeSectionConfigs(mergedRaw);let result=PluginConfigSchema.safeParse(mergedRaw);if(result.success){if(loadedFromFile&&configHadErrors)return{config:PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}}),recovery:"guardrails_defaults",removedKeys:[],warnings:["⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."]};return{config:result.data,recovery:"none",removedKeys:[],warnings:[]}}return parseConfigWithFallback(mergedRaw,rawUserConfig,result,loadedFromFile,configHadErrors)}async function loadPluginConfigWithMetaAsync(directory){let userConfigPath=path.join(getUserConfigDir(),"opencode",CONFIG_FILENAME),projectConfigPath=path.join(directory,".opencode",CONFIG_FILENAME),[userResult,projectResult]=await Promise.all([loadRawConfigFromPathAsync(userConfigPath),loadRawConfigFromPathAsync(projectConfigPath)]),loadedFromFile=userResult.fileExisted||projectResult.fileExisted,configHadErrors=userResult.hadError||projectResult.hadError,{config:config2,recovery,removedKeys,warnings}=reduceParsedConfig(userResult.config,projectResult.config,loadedFromFile,configHadErrors);return{config:config2,loadedFromFile,configHadErrors,recovery,removedKeys,warnings}}function loadAgentPrompt(agentName){let promptsDir=path.join(getUserConfigDir(),"opencode",PROMPTS_DIR_NAME),result={},promptPath=path.join(promptsDir,`${agentName}.md`);if(fs.existsSync(promptPath))try{result.prompt=fs.readFileSync(promptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error49 instanceof Error?error49.message:String(error49))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error49){advisoryWarn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error49 instanceof Error?error49.message:String(error49))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{init_warning_buffer();init_schema()});var ExecutionProfileSchema,TaskStatusSchema,TaskSizeSchema,PhaseStatusSchema,MigrationStatusSchema,TaskSchema,PhaseSchema,PlanSchema;var init_plan_schema=__esm(()=>{init_zod();ExecutionProfileSchema=exports_external.object({parallelization_enabled:exports_external.boolean().default(!1),max_concurrent_tasks:exports_external.number().int().min(1).max(64).default(10),council_parallel:exports_external.boolean().default(!0),locked:exports_external.boolean().default(!1),auto_proceed:exports_external.boolean().default(!1)}),TaskStatusSchema=exports_external.enum(["pending","in_progress","completed","blocked","closed"]),TaskSizeSchema=exports_external.enum(["small","medium","large"]),PhaseStatusSchema=exports_external.enum(["pending","in_progress","complete","completed","blocked","closed"]),MigrationStatusSchema=exports_external.enum(["native","migrated","migration_failed"]),TaskSchema=exports_external.object({id:exports_external.string(),phase:exports_external.number().int().min(1),status:TaskStatusSchema.default("pending"),size:TaskSizeSchema.default("small"),description:exports_external.string().min(1),depends:exports_external.array(exports_external.string()).default([]),acceptance:exports_external.string().optional(),files_touched:exports_external.array(exports_external.string()).default([]),evidence_path:exports_external.string().optional(),blocked_reason:exports_external.string().optional(),fr_refs:exports_external.array(exports_external.string()).optional()}),PhaseSchema=exports_external.object({id:exports_external.number().int().min(1),name:exports_external.string().min(1),status:PhaseStatusSchema.default("pending"),tasks:exports_external.array(TaskSchema).default([]),type:exports_external.enum(["code","non-code"]).optional(),required_agents:exports_external.array(exports_external.string()).optional()}),PlanSchema=exports_external.object({schema_version:exports_external.literal("1.0.0"),title:exports_external.string().min(1),swarm:exports_external.string().min(1),current_phase:exports_external.number().int().min(1).optional(),phases:exports_external.array(PhaseSchema).min(1),migration_status:MigrationStatusSchema.optional(),specMtime:exports_external.string().optional(),specHash:exports_external.string().optional(),execution_profile:ExecutionProfileSchema.optional()})});function stripCodeBlocks(content){return content.replace(FENCED_BLOCK_PATTERN,"").replace(INLINE_CODE_PATTERN,"")}function getLineNumber(content,position){return(content.substring(0,position).match(/\n/g)||[]).length+1}function validateSpecContent(content){let issues=[];if(!content||content.trim().length===0)return{valid:!1,issues:[{line:1,message:"Content is empty"}]};let strippedContent=stripCodeBlocks(content),frMatches=strippedContent.match(FR_ID_PATTERN);if(!frMatches||frMatches.length===0)issues.push({line:1,message:"No FR-### requirement IDs found in spec content"});let obligationMatches=strippedContent.match(OBLIGATION_PATTERN);if(!obligationMatches||obligationMatches.length===0)issues.push({line:1,message:"No obligation keywords (MUST, SHALL, SHOULD, MAY) found in spec content"});let sectionMatches=strippedContent.match(SECTION_HEADER_PATTERN);if(!sectionMatches||sectionMatches.length===0)issues.push({line:1,message:"No section headers (## Section Name) found in spec content"});let idMatches=strippedContent.matchAll(/\bFR-(\d{3})\b/g);for(let idMatch of idMatches)if(parseInt(idMatch[1],10)===0){let pos=idMatch.index;issues.push({line:getLineNumber(strippedContent,pos),message:`Invalid FR-ID "${idMatch[0]}" — number must be 001-999`})}return{valid:issues.length===0,issues}}var ObligationSchema,SpecRequirementSchema,SpecScenarioSchema,SpecSectionSchema,SwarmSpecSchema,SpecDeltaSchema,DeltaSpecSchema,FENCED_BLOCK_PATTERN,INLINE_CODE_PATTERN,FR_ID_PATTERN,OBLIGATION_PATTERN,SECTION_HEADER_PATTERN;var init_spec_schema=__esm(()=>{init_zod();ObligationSchema=exports_external.enum(["MUST","SHALL","SHOULD","MAY"]),SpecRequirementSchema=exports_external.object({id:exports_external.string().regex(/^FR-(?!000)\d{3}$/,"Requirement ID must match FR-### pattern (e.g., FR-001)"),obligation:ObligationSchema,text:exports_external.string().min(1)}),SpecScenarioSchema=exports_external.object({name:exports_external.string().min(1),given:exports_external.array(exports_external.string()).optional().default([]),when:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "when" clause'),thenClauses:exports_external.array(exports_external.string()).min(1,'Scenario must have at least one "then" clause')}),SpecSectionSchema=exports_external.object({name:exports_external.string().min(1),requirements:exports_external.array(SpecRequirementSchema).default([])}),SwarmSpecSchema=exports_external.object({title:exports_external.string().min(1),purpose:exports_external.string().min(1),sections:exports_external.array(SpecSectionSchema).min(1,"Spec must have at least one section")}),SpecDeltaSchema=exports_external.object({added:exports_external.array(SpecRequirementSchema).default([]),modified:exports_external.array(SpecRequirementSchema).default([]),removed:exports_external.array(SpecRequirementSchema).default([])}),DeltaSpecSchema=exports_external.union([SwarmSpecSchema,SpecDeltaSchema]),FENCED_BLOCK_PATTERN=/```[\s\S]*?```/g,INLINE_CODE_PATTERN=/`[^`]*`/g,FR_ID_PATTERN=/\bFR-\d{3}\b/g,OBLIGATION_PATTERN=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SECTION_HEADER_PATTERN=/^##\s+.+$/gm});function resolveWorktreeIsolationConfig(config2){if(config2.worktree)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,...config2.worktree};let lean=config2.turbo?.strategy==="lean"?config2.turbo.lean:void 0;if(lean?.worktree_isolation)return{...DEFAULT_WORKTREE_ISOLATION_CONFIG,policy:"auto",merge_strategy:lean.merge_strategy??"merge",worktree_dir:lean.worktree_dir,deps_strategy:lean.deps_strategy??"skip",runtime_isolation:lean.runtime_isolation??DEFAULT_WORKTREE_ISOLATION_CONFIG.runtime_isolation};return DEFAULT_WORKTREE_ISOLATION_CONFIG}var init_worktree_isolation_config=__esm(()=>{init_constants()});var exports_config={};__export(exports_config,{validateSpecContent:()=>validateSpecContent,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,loadPluginConfigWithMetaAsync:()=>loadPluginConfigWithMetaAsync,loadPluginConfigWithMeta:()=>loadPluginConfigWithMeta,loadPluginConfig:()=>loadPluginConfig,loadAgentPrompt:()=>loadAgentPrompt,isSubagent:()=>isSubagent,isQAAgent:()=>isQAAgent,_internals:()=>_internals2,WorktreeIsolationConfigSchema:()=>WorktreeIsolationConfigSchema,TurboConfigSchema:()=>TurboConfigSchema,TestEvidenceSchema:()=>TestEvidenceSchema,TaskStatusSchema:()=>TaskStatusSchema,TaskSizeSchema:()=>TaskSizeSchema,TaskSchema:()=>TaskSchema,SwarmSpecSchema:()=>SwarmSpecSchema,SwarmConfigSchema:()=>SwarmConfigSchema,SpecSectionSchema:()=>SpecSectionSchema,SpecScenarioSchema:()=>SpecScenarioSchema,SpecRequirementSchema:()=>SpecRequirementSchema,SpecDeltaSchema:()=>SpecDeltaSchema,SkillPropagationConfigSchema:()=>SkillPropagationConfigSchema,ReviewEvidenceSchema:()=>ReviewEvidenceSchema,RepoGraphConfigSchema:()=>RepoGraphConfigSchema,QA_AGENTS:()=>QA_AGENTS,PricingConfigSchema:()=>PricingConfigSchema,PluginConfigSchema:()=>PluginConfigSchema,PlanSchema:()=>PlanSchema,PipelineConfigSchema:()=>PipelineConfigSchema,PhaseStatusSchema:()=>PhaseStatusSchema,PhaseSchema:()=>PhaseSchema,PhaseCompleteConfigSchema:()=>PhaseCompleteConfigSchema,PIPELINE_AGENTS:()=>PIPELINE_AGENTS,ObligationSchema:()=>ObligationSchema,ORCHESTRATOR_NAME:()=>ORCHESTRATOR_NAME,NoteEvidenceSchema:()=>NoteEvidenceSchema,ModelPricingConfigSchema:()=>ModelPricingConfigSchema,MigrationStatusSchema:()=>MigrationStatusSchema,MemoryConfigSchema:()=>MemoryConfigSchema,LeanTurboConfigSchema:()=>LeanTurboConfigSchema,EvidenceVerdictSchema:()=>EvidenceVerdictSchema,EvidenceTypeSchema:()=>EvidenceTypeSchema,EvidenceSchema:()=>EvidenceSchema,EvidenceBundleSchema:()=>EvidenceBundleSchema,EVIDENCE_MAX_TASK_BYTES:()=>EVIDENCE_MAX_TASK_BYTES,EVIDENCE_MAX_PATCH_BYTES:()=>EVIDENCE_MAX_PATCH_BYTES,EVIDENCE_MAX_JSON_BYTES:()=>EVIDENCE_MAX_JSON_BYTES,DiffEvidenceSchema:()=>DiffEvidenceSchema,DeltaSpecSchema:()=>DeltaSpecSchema,DEFAULT_MODELS:()=>DEFAULT_MODELS,BaseEvidenceSchema:()=>BaseEvidenceSchema,AutomationModeSchema:()=>AutomationModeSchema,AutomationConfigSchema:()=>AutomationConfigSchema,AutomationCapabilitiesSchema:()=>AutomationCapabilitiesSchema,ApprovalEvidenceSchema:()=>ApprovalEvidenceSchema,ApplyPatchConfigSchema:()=>ApplyPatchConfigSchema,AgentOverrideConfigSchema:()=>AgentOverrideConfigSchema,ALL_SUBAGENT_NAMES:()=>ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES:()=>ALL_AGENT_NAMES});var _internals2;var init_config=__esm(()=>{init_constants();init_evidence_schema();init_loader();init_loader();init_plan_schema();init_schema();init_spec_schema();init_worktree_isolation_config();_internals2={loadPluginConfigWithMeta}});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
159
159
 
160
160
  ${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path2 from"node:path";function bundledProjectSkillFileReference(slug){return`file:${BUNDLED_PROJECT_SKILL_ROOT}/${slug}/SKILL.md`}function describeBundledSkillSyncFailure(err){return`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${err instanceof Error?err.message:String(err)}`}async function isSymbolicLinkAsync(p){try{return(await fsp.lstat(p)).isSymbolicLink()}catch{return!1}}async function ensureNotSymlinkedDirectoryAsync(p){try{let stat3=await fsp.lstat(p);return stat3.isDirectory()&&!stat3.isSymbolicLink()}catch(err){return err.code==="ENOENT"}}async function pathExistsAsync(p){try{return await fsp.access(p),!0}catch{return!1}}async function collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeDir=""){let currentSource=path2.join(sourceDir,relativeDir),entries=await fsp.readdir(currentSource,{withFileTypes:!0});entries.sort((a,b)=>a.name.localeCompare(b.name));let files=[];for(let entry of entries){let relativeEntry=path2.join(relativeDir,entry.name),sourcePath=path2.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))throw Error("refusing to copy symlinked bundled skill entry");if(entry.isDirectory()){files.push(...await collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeEntry));continue}if(!entry.isFile())continue;let stat3=await fsp.stat(sourcePath),nextFiles=state.files+1,nextBytes=state.bytes+stat3.size;if(nextFiles>MAX_SKILL_FILES||nextBytes>MAX_SKILL_BYTES)throw Error("bundled skill package exceeds copy bounds");state.files=nextFiles,state.bytes=nextBytes,files.push({relativePath:relativeEntry})}return files}async function ensureContainedDirectoryAsync(rootDir,directory){let safeRoot=path2.resolve(rootDir),safeDirectory=path2.resolve(directory),relative2=path2.relative(safeRoot,safeDirectory);if(relative2.startsWith("..")||path2.isAbsolute(relative2))throw Error("bundled skill destination escaped its private root");try{let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;await fsp.mkdir(safeRoot,{recursive:!0});let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}let current=safeRoot;for(let segment of relative2.split(path2.sep).filter(Boolean)){current=path2.join(current,segment);try{let stat3=await fsp.lstat(current);if(stat3.isSymbolicLink()||!stat3.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;try{await fsp.mkdir(current)}catch(mkdirErr){if(mkdirErr.code!=="EEXIST")throw mkdirErr}let stat3=await fsp.lstat(current);if(stat3.isSymbolicLink()||!stat3.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}}}async function rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles=[]){let safeDestDir=path2.resolve(destDir),dirs=new Set;for(let copiedFile of copiedFiles){let resolvedFile=path2.resolve(copiedFile),relative2=path2.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.rm(resolvedFile,{force:!0})}catch{}dirs.add(path2.dirname(resolvedFile))}for(let overwritten of overwrittenFiles.reverse()){let resolvedFile=path2.resolve(overwritten.path),relative2=path2.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.writeFile(resolvedFile,overwritten.contents)}catch{}}for(let dir of[...dirs].sort((a,b)=>b.length-a.length)){let relative2=path2.relative(safeDestDir,path2.resolve(dir));if(relative2.startsWith("..")||path2.isAbsolute(relative2))continue;try{await fsp.rmdir(dir)}catch{}}}async function copyFileAtomicAsync(sourcePath,destPath){let tempPath=path2.join(path2.dirname(destPath),`.${path2.basename(destPath)}.tmp.${randomUUID()}`);try{await fsp.copyFile(sourcePath,tempPath),await fsp.rename(tempPath,destPath)}catch(err){try{await fsp.rm(tempPath,{force:!0})}catch{}throw err}}async function copyBundledDirectoryBoundedAsync(sourceDir,destDir){let files=await collectBundledSkillFilesBoundedAsync(sourceDir,{files:0,bytes:0}),copiedFiles=[],overwrittenFiles=[];try{for(let file2 of files){let sourcePath=path2.join(sourceDir,file2.relativePath),destPath=path2.join(destDir,file2.relativePath);if(await ensureContainedDirectoryAsync(destDir,path2.dirname(destPath)),await pathExistsAsync(destPath)){if(await isSymbolicLinkAsync(destPath))throw Error("refusing to overwrite symlinked bundled skill file");let[sourceContents,destContents]=await Promise.all([fsp.readFile(sourcePath),fsp.readFile(destPath)]);if(sourceContents.equals(destContents))continue;overwrittenFiles.push({path:destPath,contents:destContents}),await copyFileAtomicAsync(sourcePath,destPath)}else await copyFileAtomicAsync(sourcePath,destPath),copiedFiles.push(destPath)}}catch(err){throw await rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles),err}}async function performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet){try{let sourceRoot=path2.join(packageRoot,".opencode","skills"),swarmDir=path2.join(projectDirectory,".swarm"),skillsDir=path2.join(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT);if(!await ensureNotSymlinkedDirectoryAsync(sourceRoot))throw Error("refusing to copy symlinked bundled skill source root");if(!await ensureNotSymlinkedDirectoryAsync(swarmDir))return;if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;for(let slug of BUNDLED_PROJECT_SKILLS){let sourceDir=path2.join(sourceRoot,slug),sourceSkill=path2.join(sourceDir,"SKILL.md"),destDir=path2.join(skillsDir,slug);if(!await pathExistsAsync(sourceSkill))continue;if(!await ensureNotSymlinkedDirectoryAsync(sourceDir))throw Error("refusing to copy symlinked bundled skill directory");if(!await ensureNotSymlinkedDirectoryAsync(destDir))continue;await copyBundledDirectoryBoundedAsync(sourceDir,destDir),log("synchronized bundled skill",{slug:bundledProjectSkillFileReference(slug)})}}catch(err){let failureMsg=describeBundledSkillSyncFailure(err);if(quiet)advisoryWarn(failureMsg);else console.warn(failureMsg)}}async function syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){let syncKey=path2.resolve(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT),existing=inFlightSyncs.get(syncKey);if(existing)return existing;if(inFlightSyncs.size>=MAX_IN_FLIGHT_SYNCS){log("skipping bundled skill sync because the in-flight limit was reached",{limit:MAX_IN_FLIGHT_SYNCS});return}let syncPromise=performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet).finally(()=>{if(inFlightSyncs.get(syncKey)===syncPromise)inFlightSyncs.delete(syncKey)});return inFlightSyncs.set(syncKey,syncPromise),syncPromise}var BUNDLED_PROJECT_SKILLS,BUNDLED_PROJECT_SKILL_ROOT=".swarm/bundled-skills",MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000,MAX_IN_FLIGHT_SYNCS=64,inFlightSyncs;var init_bundled_skills=__esm(()=>{init_warning_buffer();init_logger();BUNDLED_PROJECT_SKILLS=["brainstorm","specify","clarify-spec","resume","clarify","discover","consult","pre-phase-briefing","council","deep-dive","deep-research","codebase-review-swarm","swarm-implement","design-docs","swarm-pr-review","swarm","swarm-pr-feedback","swarm-pr-subscribe","swarm-ci-monitor","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr","ci-failure-batching","gate-attribution","merge-queue-readiness","skill-edit-validation","worktree-retry-cleanup","test-file-split","fork-pr-operations","parallel-work-check","ci-fix-monitor","issue-tracer"];inFlightSyncs=new Map});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger()});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path3 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path3.dirname(filePath),tempName=`.${path3.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path3.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve2)=>setTimeout(resolve2,ms))}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill();return}if(process.platform==="win32"){try{nodeSpawnSync("taskkill",["/PID",String(pid),"/T","/F"])}catch{directKill()}return}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill()}function streamFromNode(pipe2){let collected=new Promise((resolve2)=>{if(!pipe2){resolve2(Buffer.alloc(0));return}let chunks=[];pipe2.on("data",(chunk)=>{chunks.push(typeof chunk==="string"?Buffer.from(chunk):chunk)}),pipe2.on("end",()=>resolve2(Buffer.concat(chunks))),pipe2.on("error",()=>resolve2(Buffer.concat(chunks)))}),toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller){controller.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller){pipe2.on("data",(chunk)=>{controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller.close()),pipe2.on("error",(err)=>controller.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})};return{async text(){return(await collected).toString("utf-8")},async bytes(){let b=await collected;return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){return toWebReadable().getReader()}}}function mapStdio(v){return v??"pipe"}function streamFromBun(stream){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller){controller.close()}}).getReader()}};let candidate=stream,collect=async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[];for(;;){let{done,value}=await reader.read();if(done)break;if(value)chunks.push(value)}let total=chunks.reduce((acc,c)=>acc+c.byteLength,0),out=new Uint8Array(total),off=0;for(let c of chunks)out.set(c,off),off+=c.byteLength;return out},text=typeof candidate.text==="function"?()=>candidate.text():async()=>new TextDecoder().decode(await collect()),bytes=typeof candidate.bytes==="function"?()=>candidate.bytes():collect,getReader=typeof candidate.getReader==="function"?()=>candidate.getReader():()=>new ReadableStream({start(controller){controller.close()}}).getReader();return{text,bytes,getReader}}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function bunSpawn(cmd,options){let bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0)spawnOpts.killSignal="SIGKILL";let proc2=bun.spawn(cmd,spawnOpts);return{stdout:streamFromBun(proc2.stdout),stderr:streamFromBun(proc2.stderr),exited:proc2.exited,get exitCode(){return proc2.exitCode},kill(sig){if(options?.killProcessTree)killProcessTreeImpl(proc2.pid,sig,()=>proc2.kill(sig),!1);else proc2.kill(sig)}}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]}),killChild=(signal)=>{if(detached)killProcessTreeImpl(proc.pid,signal,()=>proc.kill(signal),!0);else proc.kill(signal)},timeoutHandle,exited=new Promise((resolve2)=>{if(proc.on("exit",(code)=>resolve2(code??0)),proc.on("error",()=>resolve2(1)),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL")}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle)});return{stdout:streamFromNode(proc.stdout),stderr:streamFromNode(proc.stderr),exited,get exitCode(){return proc.exitCode},kill(signal){killChild(signal)}}}function bunSpawnSync(cmd,options){let bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts=mergedEnv2!==void 0?{...options,env:mergedEnv2}:options;return bun.spawnSync(cmd,spawnOpts)}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0}),stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0;var init_bun_compat=()=>{};import*as fsSync2 from"node:fs";import*as fs2 from"node:fs/promises";import*as path4 from"node:path";function sameStamp(a,b){return a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs&&a.size===b.size}async function getStamp(filePath){try{let stat5=await fs2.stat(filePath);if(!stat5.isFile())return null;return{mtimeMs:stat5.mtimeMs,ctimeMs:stat5.ctimeMs,size:stat5.size}}catch{return stats.statFailureCount++,null}}function getStampSync(filePath){try{let stat5=fsSync2.statSync(filePath);if(!stat5.isFile())return null;return{mtimeMs:stat5.mtimeMs,ctimeMs:stat5.ctimeMs,size:stat5.size}}catch{return stats.statFailureCount++,null}}function canStoreRead(before,after){return after!==null&&sameStamp(before,after)}function setBounded(cache,key,value,cacheKind){cache.set(key,value);while(cache.size>MAX_CACHE_ENTRIES){let oldest=cache.keys().next().value;if(oldest===void 0)break;if(cache.delete(oldest),stats.evictionCount++,cacheKind==="text")stats.textEvictionCount++;else stats.parsedEvictionCount++}stats.textEntryCount=textCache.size,stats.parsedEntryCount=parsedCache.size}function cloneCachedValue(value){if(value===null||typeof value!=="object")return value;if(typeof structuredClone==="function")return structuredClone(value);return stats.cloneFallbackCount++,JSON.parse(JSON.stringify(value))}function readCachedTextFileSync(filePath,directRead){let cacheKey=path4.resolve(filePath),stamp=getStampSync(cacheKey);if(!stamp)return stats.textReadCount++,directRead();let cached2=textCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.textCacheHitCount++,cached2.value;stats.textCacheMissCount++,stats.textReadCount++;let value=directRead(),afterReadStamp=getStampSync(cacheKey);if(value!==null&&canStoreRead(stamp,afterReadStamp))setBounded(textCache,cacheKey,{...afterReadStamp,value},"text");return value}async function readCachedTextFile(filePath,directRead){let cacheKey=path4.resolve(filePath),stamp=await getStamp(cacheKey);if(!stamp)return stats.textReadCount++,directRead();let cached2=textCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.textCacheHitCount++,cached2.value;stats.textCacheMissCount++,stats.textReadCount++;let value=await directRead(),afterReadStamp=await getStamp(cacheKey);if(value!==null&&canStoreRead(stamp,afterReadStamp))setBounded(textCache,cacheKey,{...afterReadStamp,value},"text");return value}function readCachedParsedFileSync(filePath,namespace,readText,parse5){let resolvedPath=path4.resolve(filePath),cacheKey=`${resolvedPath}\x00${namespace}`,stamp=getStampSync(resolvedPath);if(!stamp){stats.parsedReadCount++;let content2=readText();if(content2===null)return null;return stats.parseCount++,parse5(content2)}let cached2=parsedCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.parsedCacheHitCount++,cloneCachedValue(cached2.value);stats.parsedCacheMissCount++,stats.parsedReadCount++;let content=readText();if(content===null)return null;stats.parseCount++;let value=parse5(content),afterReadStamp=getStampSync(resolvedPath);if(canStoreRead(stamp,afterReadStamp))setBounded(parsedCache,cacheKey,{...afterReadStamp,value},"parsed");return cloneCachedValue(value)}async function readCachedParsedFile(filePath,namespace,readText,parse5){let resolvedPath=path4.resolve(filePath),cacheKey=`${resolvedPath}\x00${namespace}`,stamp=await getStamp(resolvedPath);if(!stamp){stats.parsedReadCount++;let content2=await readText();if(content2===null)return null;return stats.parseCount++,parse5(content2)}let cached2=parsedCache.get(cacheKey);if(cached2&&sameStamp(cached2,stamp))return stats.parsedCacheHitCount++,cloneCachedValue(cached2.value);stats.parsedCacheMissCount++,stats.parsedReadCount++;let content=await readText();if(content===null)return null;stats.parseCount++;let value=parse5(content),afterReadStamp=await getStamp(resolvedPath);if(canStoreRead(stamp,afterReadStamp))setBounded(parsedCache,cacheKey,{...afterReadStamp,value},"parsed");return cloneCachedValue(value)}function invalidateCachedArtifact(filePath){let resolvedPath=path4.resolve(filePath);textCache.delete(resolvedPath);let prefix=`${resolvedPath}\x00`;for(let key of parsedCache.keys())if(key.startsWith(prefix))parsedCache.delete(key)}var MAX_CACHE_ENTRIES=128,textCache,parsedCache,stats;var init_swarm_artifact_cache=__esm(()=>{textCache=new Map,parsedCache=new Map,stats={textReadCount:0,textCacheHitCount:0,textCacheMissCount:0,parsedReadCount:0,parseCount:0,parsedCacheHitCount:0,parsedCacheMissCount:0,statFailureCount:0,evictionCount:0,textEvictionCount:0,parsedEvictionCount:0,cloneFallbackCount:0,textEntryCount:0,parsedEntryCount:0}});import*as fs3 from"node:fs";import*as path5 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
161
161
  → ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};for(let fn2 of fns)if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");return async(input,output)=>{for(let fn2 of fns)await _internals3.safeHook(fn2)(input,output)}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path5.normalize(path5.resolve(directory,".swarm")),resolved=path5.normalize(path5.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path5.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path5.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs3.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs3.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs3.existsSync(existingPath)){let parent=path5.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs3.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path5.normalize(candidate),normalizedBase=path5.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path5.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path5.sep}`)}async function readSwarmFileAsync(directory,filename,cache){if(cache!==void 0){let key=`${directory}::${filename}`,cached2=cache.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename);return cache.set(key,promise2),promise2}let maxAttempts=5,retryDelayMs=10;for(let attempt=0;attempt<maxAttempts;attempt++)try{let resolvedPath=_internals3.validateSwarmPath(directory,filename);return await _internals3.readCachedTextFile(resolvedPath,async()=>{return await bunFile(resolvedPath).text()})}catch(err){if(err?.code!=="ENOENT"||attempt===maxAttempts-1)return null;await new Promise((resolve4)=>setTimeout(resolve4,retryDelayMs))}return null}function estimateTokens(text){if(!text)return 0;return Math.ceil(text.length*0.33)}var _internals3;var init_utils2=__esm(()=>{init_utils();init_bun_compat();init_swarm_artifact_cache();_internals3={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});import{createHash}from"node:crypto";import{existsSync as existsSync3,mkdirSync,readFileSync as readFileSync2,renameSync,unlinkSync,writeFileSync}from"node:fs";import*as path6 from"node:path";function storeLaneOutput(directory,input,now=Date.now){let bytes=Buffer.byteLength(input.text,"utf-8"),digest=digestText(input.text);if(bytes>MAX_LANE_OUTPUT_STORED_BYTES)return{digest,chars:input.text.length,bytes,degraded:!0,error:`lane output exceeds ${MAX_LANE_OUTPUT_STORED_BYTES} byte storage limit`};let batchDigest=digestText(input.batchId),laneDigest=digestText(input.laneId),ref=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`,relPath=laneOutputRelativePath(ref),absPath=validateSwarmPath(directory,relPath),timestamp=new Date(now()).toISOString();try{if(existsSync3(absPath)){let existing=LaneOutputArtifactSchema.safeParse(JSON.parse(readFileSync2(absPath,"utf-8")));if(existing.success&&hasValidArtifactIntegrity(existing.data,ref)&&artifactIdentityMatchesInput(existing.data,input))return{ref,digest,chars:existing.data.chars,bytes:existing.data.bytes,degraded:!1};if(existing.success&&hasValidArtifactIntegrity(existing.data,ref))return{digest,chars:input.text.length,bytes,degraded:!0,error:"lane output ref collision has incompatible agent/session provenance"}}let artifact={schemaVersion:LANE_OUTPUT_SCHEMA_VERSION,ref,batchId:input.batchId,laneId:input.laneId,agent:input.agent,role:input.role,...input.sessionId?{sessionId:input.sessionId}:{},...input.parentSessionId?{parentSessionId:input.parentSessionId}:{},...input.mode?{mode:input.mode}:{},...input.workflowLane?{workflowLane:input.workflowLane}:{},...input.prHeadSha?{prHeadSha:input.prHeadSha}:{},...input.gitHead?{gitHead:input.gitHead}:{},...input.revisionDigest?{revisionDigest:input.revisionDigest}:{},...input.scope?{scope:input.scope}:{},source:input.source,text:input.text,chars:input.text.length,bytes,digest,...input.messageCount!==void 0?{messageCount:input.messageCount}:{},...input.transcriptIncomplete!==void 0?{transcriptIncomplete:input.transcriptIncomplete}:{},createdAt:timestamp,updatedAt:timestamp};return writeAtomicJson(absPath,artifact),{ref,digest,chars:artifact.chars,bytes:artifact.bytes,degraded:!1}}catch(error49){return{digest,chars:input.text.length,bytes,degraded:!0,error:error49 instanceof Error?error49.message:"failed to store lane output artifact"}}}function readLaneOutput(directory,ref){if(!REF_RE.test(ref))return null;let absPath=validateSwarmPath(directory,laneOutputRelativePath(ref));if(!existsSync3(absPath))return null;let parsed;try{parsed=LaneOutputArtifactSchema.safeParse(JSON.parse(readFileSync2(absPath,"utf-8")))}catch{return null}if(!parsed.success||!hasValidArtifactIntegrity(parsed.data,ref))return null;return{artifact:parsed.data}}function buildLaneOutputPreview(args2){let{text,ref,degraded,maxChars}=args2;if(!(text.length>maxChars)&&!degraded)return{output:text,output_chars:text.length,output_truncated:!1};let marker=buildPreviewMarker({omittedChars:Math.max(0,text.length-maxChars),ref,degraded:degraded===!0});if(text.length<=maxChars&&degraded)return{output:`${text}${marker}`,output_chars:text.length,output_truncated:!1};let budget=Math.max(0,maxChars-marker.length),headChars=Math.ceil(budget/2),tailChars=Math.floor(budget/2),head=text.slice(0,headChars),tail=tailChars>0?text.slice(text.length-tailChars):"";return{output:`${head}${marker}${tail}`,output_chars:text.length,output_truncated:!0}}function paginateLaneOutput(text,offset,limit){let lines=text.length===0?[]:text.split(`
@@ -530,7 +530,7 @@ ${request.task??""}`,terms=Array.from(extractFtsTerms(text)).slice(0,40);if(term
530
530
  ALTER TABLE memory_recall_usage ADD COLUMN unit_id TEXT;
531
531
  CREATE INDEX IF NOT EXISTS idx_memory_recall_usage_unit_id
532
532
  ON memory_recall_usage(unit_id);
533
- `}];FTS_STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","goal","how","in","into","is","it","of","on","or","role","task","that","the","this","to","user","what","when","with"])});import{realpathSync as realpathSync7}from"node:fs";import*as path39 from"node:path";function markAsPooled(provider){let originalClose=provider.close;if(provider.close=()=>{return releaseProvider(provider),Promise.resolve()},provider[POOLED_MARKER]=!0,originalClose)provider[REAL_CLOSE]=originalClose}function callRealClose(provider){let realClose=provider[REAL_CLOSE];try{realClose?.call(provider)}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[provider-pool] real close failed: ${msg}`)}}function isPooledProvider(provider){return POOLED_MARKER in provider}function getOrCreateProviderForRoot(root,config2){let key=resolvePoolKeyForRoot(root),rootGeneration=root.kind==="cohort"?root.generation:0,existing=entriesByKey.get(key);if(existing){if((existing.generation??0)===rootGeneration)return moveToHead(existing),existing.refCount++,existing.provider;evictEntryByKey(key)}for(let deferred of deferredEntries)if(deferred.key===key){if((deferred.generation??0)===rootGeneration){if(deferredEntries.delete(deferred),entriesByKey.size>=MAX_POOL_SIZE)evictLru();if(deferred.prev=null,deferred.next=head,head)head.prev=deferred;if(head=deferred,!tail)tail=deferred;return entriesByKey.set(key,deferred),deferred.refCount++,deferred.provider}deferredEntries.delete(deferred),callRealClose(deferred.provider);break}let directory=root.directory,cohortRoot=root.kind==="cohort"?root.cohortRoot:null,provider=new SQLiteMemoryProvider(directory,config2,cohortRoot);if(markAsPooled(provider),entriesByKey.size>=MAX_POOL_SIZE)evictLru();let entry={key,provider,refCount:1,prev:null,next:head};if(entry.generation=rootGeneration,head)head.prev=entry;if(head=entry,!tail)tail=entry;return entriesByKey.set(key,entry),provider}function resolvePoolKeyForRoot(root){if(root.kind==="cohort")try{return`cohort:${realpathSync7(root.cohortRoot)}`}catch{return`cohort:${path39.resolve(root.cohortRoot)}`}return resolvePoolKey(root.directory)}function evictEntryByKey(key){let entry=entriesByKey.get(key);if(!entry)return;if(entry.refCount>0){deferredEntries.add(entry),unlinkEntry(entry),entriesByKey.delete(key);return}unlinkEntry(entry),entriesByKey.delete(key),callRealClose(entry.provider)}function evictAndCloseForRoot(root){let key=resolvePoolKeyForRoot(root);evictEntryByKey(key)}function releaseProvider(provider){for(let[_key,entry]of entriesByKey)if(entry.provider===provider){entry.refCount=Math.max(0,entry.refCount-1);return}for(let entry of deferredEntries)if(entry.provider===provider){if(entry.refCount--,entry.refCount<=0)deferredEntries.delete(entry),callRealClose(provider);return}if(isPooledProvider(provider))callRealClose(provider)}function evictLru(){if(!tail)return;let evicted=tail;if(entriesByKey.delete(evicted.key),unlinkEntry(evicted),evicted.refCount>0)deferredEntries.add(evicted);else callRealClose(evicted.provider)}function moveToHead(entry){if(head===entry)return;if(unlinkEntry(entry),entry.prev=null,entry.next=head,head)head.prev=entry;if(head=entry,!tail)tail=entry}function unlinkEntry(entry){if(entry.prev)entry.prev.next=entry.next;if(entry.next)entry.next.prev=entry.prev;if(head===entry)head=entry.next;if(tail===entry)tail=entry.prev}function resolvePoolKey(directory){let rawKey=path39.resolve(directory);try{let canonical=realpathSync7(directory);if(resolvedKeyCache.delete(rawKey),resolvedKeyCache.set(rawKey,canonical),resolvedKeyCache.size>MAX_POOL_SIZE){let oldest=resolvedKeyCache.keys().next().value;if(oldest!==void 0)resolvedKeyCache.delete(oldest)}return canonical}catch{return resolvedKeyCache.get(rawKey)??rawKey}}function evictAndClose(directory){let key=resolvePoolKey(directory),active=entriesByKey.get(key);if(active)entriesByKey.delete(key),unlinkEntry(active),callRealClose(active.provider);for(let deferred of[...deferredEntries])if(deferred.key===key)deferredEntries.delete(deferred),callRealClose(deferred.provider)}var MAX_POOL_SIZE=16,POOLED_MARKER,REAL_CLOSE,head=null,tail=null,entriesByKey,deferredEntries,resolvedKeyCache;var init_provider_pool=__esm(()=>{init_sqlite_provider();POOLED_MARKER=Symbol("opencode-swarm-pooled-provider"),REAL_CLOSE=Symbol("opencode-swarm-real-close"),entriesByKey=new Map,deferredEntries=new Set,resolvedKeyCache=new Map});var exports_knowledge_link={};__export(exports_knowledge_link,{writeLinkPointer:()=>writeLinkPointer,sanitizeLinkId:()=>sanitizeLinkId,resolveLinkDir:()=>resolveLinkDir,resolveLinkBaseDir:()=>resolveLinkBaseDir,resolveKnowledgeStoreDir:()=>resolveKnowledgeStoreDir,removeLinkPointer:()=>removeLinkPointer,readLinkPointer:()=>readLinkPointer,isLinked:()=>isLinked,invalidateKnowledgeStoreDirCache:()=>invalidateKnowledgeStoreDirCache,getLinkedLocalKnowledgeStatus:()=>getLinkedLocalKnowledgeStatus,_internals:()=>_internals26,LINK_POINTER_FILENAME:()=>LINK_POINTER_FILENAME});import{existsSync as existsSync18,lstatSync as lstatSync6,mkdirSync as mkdirSync17,readFileSync as readFileSync17,rmSync as rmSync3,statSync as statSync11}from"node:fs";import*as os12 from"node:os";import*as path40 from"node:path";function resolveDataDir(){let platform=process.platform,home=process.env.HOME||os12.homedir();if(platform==="win32")return path40.join(process.env.LOCALAPPDATA||path40.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")return path40.join(home,"Library","Application Support","opencode-swarm");return path40.join(process.env.XDG_DATA_HOME||path40.join(home,".local","share"),"opencode-swarm")}function resolveLinkBaseDir(){return path40.join(resolveDataDir(),"links")}function resolveLinkDir(linkId){return path40.join(resolveLinkBaseDir(),linkId)}function sanitizeLinkId(name){if(typeof name!=="string")return null;let cleaned=name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,MAX_LINK_ID_LENGTH).replace(/[-.]+$/g,"");if(cleaned.length===0)return null;let base=cleaned.split(".")[0];if(WINDOWS_RESERVED_NAMES.has(base))return null;return cleaned}function resolveLinkPointerPath(directory){return path40.join(directory,".swarm",LINK_POINTER_FILENAME)}function readLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);if(!existsSync18(pointerPath))return null;try{let raw=JSON.parse(readFileSync17(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:obj.version===2?2:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),source:obj.source==="auto"?"auto":"manual",cohortId:typeof obj.cohortId==="string"?obj.cohortId:void 0,identitySource:obj.identitySource==="remote"||obj.identitySource==="git-common-dir"||obj.identitySource==="path"?obj.identitySource:void 0,degraded:typeof obj.degraded==="boolean"?obj.degraded:void 0,configFingerprint:typeof obj.configFingerprint==="string"?obj.configFingerprint:void 0,generation:typeof obj.generation==="number"?obj.generation:void 0}}catch{return null}}function getLinkedLocalKnowledgeStatus(directory){let localKnowledgePath=path40.join(directory,".swarm","knowledge.jsonl"),pointer=readLinkPointer(directory);if(!pointer)return{linked:!1,orphaned:!1,localKnowledgePath,resolvedKnowledgePath:localKnowledgePath,reason:"not_linked"};let resolvedKnowledgePath=path40.join(path40.resolve(resolveLinkDir(pointer.linkId)),"knowledge.jsonl");if(!existsSync18(localKnowledgePath))return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"};try{if(lstatSync6(localKnowledgePath).isSymbolicLink())return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_symlink"}}catch{return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"}}return{linked:!0,orphaned:!0,localKnowledgePath,resolvedKnowledgePath,reason:"local_regular_file"}}async function writeLinkPointer(directory,pointer){let swarmDir=path40.join(directory,".swarm");mkdirSync17(swarmDir,{recursive:!0});let pointerPath=resolveLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateKnowledgeStoreDirCache(directory)}async function removeLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);try{rmSync3(pointerPath,{force:!0})}finally{invalidateKnowledgeStoreDirCache(directory)}}function pointerStatFingerprint(directory){let pointerPath=resolveLinkPointerPath(directory);try{let st=statSync11(pointerPath);return`${st.mtimeMs}:${st.ctimeMs}:${st.size}`}catch{return null}}function resolveKnowledgeStoreDir(directory){let localSwarm=path40.join(directory,".swarm"),now=Date.now(),cached2=_resolutionCache.get(directory),currentStat=pointerStatFingerprint(directory);if(cached2&&now<cached2.expires&&cached2.pointerStat===currentStat)return cached2.linkDir??localSwarm;let linkDir=null;try{let pointer=readLinkPointer(directory);if(pointer){linkDir=path40.resolve(resolveLinkDir(pointer.linkId));let orphanStatus=getLinkedLocalKnowledgeStatus(directory);if(orphanStatus.orphaned)warn("[knowledge-link] local knowledge file is orphaned by link store",{localKnowledgePath:orphanStatus.localKnowledgePath,resolvedKnowledgePath:orphanStatus.resolvedKnowledgePath})}}catch{linkDir=null}if(!_resolutionCache.has(directory)&&_resolutionCache.size>=MAX_CACHE_ENTRIES2){let oldest=_resolutionCache.keys().next().value;if(oldest!==void 0)_resolutionCache.delete(oldest)}return _resolutionCache.set(directory,{linkDir,expires:now+CACHE_TTL_MS,pointerStat:currentStat}),linkDir??localSwarm}function invalidateKnowledgeStoreDirCache(directory){if(directory===void 0){_resolutionCache.clear();return}_resolutionCache.delete(directory)}function isLinked(directory){return readLinkPointer(directory)!==null}var LINK_POINTER_FILENAME="link.json",MAX_LINK_ID_LENGTH=64,WINDOWS_RESERVED_NAMES,CACHE_TTL_MS=2000,MAX_CACHE_ENTRIES2=500,_resolutionCache,_internals26;var init_knowledge_link=__esm(()=>{init_task_file();init_logger();WINDOWS_RESERVED_NAMES=new Set(["con","prn","aux","nul","com0","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt0","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);_resolutionCache=new Map;_internals26={resolveKnowledgeStoreDir,readLinkPointer,writeLinkPointer,removeLinkPointer,getLinkedLocalKnowledgeStatus,invalidateKnowledgeStoreDirCache,resolveLinkDir,resolveLinkBaseDir,sanitizeLinkId}});import{existsSync as existsSync19,mkdirSync as mkdirSync18,readFileSync as readFileSync18,rmSync as rmSync4,statSync as statSync12}from"node:fs";import*as path41 from"node:path";function resolveMemoryLinkPointerPath(directory){return path41.join(directory,".swarm",MEMORY_LINK_POINTER_FILENAME)}function readMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);if(!existsSync19(pointerPath))return null;try{let raw=JSON.parse(readFileSync18(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:obj.version===2?2:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),cohortId:typeof obj.cohortId==="string"?obj.cohortId:void 0,identitySource:obj.identitySource==="remote"||obj.identitySource==="git-common-dir"||obj.identitySource==="path"?obj.identitySource:void 0,degraded:typeof obj.degraded==="boolean"?obj.degraded:void 0,configFingerprint:typeof obj.configFingerprint==="string"?obj.configFingerprint:void 0,generation:typeof obj.generation==="number"?obj.generation:void 0}}catch{return null}}async function writeMemoryLinkPointer(directory,pointer){let swarmDir=path41.join(directory,".swarm");mkdirSync18(swarmDir,{recursive:!0});let pointerPath=resolveMemoryLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateMemoryStoreDirCache(directory)}async function removeMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{rmSync4(pointerPath,{force:!0})}finally{invalidateMemoryStoreDirCache(directory)}}function pointerStatFingerprint2(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{let st=statSync12(pointerPath);return`${st.mtimeMs}:${st.ctimeMs}:${st.size}`}catch{return null}}function resolveMemoryStoreDir(directory){let localSwarm=path41.join(directory,".swarm"),now=Date.now(),cached2=_resolutionCache2.get(directory),currentStat=pointerStatFingerprint2(directory);if(cached2&&now<cached2.expires&&cached2.pointerStat===currentStat)return cached2.linkDir??localSwarm;let linkDir=null;try{let pointer=readMemoryLinkPointer(directory);if(pointer)linkDir=path41.resolve(resolveLinkDir(pointer.linkId))}catch{linkDir=null}if(!_resolutionCache2.has(directory)&&_resolutionCache2.size>=MAX_CACHE_ENTRIES3){let oldest=_resolutionCache2.keys().next().value;if(oldest!==void 0)_resolutionCache2.delete(oldest)}return _resolutionCache2.set(directory,{linkDir,expires:now+CACHE_TTL_MS2,pointerStat:currentStat}),linkDir??localSwarm}function invalidateMemoryStoreDirCache(directory){if(directory===void 0){_resolutionCache2.clear();return}_resolutionCache2.delete(directory)}var MEMORY_LINK_POINTER_FILENAME="memory-link.json",CACHE_TTL_MS2=2000,MAX_CACHE_ENTRIES3=500,_resolutionCache2;var init_memory_link=__esm(()=>{init_task_file();init_knowledge_link();init_logger();_resolutionCache2=new Map});import*as path42 from"node:path";function resolveVettedMemoryRoot(directory,config2){if(config2?.link?.enabled!==!0){let existingPointer=readMemoryLinkPointer(directory);if(existingPointer)warn(`[memory-link] memory.link.enabled is false but a cohort pointer exists (linkId=${existingPointer.linkId}). Cohort memory is unreachable — run \`/swarm memory link\` or remove the pointer with \`/swarm memory unlink\`.`,{directory,linkId:existingPointer.linkId});return wrapLocalRoot(directory)}let pointer=readMemoryLinkPointer(directory);if(!pointer)return wrapLocalRoot(directory);let sharedDir=resolveMemoryStoreDir(directory),localSwarm=path42.join(directory,".swarm");if(sharedDir===localSwarm)return wrapLocalRoot(directory);return{kind:"cohort",cohortRoot:path42.join(sharedDir,"memory"),cohortId:pointer.cohortId??pointer.linkId,generation:pointer.generation??0,linkId:pointer.linkId,directory}}function wrapLocalRoot(directory){return log("[memory] wrapping raw directory as local vetted root — cohort sharing inactive for this caller",{directory}),{kind:"local",root:path42.join(directory,".swarm"),directory}}function isCohortRoot(root){return root.kind==="cohort"}function rootStoragePath(root){return root.kind==="cohort"?root.cohortRoot:path42.join(root.root,"memory")}var init_storage_root=__esm(()=>{init_logger();init_memory_link()});import{createHash as createHash15}from"node:crypto";import{existsSync as existsSync20,readFileSync as readFileSync19}from"node:fs";import*as path43 from"node:path";class MemoryGateway{context;config;provider;vettedRoot;now;disposed=!1;constructor(context,options={}){this.context=context;this.config=resolveMemoryConfig(options.config??DEFAULT_MEMORY_CONFIG),this.vettedRoot=resolveVettedMemoryRoot(context.directory,this.config),this.provider=options.provider??createConfiguredMemoryProviderForRoot(this.vettedRoot,this.config),this.now=options.now??(()=>new Date)}isEnabled(){return this.config.enabled}async dispose(){if(this.disposed)return;this.disposed=!0,await this.provider.close?.()}deriveAllowedScopes(){let resolvedRoot=path43.resolve(this.context.directory),repoId=createStableId(readGitRemoteUrl(resolvedRoot)??path43.basename(resolvedRoot)),scopes=[{type:"workspace",workspaceId:createStableId(path43.dirname(resolvedRoot))},{type:"repository",repoId,repoRoot:resolvedRoot}];if(isCohortRoot(this.vettedRoot))scopes.push({type:"cohort",cohortId:this.vettedRoot.cohortId});if(this.context.runId||this.context.sessionID)scopes.push({type:"run",runId:this.context.runId??this.context.sessionID});if(this.context.agentId||this.context.agentRole)scopes.push({type:"agent",agentId:this.context.agentId??this.context.agentRole,runId:this.context.runId??this.context.sessionID});return scopes}async recall(input){this.assertEnabled();let query=normalizeMemoryText(input.query);if(query.length<3)throw new MemoryValidationError("query must be at least 3 characters");let maxItems=clampInt(input.maxItems??this.config.recall.defaultMaxItems,1,20),tokenBudget=clampInt(input.tokenBudget??this.config.recall.defaultTokenBudget,100,5000),generatedAt=this.now().toISOString(),allowedScopes=this.deriveAllowedScopes(),scopes=input.scopes?validateRequestedScopes(input.scopes,allowedScopes):allowedScopes,request={query,task:input.task,agentRole:this.context.agentRole,mode:input.mode??"manual",scopes,kinds:input.kinds,maxItems,tokenBudget,minScore:input.minScore??this.config.recall.minScore,requireQuerySignal:input.requireQuerySignal,includeExpired:input.includeExpired},recallResult=this.provider.recallWithDiagnostics?await this.provider.recallWithDiagnostics(request):{items:await this.provider.recall(request)},bundle=toRecallBundle({id:createBundleId(query,generatedAt),query,generatedAt,items:recallResult.items,tokenBudget,diagnostics:recallResult.diagnostics?{injectionSkipReason:input.mode==="injection"?resolveInjectionSkipReason(recallResult.diagnostics):void 0,candidateCount:recallResult.diagnostics.candidateCount,preScoredFilteredCount:recallResult.diagnostics.preScoredFilteredCount,noSignalCount:recallResult.diagnostics.noSignalCount,belowThresholdCount:recallResult.diagnostics.belowThresholdCount}:void 0});return await this.provider.recordRecallUsage?.({bundleId:bundle.id,query,scopes,kinds:input.kinds,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate,agentRole:this.context.agentRole,runId:this.context.runId??this.context.sessionID,unitId:this.context.unitId,timestamp:generatedAt}),bundle}async propose(input){if(this.assertEnabled(),!this.provider.createProposal)throw new MemoryValidationError("memory provider does not support proposals");let redactedFields=new Set,redactProposalField=(field,value)=>{let redacted=redactSecrets(value);if(redacted!==value)redactedFields.add(field);return redacted},rationale=redactProposalField("rationale",normalizeMemoryText(input.rationale));if(!rationale)throw new MemoryValidationError("rationale is required");let evidenceRefs=(input.evidenceRefs??[]).map((ref)=>normalizeMemoryText(ref)).filter(Boolean).map((ref)=>redactProposalField("evidenceRefs",ref)).slice(0,20),needsRecord=input.operation==="add"||input.operation==="update"||input.operation==="supersede",proposedRecord,status="pending",reviewer,reviewedAt,rejectionReason,targetMemoryId=input.targetMemoryId===void 0?void 0:redactProposalField("targetMemoryId",normalizeMemoryText(input.targetMemoryId)),relatedMemoryIds=input.relatedMemoryIds?.map((id)=>redactProposalField("relatedMemoryIds",normalizeMemoryText(id))),proposalText=`${input.operation}:${targetMemoryId??""}`;if(needsRecord){if(!input.kind)throw new MemoryValidationError("kind is required for this operation");if(!input.text)throw new MemoryValidationError("text is required for this operation");proposalText=input.text;let normalizedText=normalizeMemoryText(input.text),redactedText=redactProposalField("text",normalizedText),extractedPaths=extractFilePaths(evidenceRefs),extractedSymbols=extractSymbols(evidenceRefs),recordMetadata={};if(extractedPaths.length>0)recordMetadata.files=extractedPaths;if(extractedSymbols.length>0)recordMetadata.symbols=extractedSymbols;proposedRecord=this.createRecord({kind:input.kind,text:redactedText,evidenceRefs,source:sourceFromEvidence(evidenceRefs,this.context),metadata:recordMetadata}),validateMemoryRecordRules(proposedRecord,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}if(redactedFields.size>0)status="rejected",reviewer="auto_policy",reviewedAt=this.now().toISOString(),rejectionReason=`proposal field(s) contained a likely secret and were redacted: ${Array.from(redactedFields).join(", ")}`;if((input.operation==="update"||input.operation==="delete"||input.operation==="supersede")&&!targetMemoryId)throw new MemoryValidationError(`${input.operation} proposals require targetMemoryId`);if(input.operation==="merge"&&(relatedMemoryIds??[]).length<2)throw new MemoryValidationError("merge proposals require relatedMemoryIds");let createdAt=this.now().toISOString(),proposer=this.context.agentId??this.context.agentRole??this.context.sessionID??"unknown",proposal={id:createProposalId({createdAt,proposer,text:proposalText}),operation:input.operation,proposedRecord,targetMemoryId,relatedMemoryIds,proposedBy:{agentRole:this.context.agentRole,agentId:this.context.agentId,runId:this.context.runId??this.context.sessionID},rationale,evidenceRefs,status,reviewer,reviewedAt,rejectionReason,createdAt,metadata:{}};return this.provider.createProposal(proposal)}async listMemories(filter={}){return this.assertEnabled(),this.provider.list(filter)}async listProposals(filter){if(this.assertEnabled(),!this.provider.listProposals)throw new MemoryValidationError("memory provider does not support proposals");return this.provider.listProposals(filter)}async listRecallUsage(filter){if(this.assertEnabled(),!this.provider.listRecallUsage)return[];return this.provider.listRecallUsage(filter)}async upsertCurated(record2){this.assertEnabled();let parsed=validateMemoryRecordRules(record2,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.provider.upsert(parsed)}async applyCuratorDecision(decision){if(this.assertEnabled(),!this.provider.applyCuratorDecision)throw new MemoryValidationError("memory provider does not support curator decisions");let parsed=validateCuratorMemoryDecision(decision),resolved=this.resolveCuratorDecision(parsed);return this.provider.applyCuratorDecision(resolved)}createRecord(input){let now=this.now().toISOString(),text=normalizeMemoryText(input.text),kind=input.kind,stability=input.stability??(kind==="scratch"?"ephemeral":"durable"),scope=this.resolveRecordScope(input.scope,stability),expiresAt=kind==="scratch"?new Date(this.now().getTime()+604800000).toISOString():void 0,recordBase={scope,kind,text};return{id:createMemoryId(recordBase),scope,kind,text,tags:normalizeTags2(input.tags??inferTags(text)),confidence:clamp(input.confidence??0.5,0,1),stability,source:input.source??sourceFromEvidence(input.evidenceRefs??[],this.context),createdAt:now,updatedAt:now,expiresAt,contentHash:computeMemoryContentHash(recordBase),metadata:input.metadata??{},cohortId:isCohortRoot(this.vettedRoot)?this.vettedRoot.cohortId:void 0,producerSessionId:this.context.sessionID,producerAgentRole:this.context.agentRole,redactionPolicyVersion:computeRedactionPolicyVersion(this.config.redaction.rejectDurableSecrets),providerVersion:this.provider.name}}resolveCuratorDecision(decision){switch(decision.action){case"add":return{action:"add",proposalId:decision.proposalId,memory:this.createRecordFromNew(decision.memory)};case"supersede":return{action:"supersede",proposalId:decision.proposalId,oldMemoryId:decision.oldMemoryId,replacement:this.createRecordFromNew(decision.replacement),reason:normalizeMemoryText(decision.reason)};case"update":{let patch=normalizeMemoryPatch(decision.patch);if(patch.scope)patch.scope=this.resolveRecordScope(patch.scope);return{action:"update",proposalId:decision.proposalId,targetMemoryId:decision.targetMemoryId,patch,reason:normalizeMemoryText(decision.reason)}}case"reject":case"noop":return{action:decision.action,proposalId:decision.proposalId,reason:normalizeMemoryText(decision.reason)}}}createRecordFromNew(input){let record2=this.createRecord({kind:input.kind,text:input.text,scope:input.scope,tags:input.tags,confidence:input.confidence,stability:input.stability,source:input.source,metadata:input.metadata}),next=input.expiresAt?{...record2,expiresAt:input.expiresAt}:record2;return validateMemoryRecordRules(next,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}resolveRecordScope(scope,stability){let allowedScopes=this.deriveAllowedScopes();if(!scope){let wantsCohort=stability!=="ephemeral"&&stability!=="session",cohortScope=allowedScopes.find((s)=>s.type==="cohort"),defaultScope=wantsCohort?cohortScope??allowedScopes[1]??allowedScopes[0]:allowedScopes[1]??allowedScopes[0];if(!defaultScope)throw new MemoryValidationError("memory scope is not available for this context");return defaultScope}return validateRequestedScopes([scope],allowedScopes,"memory scope is not allowed for this context"),scope}assertEnabled(){if(!this.config.enabled)throw new MemoryDisabledError}}function createMemoryGateway(context,options={}){return new MemoryGateway(context,options)}function createConfiguredMemoryProvider(directory,config2){let root=resolveVettedMemoryRoot(directory,config2);return createConfiguredMemoryProviderForRoot(root,config2)}function createConfiguredMemoryProviderForRoot(root,config2){if(config2.provider==="sqlite")return getOrCreateProviderForRoot(root,config2);let cohortRoot=root.kind==="cohort"?root.cohortRoot:null;return new LocalJsonlMemoryProvider(root.directory,config2,cohortRoot)}function sourceFromEvidence(evidenceRefs,context){let first=evidenceRefs[0];if(!first)return{type:"agent",createdBy:context.agentId??context.agentRole};if(/^https?:\/\//i.test(first))return{type:"web",url:first};if(/^[a-f0-9]{40}$/i.test(first))return{type:"commit",commitSha:first};let filePath=extractFilePaths(evidenceRefs)[0]??first;if(filePath!==first&&(filePath.includes("/")||filePath.includes("\\")||filePath.includes(".")))return{type:"file",filePath};if(first.includes("/")||first.includes("\\")||first.includes("."))return{type:"file",filePath:first};return{type:"manual",ref:first}}function createStableId(value){return createHash15("sha256").update(value.toLowerCase()).digest("hex").slice(0,16)}function readGitRemoteUrl(directory){if(gitRemoteUrlCache.has(directory))return gitRemoteUrlCache.get(directory);let gitConfigPath=path43.join(directory,".git","config");if(!existsSync20(gitConfigPath)){gitRemoteUrlCache.set(directory,void 0);return}try{let remoteUrl=readFileSync19(gitConfigPath,"utf-8").match(/\[remote "origin"\][\s\S]*?\n\s*url\s*=\s*(.+)/)?.[1]?.trim();return gitRemoteUrlCache.set(directory,remoteUrl),remoteUrl}catch{gitRemoteUrlCache.set(directory,void 0);return}}function validateRequestedScopes(requested,allowed,disallowedMessage="recall scope is not allowed for this context"){if(requested.length===0)throw new MemoryValidationError("recall scopes must not be empty");let allowedKeys=new Set(allowed.map(scopeKey));for(let scope of requested)if(!allowedKeys.has(scopeKey(scope)))throw new MemoryValidationError(disallowedMessage);return requested}function resolveInjectionSkipReason(diagnostics){if(diagnostics.returnedCount>0)return;if(diagnostics.candidateCount===0)return"no_results";let signalEligibleCount=diagnostics.candidateCount-diagnostics.preScoredFilteredCount-diagnostics.suppressedLowQCount;if(signalEligibleCount>0&&diagnostics.noSignalCount>0&&diagnostics.noSignalCount>=signalEligibleCount)return"no_signal";if(diagnostics.belowThresholdCount>0)return"below_threshold";return"no_results"}function scopeKey(scope){return JSON.stringify({type:scope.type,userId:scope.userId,workspaceId:scope.workspaceId,projectId:scope.projectId,repoId:scope.repoId,repoRoot:scope.repoRoot?path43.resolve(scope.repoRoot):void 0,runId:scope.runId,agentId:scope.agentId,cohortId:scope.cohortId})}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function clampInt(value,min,max){return Math.trunc(clamp(value,min,max))}function normalizeTags2(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}function normalizeMemoryPatch(patch){return{...patch,text:patch.text===void 0?void 0:normalizeMemoryText(patch.text),tags:patch.tags===void 0?void 0:normalizeTags2(patch.tags)}}function inferTags(text){let lower=text.toLowerCase(),tags=[];for(let[tag,pattern]of[["testing",/\b(test|spec|bun|jest|vitest)\b/],["tooling",/\b(pnpm|npm|yarn|bun|biome|eslint|typescript)\b/],["security",/\b(security|auth|token|secret|password|csp)\b/],["api",/\b(api|endpoint|graphql|rest|sdk)\b/],["architecture",/\b(architecture|decision|adr|pattern)\b/],["failure",/\b(fail|failure|regression|flaky|timeout)\b/]])if(pattern.test(lower))tags.push(tag);return tags}function extractFilePaths(refs){let seen=new Set,paths=[];for(let ref of refs){FILE_PATH_REGEX.lastIndex=0;let matches=ref.match(FILE_PATH_REGEX);if(!matches)continue;for(let m of matches)if(!seen.has(m)){if(seen.add(m),paths.push(m),paths.length>=20)return paths}}return paths}function extractSymbols(refs){let seen=new Set,symbols=[],identRegex=/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g;for(let ref of refs){identRegex.lastIndex=0;let matches=ref.match(identRegex);if(!matches)continue;for(let m of matches)if(m.length>=3&&!seen.has(m)&&!RESERVED_IDENTIFIERS.has(m)){if(seen.add(m),symbols.push(m),symbols.length>=20)return symbols}}return symbols}var gitRemoteUrlCache,FILE_PATH_REGEX,RESERVED_IDENTIFIERS;var init_gateway=__esm(()=>{init_config2();init_errors4();init_local_jsonl_provider();init_prompt_block();init_provider_pool();init_redaction();init_schema2();init_storage_root();gitRemoteUrlCache=new Map;FILE_PATH_REGEX=/\b(?:src|tests|test|docs|scripts|packages|lib|config|examples|internal|cmd|pkg|bin|tools|cli|api|server|client|app|core|utils|hooks|services|commands|agents|memory)\/[A-Za-z0-9._/@+-]+/g,RESERVED_IDENTIFIERS=new Set(["const","let","var","function","class","interface","type","async","await","return","if","else","for","while","do","switch","case","break","continue","new","this","super","extends","implements","import","export","from","default","try","catch","finally","throw","typeof","instanceof","in","of","as","yield","static","get","set","readonly","public","private","protected"])});async function applyCouncilReward(provider,opts){let bundles=await provider.listRecallUsage?.({runId:opts.runId})??[];if(bundles.length===0)return{memoriesRewarded:0};let attributedBundles=bundles.filter((bundle)=>bundle.unitId==null||opts.unitId==null||bundle.unitId===opts.unitId),distinctIds=new Set;for(let bundle of attributedBundles)for(let id of bundle.memoryIds)distinctIds.add(id);let result=await(provider.withTransaction?provider.withTransaction(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates}):(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates})()),memoriesRewarded=result.size,rewardedRecords=[...result.values()].map(({rec})=>rec);try{await propagateReward(provider,opts,rewardedRecords,distinctIds)}catch(err){log(`[memory:propagation] skipped after error: ${err instanceof Error?err.message:String(err)}`)}return{memoriesRewarded}}async function propagateReward(provider,opts,sources,directlyRewardedIds){if(sources.length===0)return;let qConfig=opts.qLearning??DEFAULT_QLEARNING_CONFIG,fraction=qConfig.propagationFraction,fanoutCap=qConfig.propagationFanoutCap,windowDays=qConfig.propagationWindowDays,relatednessThreshold=qConfig.propagationRelatednessThreshold;if(!Number.isFinite(fraction)||fraction<=0)return;if(!Number.isFinite(fanoutCap)||fanoutCap<=0)return;if(!Number.isFinite(windowDays)||windowDays<=0)return;if(!Number.isFinite(relatednessThreshold))return;if(typeof provider.list!=="function")return;let nowMs=Date.parse(opts.timestamp);if(!Number.isFinite(nowMs))return;let windowMs=windowDays*MS_PER_DAY2,recencyById=await buildRetrievalRecency(provider);if(!recencyById)return;let orderedSources=[...sources].sort((a,b)=>a.id.localeCompare(b.id)),scheduled=new Map,listCache=new Map;for(let source of orderedSources){let scopeKey2=stableScopeKey(source.scope),cacheKey=`${scopeKey2}::${source.kind}`,candidates=listCache.get(cacheKey);if(!candidates)candidates=await provider.list({scopes:[source.scope],kinds:[source.kind]}),listCache.set(cacheKey,candidates);let sourceTokens=tokenize(source.text),qualified=[];for(let cand of candidates){if(cand.id===source.id)continue;if(directlyRewardedIds.has(cand.id))continue;if(stableScopeKey(cand.scope)!==scopeKey2)continue;if(cand.kind!==source.kind)continue;let retrievedAt=recencyById.get(cand.id);if(retrievedAt===void 0)continue;if(nowMs-retrievedAt>windowMs)continue;let overlap2=jaccard(sourceTokens,tokenize(cand.text));if(overlap2<relatednessThreshold)continue;qualified.push({record:cand,overlap:overlap2})}qualified.sort((a,b)=>b.overlap-a.overlap||a.record.id.localeCompare(b.record.id));let cap=Math.trunc(fanoutCap),selected=qualified.slice(0,cap),dropped=qualified.length-selected.length;if(dropped>0)log(`[memory:propagation] fan-out cap reached for source ${source.id}: ${qualified.length} qualified, ${selected.length} propagated, ${dropped} dropped by cap ${cap}`);for(let{record:record2}of selected)if(!scheduled.has(record2.id))scheduled.set(record2.id,record2)}for(let record2 of scheduled.values()){let qBefore=getQValue(record2,opts.initialQValue),qAfter=applyPropagatedEmaUpdate(qBefore,opts.reward,opts.eta,fraction);await provider.upsert(setQValue(record2,qAfter)),await provider.appendRewardEvent?.({memoryId:record2.id,runId:opts.runId,unitId:opts.unitId,verdict:`${opts.verdictLabel??"APPROVE"}${PROPAGATED_VERDICT_SUFFIX}`,reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp})}}function truncateObjectForJson(obj,capBytes){let asIs=JSON.stringify(obj);if(asIs.length<=capBytes)return obj;if(JSON.stringify({...obj,__truncated__:!0}).length<=capBytes)return{...obj,__truncated__:!0};return{__truncated__:!0,originalSize:asIs.length,cap:capBytes}}async function buildRetrievalRecency(provider){if(typeof provider.listRecallUsage!=="function")return null;let since=new Date(Date.now()-RECENCY_WINDOW_MS).toISOString(),usage=await provider.listRecallUsage({since,limit:RECENCY_EVENT_LIMIT})??[],recency=new Map;for(let event of usage){let ts=Date.parse(event.timestamp);if(!Number.isFinite(ts))continue;for(let id of event.memoryIds){let prev=recency.get(id);if(prev===void 0||ts>prev)recency.set(id,ts)}}return recency}var PROPAGATED_VERDICT_SUFFIX="_PROPAGATED",MS_PER_DAY2=86400000,RECENCY_WINDOW_MS,RECENCY_EVENT_LIMIT=1000;var init_reward_capture=__esm(()=>{init_logger();init_config2();init_schema2();init_scoring();RECENCY_WINDOW_MS=30*MS_PER_DAY2});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win323){return win323===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state.prefix="./";return output};exports.wrapOutput=(input,state={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path44,{windows}={})=>{let segs=path44.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state.maxDepth=0,!isPathSeparator(code))tokens.push(token);state.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state.maxDepth+=tokens[tokens.length-1].depth}state.slashes=slashes,state.parts=parts}return state};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants3=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants3,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants3.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse5=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants3.globChars(opts.windows),EXTGLOB_CHARS=constants3.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state.index===len-1,peek=state.peek=(n=1)=>input[state.index+n],advance=state.advance=()=>input[++state.index]||"",remaining=()=>input.slice(state.index+1),consume=(value2="",num=0)=>{state.consumed+=value2,state.index+=num},append=(token)=>{state.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state.start++,count++;if(count%2===0)return!1;return state.negated=!0,state.start++,!0},increment=(type)=>{state[type]++,stack.push(type)},decrement=(type)=>{state[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state.output=state.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state.parens,token.output=state.output,token.startIndex=state.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal2=input.slice(token.startIndex,state.index+1),body=input.slice(token.startIndex+2,state.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open3=tokens[token.tokensIndex];open3.type="text",open3.value=literal2,open3.output=safeOutput||utils.escapeRegex(literal2);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state.output=token.output+open3.output,state.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse5(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc2,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc2)return esc2+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc2)return esc2+first+(rest?star:"");return star}return esc2?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state.output=input,state;return state.output=utils.wrapOutput(output,state,options),state}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state.brackets===0){push({type:"text",value});continue}}if(state.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix4=POSIX_REGEX_SOURCE[rest2];if(posix4){if(prev.value=pre+posix4,state.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state.quotes=state.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state.output=state.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open3={type:"brace",value,output:"(",outputIndex:state.output.length,tokensIndex:state.tokens.length};braces.push(open3),push(open3);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state.output.slice(0,brace.outputIndex),toks=state.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state.output=out;for(let t of toks)state.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state.index===state.start+1){state.start=state.index+1,state.consumed="",state.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state.braces+state.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state.backtrack=!0,state.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state.output=prev.output,state.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state.output=state.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state.globstar=!0,state.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state.output=state.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state.output+=prior.output+prev.output,state.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state.output=prev.output,state.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state.output=state.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state.output+=prev.output,state.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state.index===state.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state.output+=nodot,prev.output+=nodot;if(peek()!=="*")state.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state.output=utils.escapeLast(state.output,"["),decrement("brackets")}while(state.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state.output=utils.escapeLast(state.output,"("),decrement("parens")}while(state.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state.output=utils.escapeLast(state.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state.backtrack===!0){state.output="";for(let token of state.tokens)if(state.output+=token.output!=null?token.output:token.value,token.suffix)state.output+=token.suffix}return state};parse5.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants3.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse5});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse5=require_parse(),utils=require_utils(),constants3=require_constants(),isObject2=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state2=isMatch(str);if(state2)return state2}return!1}}let isState=isObject2(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix4=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix4}),result={glob,state,regex,posix:posix4,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix4}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix4?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix4);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse5(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state.output})${append}`;if(state&&state.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse5.fastpaths(input,options);if(!parsed.output)parsed=parse5(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants3;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache){let item=cache.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count=1){let requested=Number(count);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}import*as fsSync5 from"node:fs";import*as path44 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let sortedKeys=Object.keys(args2).sort();return Number(bunHash(JSON.stringify(args2,sortedKeys)))}catch(error49){return log("[Guardrails] hashArgs failed",{error:error49 instanceof Error?error49.message:String(error49)}),0}}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached2=pathNormalizationCache.get(cacheKey);if(cached2!==void 0)return cached2;try{let absolutePath=path44.isAbsolute(filePath)?filePath:path44.resolve(cwd,filePath),normalized=fsSync5.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path44.isAbsolute(filePath)?filePath:path44.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached2=globMatcherCache.get(cacheKey);if(cached2!==void 0)return cached2;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path44.resolve(cwd),normalizedTarget=path44.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path44.relative(normalizedCwd,current);if(rel===""||rel.startsWith(".."))break;ancestors.push(current);let parent=path44.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat8=null;try{stat8=fsSync5.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat8.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink — writing through a symlink could redirect the write outside the working directory`}return null}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path44){return pathLib.parse(targetAbsolute).root!==pathLib.parse(cwdAbsolute).root}function isInDeclaredScope(filePath,scopeEntries,cwd){let dir=cwd??process.cwd(),caseInsensitive=process.platform==="win32",resolvedFileRaw=path44.resolve(dir,filePath),resolvedFile=caseInsensitive?resolvedFileRaw.toLowerCase():resolvedFileRaw;return scopeEntries.some((scope)=>{let resolvedScopeRaw=path44.resolve(dir,scope),resolvedScope=caseInsensitive?resolvedScopeRaw.toLowerCase():resolvedScopeRaw;if(resolvedFile===resolvedScope)return!0;let rel=path44.relative(resolvedScope,resolvedFile);return rel.length>0&&!rel.startsWith("..")&&!path44.isAbsolute(rel)})}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),normalizedPath,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path44.resolve(dir,normalizedWithSymlinks),normalizedPath=path44.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path44.resolve(dir,filePath),normalizedPath=path44.relative(dir,resolvedTarget).replace(/\\/g,"/")}if(isOnDifferentFilesystemRoot(resolvedTarget,dir))return{allowed:!1,reason:`Path blocked: ${filePath} is on a different drive/root than the working directory`};if(normalizedPath===".."||normalizedPath.startsWith("../"))return{allowed:!1,reason:`Path blocked: ${normalizedPath} resolves outside the working directory`};let rules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent];if(!rules)return{allowed:!1,reason:`Unknown agent: ${agentName}`};if(rules.readOnly)return{allowed:!1,reason:`Path blocked: ${normalizedPath} (agent ${normalizedAgent} is read-only)`};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(normalizedPath===blocked)return{allowed:!1,reason:`Path blocked (exact): ${normalizedPath}`}}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(getGlobMatcher(glob)(normalizedPath))return{allowed:!1,reason:`Path blocked (glob ${glob}): ${normalizedPath}`}}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>normalizedPath===allowed))return{allowed:!0}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath);if(rules.blockedZones.includes(zone))return{allowed:!1,reason:`Path blocked: ${normalizedPath} is in ${zone} zone`,zone}}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some((glob)=>{return getGlobMatcher(glob)(normalizedPath)}))return{allowed:!0}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath)}))return{allowed:!0}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(normalizedPath.startsWith(prefix))return{allowed:!1,reason:`Path blocked: ${normalizedPath} is under ${prefix}`}}if(!((normalizedAgent==="coder"||strippedAgent==="coder")&&options?.declaredScope!=null&&options.declaredScope.length>0&&isInDeclaredScope(normalizedPath,options.declaredScope,dir))){if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>normalizedPath.startsWith(prefix)))return{allowed:!1,reason:`Path ${normalizedPath} not in allowed list for ${normalizedAgent}`}}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return{allowed:!1,reason:`Path ${normalizedPath} not in allowed list for ${normalizedAgent}`}}return{allowed:!0}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),options)}var import_picomatch,pathNormalizationCache,globMatcherCache,DEFAULT_AGENT_AUTHORITY_RULES;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_utils();init_bun_compat();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200});DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}}});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&&QUOTA_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;session.pendingAdvisoryMessages??=[];let rejections=input.rejectionCount??0,resolutionPath;if(rejections>=3)resolutionPath="soundingboard",session.pendingAdvisoryMessages.push(`CONFLICT ESCALATION: ${input.sourceAgent} vs ${input.targetAgent} on task ${input.taskId??"unknown"}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`);else resolutionPath="self_resolve",session.pendingAdvisoryMessages.push(`CONFLICT DETECTED: ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${input.taskId??"unknown"}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`);let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state2();init_telemetry()});function extractCurrentPhase(planContent){if(!planContent)return null;let lines=planContent.split(`
533
+ `}];FTS_STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","goal","how","in","into","is","it","of","on","or","role","task","that","the","this","to","user","what","when","with"])});import{realpathSync as realpathSync7}from"node:fs";import*as path39 from"node:path";function markAsPooled(provider){let originalClose=provider.close;if(provider.close=()=>{return releaseProvider(provider),Promise.resolve()},provider[POOLED_MARKER]=!0,originalClose)provider[REAL_CLOSE]=originalClose}function callRealClose(provider){let realClose=provider[REAL_CLOSE];try{realClose?.call(provider)}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[provider-pool] real close failed: ${msg}`)}}function isPooledProvider(provider){return POOLED_MARKER in provider}function getOrCreateProviderForRoot(root,config2){let key=resolvePoolKeyForRoot(root),rootGeneration=root.kind==="cohort"?root.generation:0,existing=entriesByKey.get(key);if(existing){if((existing.generation??0)===rootGeneration)return moveToHead(existing),existing.refCount++,existing.provider;evictEntryByKey(key)}for(let deferred of deferredEntries)if(deferred.key===key){if((deferred.generation??0)===rootGeneration){if(deferredEntries.delete(deferred),entriesByKey.size>=MAX_POOL_SIZE)evictLru();if(deferred.prev=null,deferred.next=head,head)head.prev=deferred;if(head=deferred,!tail)tail=deferred;return entriesByKey.set(key,deferred),deferred.refCount++,deferred.provider}deferredEntries.delete(deferred),callRealClose(deferred.provider);break}let directory=root.directory,cohortRoot=root.kind==="cohort"?root.cohortRoot:null,provider=new SQLiteMemoryProvider(directory,config2,cohortRoot);if(markAsPooled(provider),entriesByKey.size>=MAX_POOL_SIZE)evictLru();let entry={key,provider,refCount:1,prev:null,next:head};if(entry.generation=rootGeneration,head)head.prev=entry;if(head=entry,!tail)tail=entry;return entriesByKey.set(key,entry),provider}function resolvePoolKeyForRoot(root){if(root.kind==="cohort")try{return`cohort:${realpathSync7(root.cohortRoot)}`}catch{return`cohort:${path39.resolve(root.cohortRoot)}`}return resolvePoolKey(root.directory)}function evictEntryByKey(key){let entry=entriesByKey.get(key);if(!entry)return;if(entry.refCount>0){deferredEntries.add(entry),unlinkEntry(entry),entriesByKey.delete(key);return}unlinkEntry(entry),entriesByKey.delete(key),callRealClose(entry.provider)}function evictAndCloseForRoot(root){let key=resolvePoolKeyForRoot(root);evictEntryByKey(key)}function releaseProvider(provider){for(let[_key,entry]of entriesByKey)if(entry.provider===provider){entry.refCount=Math.max(0,entry.refCount-1);return}for(let entry of deferredEntries)if(entry.provider===provider){if(entry.refCount--,entry.refCount<=0)deferredEntries.delete(entry),callRealClose(provider);return}if(isPooledProvider(provider))callRealClose(provider)}function evictLru(){if(!tail)return;let evicted=tail;if(entriesByKey.delete(evicted.key),unlinkEntry(evicted),evicted.refCount>0)deferredEntries.add(evicted);else callRealClose(evicted.provider)}function moveToHead(entry){if(head===entry)return;if(unlinkEntry(entry),entry.prev=null,entry.next=head,head)head.prev=entry;if(head=entry,!tail)tail=entry}function unlinkEntry(entry){if(entry.prev)entry.prev.next=entry.next;if(entry.next)entry.next.prev=entry.prev;if(head===entry)head=entry.next;if(tail===entry)tail=entry.prev}function resolvePoolKey(directory){let rawKey=path39.resolve(directory);try{let canonical=realpathSync7(directory);if(resolvedKeyCache.delete(rawKey),resolvedKeyCache.set(rawKey,canonical),resolvedKeyCache.size>MAX_POOL_SIZE){let oldest=resolvedKeyCache.keys().next().value;if(oldest!==void 0)resolvedKeyCache.delete(oldest)}return canonical}catch{return resolvedKeyCache.get(rawKey)??rawKey}}function evictAndClose(directory){let key=resolvePoolKey(directory),active=entriesByKey.get(key);if(active)entriesByKey.delete(key),unlinkEntry(active),callRealClose(active.provider);for(let deferred of[...deferredEntries])if(deferred.key===key)deferredEntries.delete(deferred),callRealClose(deferred.provider)}var MAX_POOL_SIZE=16,POOLED_MARKER,REAL_CLOSE,head=null,tail=null,entriesByKey,deferredEntries,resolvedKeyCache;var init_provider_pool=__esm(()=>{init_sqlite_provider();POOLED_MARKER=Symbol("opencode-swarm-pooled-provider"),REAL_CLOSE=Symbol("opencode-swarm-real-close"),entriesByKey=new Map,deferredEntries=new Set,resolvedKeyCache=new Map});var exports_knowledge_link={};__export(exports_knowledge_link,{writeLinkPointer:()=>writeLinkPointer,sanitizeLinkId:()=>sanitizeLinkId,resolveLinkDir:()=>resolveLinkDir,resolveLinkBaseDir:()=>resolveLinkBaseDir,resolveKnowledgeStoreDir:()=>resolveKnowledgeStoreDir,removeLinkPointer:()=>removeLinkPointer,readLinkPointer:()=>readLinkPointer,isLinked:()=>isLinked,invalidateKnowledgeStoreDirCache:()=>invalidateKnowledgeStoreDirCache,getLinkedLocalKnowledgeStatus:()=>getLinkedLocalKnowledgeStatus,_internals:()=>_internals26,LINK_POINTER_FILENAME:()=>LINK_POINTER_FILENAME});import{existsSync as existsSync18,lstatSync as lstatSync6,mkdirSync as mkdirSync17,readFileSync as readFileSync17,rmSync as rmSync3,statSync as statSync11}from"node:fs";import*as os12 from"node:os";import*as path40 from"node:path";function resolveDataDir(){let platform=process.platform,home=process.env.HOME||os12.homedir();if(platform==="win32")return path40.join(process.env.LOCALAPPDATA||path40.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")return path40.join(home,"Library","Application Support","opencode-swarm");return path40.join(process.env.XDG_DATA_HOME||path40.join(home,".local","share"),"opencode-swarm")}function resolveLinkBaseDir(){return path40.join(resolveDataDir(),"links")}function resolveLinkDir(linkId){return path40.join(resolveLinkBaseDir(),linkId)}function sanitizeLinkId(name){if(typeof name!=="string")return null;let cleaned=name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,MAX_LINK_ID_LENGTH).replace(/[-.]+$/g,"");if(cleaned.length===0)return null;let base=cleaned.split(".")[0];if(WINDOWS_RESERVED_NAMES.has(base))return null;return cleaned}function resolveLinkPointerPath(directory){return path40.join(directory,".swarm",LINK_POINTER_FILENAME)}function readLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);if(!existsSync18(pointerPath))return null;try{let raw=JSON.parse(readFileSync17(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:obj.version===2?2:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),source:obj.source==="auto"?"auto":"manual",cohortId:typeof obj.cohortId==="string"?obj.cohortId:void 0,identitySource:obj.identitySource==="remote"||obj.identitySource==="git-common-dir"||obj.identitySource==="path"?obj.identitySource:void 0,degraded:typeof obj.degraded==="boolean"?obj.degraded:void 0,configFingerprint:typeof obj.configFingerprint==="string"?obj.configFingerprint:void 0,generation:typeof obj.generation==="number"?obj.generation:void 0}}catch{return null}}function getLinkedLocalKnowledgeStatus(directory){let localKnowledgePath=path40.join(directory,".swarm","knowledge.jsonl"),pointer=readLinkPointer(directory);if(!pointer)return{linked:!1,orphaned:!1,localKnowledgePath,resolvedKnowledgePath:localKnowledgePath,reason:"not_linked"};let resolvedKnowledgePath=path40.join(path40.resolve(resolveLinkDir(pointer.linkId)),"knowledge.jsonl");if(!existsSync18(localKnowledgePath))return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"};try{if(lstatSync6(localKnowledgePath).isSymbolicLink())return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_symlink"}}catch{return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"}}return{linked:!0,orphaned:!0,localKnowledgePath,resolvedKnowledgePath,reason:"local_regular_file"}}async function writeLinkPointer(directory,pointer){let swarmDir=path40.join(directory,".swarm");mkdirSync17(swarmDir,{recursive:!0});let pointerPath=resolveLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateKnowledgeStoreDirCache(directory)}async function removeLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);try{rmSync3(pointerPath,{force:!0})}finally{invalidateKnowledgeStoreDirCache(directory)}}function pointerStatFingerprint(directory){let pointerPath=resolveLinkPointerPath(directory);try{let st=statSync11(pointerPath);return`${st.mtimeMs}:${st.ctimeMs}:${st.size}`}catch{return null}}function resolveKnowledgeStoreDir(directory){let localSwarm=path40.join(directory,".swarm"),now=Date.now(),cached2=_resolutionCache.get(directory),currentStat=pointerStatFingerprint(directory);if(cached2&&now<cached2.expires&&cached2.pointerStat===currentStat)return cached2.linkDir??localSwarm;let linkDir=null;try{let pointer=readLinkPointer(directory);if(pointer){linkDir=path40.resolve(resolveLinkDir(pointer.linkId));let orphanStatus=getLinkedLocalKnowledgeStatus(directory);if(orphanStatus.orphaned)warn("[knowledge-link] local knowledge file is orphaned by link store",{localKnowledgePath:orphanStatus.localKnowledgePath,resolvedKnowledgePath:orphanStatus.resolvedKnowledgePath})}}catch{linkDir=null}if(!_resolutionCache.has(directory)&&_resolutionCache.size>=MAX_CACHE_ENTRIES2){let oldest=_resolutionCache.keys().next().value;if(oldest!==void 0)_resolutionCache.delete(oldest)}return _resolutionCache.set(directory,{linkDir,expires:now+CACHE_TTL_MS,pointerStat:currentStat}),linkDir??localSwarm}function invalidateKnowledgeStoreDirCache(directory){if(directory===void 0){_resolutionCache.clear();return}_resolutionCache.delete(directory)}function isLinked(directory){return readLinkPointer(directory)!==null}var LINK_POINTER_FILENAME="link.json",MAX_LINK_ID_LENGTH=64,WINDOWS_RESERVED_NAMES,CACHE_TTL_MS=2000,MAX_CACHE_ENTRIES2=500,_resolutionCache,_internals26;var init_knowledge_link=__esm(()=>{init_task_file();init_logger();WINDOWS_RESERVED_NAMES=new Set(["con","prn","aux","nul","com0","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt0","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);_resolutionCache=new Map;_internals26={resolveKnowledgeStoreDir,readLinkPointer,writeLinkPointer,removeLinkPointer,getLinkedLocalKnowledgeStatus,invalidateKnowledgeStoreDirCache,resolveLinkDir,resolveLinkBaseDir,sanitizeLinkId}});import{existsSync as existsSync19,mkdirSync as mkdirSync18,readFileSync as readFileSync18,rmSync as rmSync4,statSync as statSync12}from"node:fs";import*as path41 from"node:path";function resolveMemoryLinkPointerPath(directory){return path41.join(directory,".swarm",MEMORY_LINK_POINTER_FILENAME)}function readMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);if(!existsSync19(pointerPath))return null;try{let raw=JSON.parse(readFileSync18(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:obj.version===2?2:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),cohortId:typeof obj.cohortId==="string"?obj.cohortId:void 0,identitySource:obj.identitySource==="remote"||obj.identitySource==="git-common-dir"||obj.identitySource==="path"?obj.identitySource:void 0,degraded:typeof obj.degraded==="boolean"?obj.degraded:void 0,configFingerprint:typeof obj.configFingerprint==="string"?obj.configFingerprint:void 0,generation:typeof obj.generation==="number"?obj.generation:void 0}}catch{return null}}async function writeMemoryLinkPointer(directory,pointer){let swarmDir=path41.join(directory,".swarm");mkdirSync18(swarmDir,{recursive:!0});let pointerPath=resolveMemoryLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateMemoryStoreDirCache(directory)}async function removeMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{rmSync4(pointerPath,{force:!0})}finally{invalidateMemoryStoreDirCache(directory)}}function pointerStatFingerprint2(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{let st=statSync12(pointerPath);return`${st.mtimeMs}:${st.ctimeMs}:${st.size}`}catch{return null}}function resolveMemoryStoreDir(directory){let localSwarm=path41.join(directory,".swarm"),now=Date.now(),cached2=_resolutionCache2.get(directory),currentStat=pointerStatFingerprint2(directory);if(cached2&&now<cached2.expires&&cached2.pointerStat===currentStat)return cached2.linkDir??localSwarm;let linkDir=null;try{let pointer=readMemoryLinkPointer(directory);if(pointer)linkDir=path41.resolve(resolveLinkDir(pointer.linkId))}catch{linkDir=null}if(!_resolutionCache2.has(directory)&&_resolutionCache2.size>=MAX_CACHE_ENTRIES3){let oldest=_resolutionCache2.keys().next().value;if(oldest!==void 0)_resolutionCache2.delete(oldest)}return _resolutionCache2.set(directory,{linkDir,expires:now+CACHE_TTL_MS2,pointerStat:currentStat}),linkDir??localSwarm}function invalidateMemoryStoreDirCache(directory){if(directory===void 0){_resolutionCache2.clear();return}_resolutionCache2.delete(directory)}var MEMORY_LINK_POINTER_FILENAME="memory-link.json",CACHE_TTL_MS2=2000,MAX_CACHE_ENTRIES3=500,_resolutionCache2;var init_memory_link=__esm(()=>{init_task_file();init_knowledge_link();init_logger();_resolutionCache2=new Map});import*as path42 from"node:path";function resolveVettedMemoryRoot(directory,config2){if(config2?.link?.enabled!==!0){let existingPointer=readMemoryLinkPointer(directory);if(existingPointer)warn(`[memory-link] memory.link.enabled is false but a cohort pointer exists (linkId=${existingPointer.linkId}). Cohort memory is unreachable — run \`/swarm memory link\` or remove the pointer with \`/swarm memory unlink\`.`,{directory,linkId:existingPointer.linkId});return wrapLocalRoot(directory)}let pointer=readMemoryLinkPointer(directory);if(!pointer)return wrapLocalRoot(directory);let sharedDir=resolveMemoryStoreDir(directory),localSwarm=path42.join(directory,".swarm");if(sharedDir===localSwarm)return wrapLocalRoot(directory);return{kind:"cohort",cohortRoot:path42.join(sharedDir,"memory"),cohortId:pointer.cohortId??pointer.linkId,generation:pointer.generation??0,linkId:pointer.linkId,directory}}function wrapLocalRoot(directory){return log("[memory] wrapping raw directory as local vetted root — cohort sharing inactive for this caller",{directory}),{kind:"local",root:path42.join(directory,".swarm"),directory}}function isCohortRoot(root){return root.kind==="cohort"}function rootStoragePath(root){return root.kind==="cohort"?root.cohortRoot:path42.join(root.root,"memory")}var init_storage_root=__esm(()=>{init_logger();init_memory_link()});import{createHash as createHash15}from"node:crypto";import{existsSync as existsSync20,readFileSync as readFileSync19}from"node:fs";import*as path43 from"node:path";class MemoryGateway{context;config;provider;vettedRoot;now;disposed=!1;constructor(context,options={}){this.context=context;this.config=resolveMemoryConfig(options.config??DEFAULT_MEMORY_CONFIG),this.vettedRoot=resolveVettedMemoryRoot(context.directory,this.config),this.provider=options.provider??createConfiguredMemoryProviderForRoot(this.vettedRoot,this.config),this.now=options.now??(()=>new Date)}isEnabled(){return this.config.enabled}async dispose(){if(this.disposed)return;this.disposed=!0,await this.provider.close?.()}deriveAllowedScopes(){let resolvedRoot=path43.resolve(this.context.directory),repoId=createStableId(readGitRemoteUrl(resolvedRoot)??path43.basename(resolvedRoot)),scopes=[{type:"workspace",workspaceId:createStableId(path43.dirname(resolvedRoot))},{type:"repository",repoId,repoRoot:resolvedRoot}];if(isCohortRoot(this.vettedRoot))scopes.push({type:"cohort",cohortId:this.vettedRoot.cohortId});if(this.context.runId||this.context.sessionID)scopes.push({type:"run",runId:this.context.runId??this.context.sessionID});if(this.context.agentId||this.context.agentRole)scopes.push({type:"agent",agentId:this.context.agentId??this.context.agentRole,runId:this.context.runId??this.context.sessionID});return scopes}async recall(input){this.assertEnabled();let query=normalizeMemoryText(input.query);if(query.length<3)throw new MemoryValidationError("query must be at least 3 characters");let maxItems=clampInt(input.maxItems??this.config.recall.defaultMaxItems,1,20),tokenBudget=clampInt(input.tokenBudget??this.config.recall.defaultTokenBudget,100,5000),generatedAt=this.now().toISOString(),allowedScopes=this.deriveAllowedScopes(),scopes=input.scopes?validateRequestedScopes(input.scopes,allowedScopes):allowedScopes,request={query,task:input.task,agentRole:this.context.agentRole,mode:input.mode??"manual",scopes,kinds:input.kinds,maxItems,tokenBudget,minScore:input.minScore??this.config.recall.minScore,requireQuerySignal:input.requireQuerySignal,includeExpired:input.includeExpired},recallResult=this.provider.recallWithDiagnostics?await this.provider.recallWithDiagnostics(request):{items:await this.provider.recall(request)},bundle=toRecallBundle({id:createBundleId(query,generatedAt),query,generatedAt,items:recallResult.items,tokenBudget,diagnostics:recallResult.diagnostics?{injectionSkipReason:input.mode==="injection"?resolveInjectionSkipReason(recallResult.diagnostics):void 0,candidateCount:recallResult.diagnostics.candidateCount,preScoredFilteredCount:recallResult.diagnostics.preScoredFilteredCount,noSignalCount:recallResult.diagnostics.noSignalCount,belowThresholdCount:recallResult.diagnostics.belowThresholdCount}:void 0});return await this.provider.recordRecallUsage?.({bundleId:bundle.id,query,scopes,kinds:input.kinds,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate,agentRole:this.context.agentRole,runId:this.context.runId??this.context.sessionID,unitId:this.context.unitId,timestamp:generatedAt}),bundle}async propose(input){if(this.assertEnabled(),!this.provider.createProposal)throw new MemoryValidationError("memory provider does not support proposals");let redactedFields=new Set,redactProposalField=(field,value)=>{let redacted=redactSecrets(value);if(redacted!==value)redactedFields.add(field);return redacted},rationale=redactProposalField("rationale",normalizeMemoryText(input.rationale));if(!rationale)throw new MemoryValidationError("rationale is required");let evidenceRefs=(input.evidenceRefs??[]).map((ref)=>normalizeMemoryText(ref)).filter(Boolean).map((ref)=>redactProposalField("evidenceRefs",ref)).slice(0,20),needsRecord=input.operation==="add"||input.operation==="update"||input.operation==="supersede",proposedRecord,status="pending",reviewer,reviewedAt,rejectionReason,targetMemoryId=input.targetMemoryId===void 0?void 0:redactProposalField("targetMemoryId",normalizeMemoryText(input.targetMemoryId)),relatedMemoryIds=input.relatedMemoryIds?.map((id)=>redactProposalField("relatedMemoryIds",normalizeMemoryText(id))),proposalText=`${input.operation}:${targetMemoryId??""}`;if(needsRecord){if(!input.kind)throw new MemoryValidationError("kind is required for this operation");if(!input.text)throw new MemoryValidationError("text is required for this operation");proposalText=input.text;let normalizedText=normalizeMemoryText(input.text),redactedText=redactProposalField("text",normalizedText),extractedPaths=extractFilePaths(evidenceRefs),extractedSymbols=extractSymbols(evidenceRefs),recordMetadata={};if(extractedPaths.length>0)recordMetadata.files=extractedPaths;if(extractedSymbols.length>0)recordMetadata.symbols=extractedSymbols;proposedRecord=this.createRecord({kind:input.kind,text:redactedText,evidenceRefs,source:sourceFromEvidence(evidenceRefs,this.context),metadata:recordMetadata}),validateMemoryRecordRules(proposedRecord,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}if(redactedFields.size>0)status="rejected",reviewer="auto_policy",reviewedAt=this.now().toISOString(),rejectionReason=`proposal field(s) contained a likely secret and were redacted: ${Array.from(redactedFields).join(", ")}`;if((input.operation==="update"||input.operation==="delete"||input.operation==="supersede")&&!targetMemoryId)throw new MemoryValidationError(`${input.operation} proposals require targetMemoryId`);if(input.operation==="merge"&&(relatedMemoryIds??[]).length<2)throw new MemoryValidationError("merge proposals require relatedMemoryIds");let createdAt=this.now().toISOString(),proposer=this.context.agentId??this.context.agentRole??this.context.sessionID??"unknown",proposal={id:createProposalId({createdAt,proposer,text:proposalText}),operation:input.operation,proposedRecord,targetMemoryId,relatedMemoryIds,proposedBy:{agentRole:this.context.agentRole,agentId:this.context.agentId,runId:this.context.runId??this.context.sessionID},rationale,evidenceRefs,status,reviewer,reviewedAt,rejectionReason,createdAt,metadata:{}};return this.provider.createProposal(proposal)}async listMemories(filter={}){return this.assertEnabled(),this.provider.list(filter)}async listProposals(filter){if(this.assertEnabled(),!this.provider.listProposals)throw new MemoryValidationError("memory provider does not support proposals");return this.provider.listProposals(filter)}async listRecallUsage(filter){if(this.assertEnabled(),!this.provider.listRecallUsage)return[];return this.provider.listRecallUsage(filter)}async upsertCurated(record2){this.assertEnabled();let parsed=validateMemoryRecordRules(record2,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets});return this.provider.upsert(parsed)}async applyCuratorDecision(decision){if(this.assertEnabled(),!this.provider.applyCuratorDecision)throw new MemoryValidationError("memory provider does not support curator decisions");let parsed=validateCuratorMemoryDecision(decision),resolved=this.resolveCuratorDecision(parsed);return this.provider.applyCuratorDecision(resolved)}createRecord(input){let now=this.now().toISOString(),text=normalizeMemoryText(input.text),kind=input.kind,stability=input.stability??(kind==="scratch"?"ephemeral":"durable"),scope=this.resolveRecordScope(input.scope,stability),expiresAt=kind==="scratch"?new Date(this.now().getTime()+604800000).toISOString():void 0,recordBase={scope,kind,text};return{id:createMemoryId(recordBase),scope,kind,text,tags:normalizeTags2(input.tags??inferTags(text)),confidence:clamp(input.confidence??0.5,0,1),stability,source:input.source??sourceFromEvidence(input.evidenceRefs??[],this.context),createdAt:now,updatedAt:now,expiresAt,contentHash:computeMemoryContentHash(recordBase),metadata:input.metadata??{},cohortId:isCohortRoot(this.vettedRoot)?this.vettedRoot.cohortId:void 0,producerSessionId:this.context.sessionID,producerAgentRole:this.context.agentRole,redactionPolicyVersion:computeRedactionPolicyVersion(this.config.redaction.rejectDurableSecrets),providerVersion:this.provider.name}}resolveCuratorDecision(decision){switch(decision.action){case"add":return{action:"add",proposalId:decision.proposalId,memory:this.createRecordFromNew(decision.memory)};case"supersede":return{action:"supersede",proposalId:decision.proposalId,oldMemoryId:decision.oldMemoryId,replacement:this.createRecordFromNew(decision.replacement),reason:normalizeMemoryText(decision.reason)};case"update":{let patch=normalizeMemoryPatch(decision.patch);if(patch.scope)patch.scope=this.resolveRecordScope(patch.scope);return{action:"update",proposalId:decision.proposalId,targetMemoryId:decision.targetMemoryId,patch,reason:normalizeMemoryText(decision.reason)}}case"reject":case"noop":return{action:decision.action,proposalId:decision.proposalId,reason:normalizeMemoryText(decision.reason)}}}createRecordFromNew(input){let record2=this.createRecord({kind:input.kind,text:input.text,scope:input.scope,tags:input.tags,confidence:input.confidence,stability:input.stability,source:input.source,metadata:input.metadata}),next=input.expiresAt?{...record2,expiresAt:input.expiresAt}:record2;return validateMemoryRecordRules(next,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}resolveRecordScope(scope,stability){let allowedScopes=this.deriveAllowedScopes();if(!scope){let wantsCohort=stability!=="ephemeral"&&stability!=="session",cohortScope=allowedScopes.find((s)=>s.type==="cohort"),defaultScope=wantsCohort?cohortScope??allowedScopes[1]??allowedScopes[0]:allowedScopes[1]??allowedScopes[0];if(!defaultScope)throw new MemoryValidationError("memory scope is not available for this context");return defaultScope}return validateRequestedScopes([scope],allowedScopes,"memory scope is not allowed for this context"),scope}assertEnabled(){if(!this.config.enabled)throw new MemoryDisabledError}}function createMemoryGateway(context,options={}){return new MemoryGateway(context,options)}function createConfiguredMemoryProvider(directory,config2){let root=resolveVettedMemoryRoot(directory,config2);return createConfiguredMemoryProviderForRoot(root,config2)}function createConfiguredMemoryProviderForRoot(root,config2){if(config2.provider==="sqlite")return getOrCreateProviderForRoot(root,config2);let cohortRoot=root.kind==="cohort"?root.cohortRoot:null;return new LocalJsonlMemoryProvider(root.directory,config2,cohortRoot)}function sourceFromEvidence(evidenceRefs,context){let first=evidenceRefs[0];if(!first)return{type:"agent",createdBy:context.agentId??context.agentRole};if(/^https?:\/\//i.test(first))return{type:"web",url:first};if(/^[a-f0-9]{40}$/i.test(first))return{type:"commit",commitSha:first};let filePath=extractFilePaths(evidenceRefs)[0]??first;if(filePath!==first&&(filePath.includes("/")||filePath.includes("\\")||filePath.includes(".")))return{type:"file",filePath};if(first.includes("/")||first.includes("\\")||first.includes("."))return{type:"file",filePath:first};return{type:"manual",ref:first}}function createStableId(value){return createHash15("sha256").update(value.toLowerCase()).digest("hex").slice(0,16)}function readGitRemoteUrl(directory){if(gitRemoteUrlCache.has(directory))return gitRemoteUrlCache.get(directory);let gitConfigPath=path43.join(directory,".git","config");if(!existsSync20(gitConfigPath)){gitRemoteUrlCache.set(directory,void 0);return}try{let remoteUrl=readFileSync19(gitConfigPath,"utf-8").match(/\[remote "origin"\][\s\S]*?\n\s*url\s*=\s*(.+)/)?.[1]?.trim();return gitRemoteUrlCache.set(directory,remoteUrl),remoteUrl}catch{gitRemoteUrlCache.set(directory,void 0);return}}function validateRequestedScopes(requested,allowed,disallowedMessage="recall scope is not allowed for this context"){if(requested.length===0)throw new MemoryValidationError("recall scopes must not be empty");let allowedKeys=new Set(allowed.map(scopeKey));for(let scope of requested)if(!allowedKeys.has(scopeKey(scope)))throw new MemoryValidationError(disallowedMessage);return requested}function resolveInjectionSkipReason(diagnostics){if(diagnostics.returnedCount>0)return;if(diagnostics.candidateCount===0)return"no_results";let signalEligibleCount=diagnostics.candidateCount-diagnostics.preScoredFilteredCount-diagnostics.suppressedLowQCount;if(signalEligibleCount>0&&diagnostics.noSignalCount>0&&diagnostics.noSignalCount>=signalEligibleCount)return"no_signal";if(diagnostics.belowThresholdCount>0)return"below_threshold";return"no_results"}function scopeKey(scope){return JSON.stringify({type:scope.type,userId:scope.userId,workspaceId:scope.workspaceId,projectId:scope.projectId,repoId:scope.repoId,repoRoot:scope.repoRoot?path43.resolve(scope.repoRoot):void 0,runId:scope.runId,agentId:scope.agentId,cohortId:scope.cohortId})}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function clampInt(value,min,max){return Math.trunc(clamp(value,min,max))}function normalizeTags2(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}function normalizeMemoryPatch(patch){return{...patch,text:patch.text===void 0?void 0:normalizeMemoryText(patch.text),tags:patch.tags===void 0?void 0:normalizeTags2(patch.tags)}}function inferTags(text){let lower=text.toLowerCase(),tags=[];for(let[tag,pattern]of[["testing",/\b(test|spec|bun|jest|vitest)\b/],["tooling",/\b(pnpm|npm|yarn|bun|biome|eslint|typescript)\b/],["security",/\b(security|auth|token|secret|password|csp)\b/],["api",/\b(api|endpoint|graphql|rest|sdk)\b/],["architecture",/\b(architecture|decision|adr|pattern)\b/],["failure",/\b(fail|failure|regression|flaky|timeout)\b/]])if(pattern.test(lower))tags.push(tag);return tags}function extractFilePaths(refs){let seen=new Set,paths=[];for(let ref of refs){FILE_PATH_REGEX.lastIndex=0;let matches=ref.match(FILE_PATH_REGEX);if(!matches)continue;for(let m of matches)if(!seen.has(m)){if(seen.add(m),paths.push(m),paths.length>=20)return paths}}return paths}function extractSymbols(refs){let seen=new Set,symbols=[],identRegex=/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g;for(let ref of refs){identRegex.lastIndex=0;let matches=ref.match(identRegex);if(!matches)continue;for(let m of matches)if(m.length>=3&&!seen.has(m)&&!RESERVED_IDENTIFIERS.has(m)){if(seen.add(m),symbols.push(m),symbols.length>=20)return symbols}}return symbols}var gitRemoteUrlCache,FILE_PATH_REGEX,RESERVED_IDENTIFIERS;var init_gateway=__esm(()=>{init_config2();init_errors4();init_local_jsonl_provider();init_prompt_block();init_provider_pool();init_redaction();init_schema2();init_storage_root();gitRemoteUrlCache=new Map;FILE_PATH_REGEX=/\b(?:src|tests|test|docs|scripts|packages|lib|config|examples|internal|cmd|pkg|bin|tools|cli|api|server|client|app|core|utils|hooks|services|commands|agents|memory)\/[A-Za-z0-9._/@+-]+/g,RESERVED_IDENTIFIERS=new Set(["const","let","var","function","class","interface","type","async","await","return","if","else","for","while","do","switch","case","break","continue","new","this","super","extends","implements","import","export","from","default","try","catch","finally","throw","typeof","instanceof","in","of","as","yield","static","get","set","readonly","public","private","protected"])});async function applyCouncilReward(provider,opts){let bundles=await provider.listRecallUsage?.({runId:opts.runId})??[];if(bundles.length===0)return{memoriesRewarded:0};let attributedBundles=bundles.filter((bundle)=>bundle.unitId==null||opts.unitId==null||bundle.unitId===opts.unitId),distinctIds=new Set;for(let bundle of attributedBundles)for(let id of bundle.memoryIds)distinctIds.add(id);let result=await(provider.withTransaction?provider.withTransaction(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates}):(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates})()),memoriesRewarded=result.size,rewardedRecords=[...result.values()].map(({rec})=>rec);try{await propagateReward(provider,opts,rewardedRecords,distinctIds)}catch(err){log(`[memory:propagation] skipped after error: ${err instanceof Error?err.message:String(err)}`)}return{memoriesRewarded}}async function propagateReward(provider,opts,sources,directlyRewardedIds){if(sources.length===0)return;let qConfig=opts.qLearning??DEFAULT_QLEARNING_CONFIG,fraction=qConfig.propagationFraction,fanoutCap=qConfig.propagationFanoutCap,windowDays=qConfig.propagationWindowDays,relatednessThreshold=qConfig.propagationRelatednessThreshold;if(!Number.isFinite(fraction)||fraction<=0)return;if(!Number.isFinite(fanoutCap)||fanoutCap<=0)return;if(!Number.isFinite(windowDays)||windowDays<=0)return;if(!Number.isFinite(relatednessThreshold))return;if(typeof provider.list!=="function")return;let nowMs=Date.parse(opts.timestamp);if(!Number.isFinite(nowMs))return;let windowMs=windowDays*MS_PER_DAY2,recencyById=await buildRetrievalRecency(provider,nowMs);if(!recencyById)return;let orderedSources=[...sources].sort((a,b)=>a.id.localeCompare(b.id)),scheduled=new Map,listCache=new Map;for(let source of orderedSources){let scopeKey2=stableScopeKey(source.scope),cacheKey=`${scopeKey2}::${source.kind}`,candidates=listCache.get(cacheKey);if(!candidates)candidates=await provider.list({scopes:[source.scope],kinds:[source.kind]}),listCache.set(cacheKey,candidates);let sourceTokens=tokenize(source.text),qualified=[];for(let cand of candidates){if(cand.id===source.id)continue;if(directlyRewardedIds.has(cand.id))continue;if(stableScopeKey(cand.scope)!==scopeKey2)continue;if(cand.kind!==source.kind)continue;let retrievedAt=recencyById.get(cand.id);if(retrievedAt===void 0)continue;if(nowMs-retrievedAt>windowMs)continue;let overlap2=jaccard(sourceTokens,tokenize(cand.text));if(overlap2<relatednessThreshold)continue;qualified.push({record:cand,overlap:overlap2})}qualified.sort((a,b)=>b.overlap-a.overlap||a.record.id.localeCompare(b.record.id));let cap=Math.trunc(fanoutCap),selected=qualified.slice(0,cap),dropped=qualified.length-selected.length;if(dropped>0)log(`[memory:propagation] fan-out cap reached for source ${source.id}: ${qualified.length} qualified, ${selected.length} propagated, ${dropped} dropped by cap ${cap}`);for(let{record:record2}of selected)if(!scheduled.has(record2.id))scheduled.set(record2.id,record2)}for(let record2 of scheduled.values()){let qBefore=getQValue(record2,opts.initialQValue),qAfter=applyPropagatedEmaUpdate(qBefore,opts.reward,opts.eta,fraction);await provider.upsert(setQValue(record2,qAfter)),await provider.appendRewardEvent?.({memoryId:record2.id,runId:opts.runId,unitId:opts.unitId,verdict:`${opts.verdictLabel??"APPROVE"}${PROPAGATED_VERDICT_SUFFIX}`,reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp})}}function truncateObjectForJson(obj,capBytes){let asIs=JSON.stringify(obj);if(asIs.length<=capBytes)return obj;if(JSON.stringify({...obj,__truncated__:!0}).length<=capBytes)return{...obj,__truncated__:!0};return{__truncated__:!0,originalSize:asIs.length,cap:capBytes}}async function buildRetrievalRecency(provider,nowMs){if(typeof provider.listRecallUsage!=="function")return null;let since=new Date(nowMs-RECENCY_WINDOW_MS).toISOString(),usage=await provider.listRecallUsage({since,limit:RECENCY_EVENT_LIMIT})??[],recency=new Map;for(let event of usage){let ts=Date.parse(event.timestamp);if(!Number.isFinite(ts))continue;for(let id of event.memoryIds){let prev=recency.get(id);if(prev===void 0||ts>prev)recency.set(id,ts)}}return recency}var PROPAGATED_VERDICT_SUFFIX="_PROPAGATED",MS_PER_DAY2=86400000,RECENCY_WINDOW_MS,RECENCY_EVENT_LIMIT=1000;var init_reward_capture=__esm(()=>{init_logger();init_config2();init_schema2();init_scoring();RECENCY_WINDOW_MS=30*MS_PER_DAY2});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win323){return win323===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state.prefix="./";return output};exports.wrapOutput=(input,state={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path44,{windows}={})=>{let segs=path44.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state.maxDepth=0,!isPathSeparator(code))tokens.push(token);state.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state.maxDepth+=tokens[tokens.length-1].depth}state.slashes=slashes,state.parts=parts}return state};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants3=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants3,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants3.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse5=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants3.globChars(opts.windows),EXTGLOB_CHARS=constants3.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state.index===len-1,peek=state.peek=(n=1)=>input[state.index+n],advance=state.advance=()=>input[++state.index]||"",remaining=()=>input.slice(state.index+1),consume=(value2="",num=0)=>{state.consumed+=value2,state.index+=num},append=(token)=>{state.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state.start++,count++;if(count%2===0)return!1;return state.negated=!0,state.start++,!0},increment=(type)=>{state[type]++,stack.push(type)},decrement=(type)=>{state[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state.output=state.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state.parens,token.output=state.output,token.startIndex=state.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal2=input.slice(token.startIndex,state.index+1),body=input.slice(token.startIndex+2,state.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open3=tokens[token.tokensIndex];open3.type="text",open3.value=literal2,open3.output=safeOutput||utils.escapeRegex(literal2);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state.output=token.output+open3.output,state.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse5(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc2,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc2)return esc2+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc2)return esc2+first+(rest?star:"");return star}return esc2?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state.output=input,state;return state.output=utils.wrapOutput(output,state,options),state}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state.brackets===0){push({type:"text",value});continue}}if(state.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix4=POSIX_REGEX_SOURCE[rest2];if(posix4){if(prev.value=pre+posix4,state.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state.quotes=state.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state.output=state.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open3={type:"brace",value,output:"(",outputIndex:state.output.length,tokensIndex:state.tokens.length};braces.push(open3),push(open3);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state.output.slice(0,brace.outputIndex),toks=state.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state.output=out;for(let t of toks)state.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state.index===state.start+1){state.start=state.index+1,state.consumed="",state.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state.braces+state.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state.backtrack=!0,state.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state.output=prev.output,state.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state.output=state.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state.globstar=!0,state.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state.output=state.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state.output+=prior.output+prev.output,state.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state.output=prev.output,state.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state.output=state.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state.output+=prev.output,state.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state.index===state.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state.output+=nodot,prev.output+=nodot;if(peek()!=="*")state.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state.output=utils.escapeLast(state.output,"["),decrement("brackets")}while(state.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state.output=utils.escapeLast(state.output,"("),decrement("parens")}while(state.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state.output=utils.escapeLast(state.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state.backtrack===!0){state.output="";for(let token of state.tokens)if(state.output+=token.output!=null?token.output:token.value,token.suffix)state.output+=token.suffix}return state};parse5.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants3.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse5});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse5=require_parse(),utils=require_utils(),constants3=require_constants(),isObject2=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state2=isMatch(str);if(state2)return state2}return!1}}let isState=isObject2(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix4=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix4}),result={glob,state,regex,posix:posix4,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix4}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix4?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix4);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse5(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state.output})${append}`;if(state&&state.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse5.fastpaths(input,options);if(!parsed.output)parsed=parse5(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants3;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache){let item=cache.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count=1){let requested=Number(count);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}import*as fsSync5 from"node:fs";import*as path44 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let sortedKeys=Object.keys(args2).sort();return Number(bunHash(JSON.stringify(args2,sortedKeys)))}catch(error49){return log("[Guardrails] hashArgs failed",{error:error49 instanceof Error?error49.message:String(error49)}),0}}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached2=pathNormalizationCache.get(cacheKey);if(cached2!==void 0)return cached2;try{let absolutePath=path44.isAbsolute(filePath)?filePath:path44.resolve(cwd,filePath),normalized=fsSync5.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path44.isAbsolute(filePath)?filePath:path44.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached2=globMatcherCache.get(cacheKey);if(cached2!==void 0)return cached2;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path44.resolve(cwd),normalizedTarget=path44.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path44.relative(normalizedCwd,current);if(rel===""||rel.startsWith(".."))break;ancestors.push(current);let parent=path44.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat8=null;try{stat8=fsSync5.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat8.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink — writing through a symlink could redirect the write outside the working directory`}return null}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path44){return pathLib.parse(targetAbsolute).root!==pathLib.parse(cwdAbsolute).root}function isInDeclaredScope(filePath,scopeEntries,cwd){let dir=cwd??process.cwd(),caseInsensitive=process.platform==="win32",resolvedFileRaw=path44.resolve(dir,filePath),resolvedFile=caseInsensitive?resolvedFileRaw.toLowerCase():resolvedFileRaw;return scopeEntries.some((scope)=>{let resolvedScopeRaw=path44.resolve(dir,scope),resolvedScope=caseInsensitive?resolvedScopeRaw.toLowerCase():resolvedScopeRaw;if(resolvedFile===resolvedScope)return!0;let rel=path44.relative(resolvedScope,resolvedFile);return rel.length>0&&!rel.startsWith("..")&&!path44.isAbsolute(rel)})}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),normalizedPath,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path44.resolve(dir,normalizedWithSymlinks),normalizedPath=path44.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path44.resolve(dir,filePath),normalizedPath=path44.relative(dir,resolvedTarget).replace(/\\/g,"/")}if(isOnDifferentFilesystemRoot(resolvedTarget,dir))return{allowed:!1,reason:`Path blocked: ${filePath} is on a different drive/root than the working directory`};if(normalizedPath===".."||normalizedPath.startsWith("../"))return{allowed:!1,reason:`Path blocked: ${normalizedPath} resolves outside the working directory`};let rules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent];if(!rules)return{allowed:!1,reason:`Unknown agent: ${agentName}`};if(rules.readOnly)return{allowed:!1,reason:`Path blocked: ${normalizedPath} (agent ${normalizedAgent} is read-only)`};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(normalizedPath===blocked)return{allowed:!1,reason:`Path blocked (exact): ${normalizedPath}`}}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(getGlobMatcher(glob)(normalizedPath))return{allowed:!1,reason:`Path blocked (glob ${glob}): ${normalizedPath}`}}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>normalizedPath===allowed))return{allowed:!0}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath);if(rules.blockedZones.includes(zone))return{allowed:!1,reason:`Path blocked: ${normalizedPath} is in ${zone} zone`,zone}}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some((glob)=>{return getGlobMatcher(glob)(normalizedPath)}))return{allowed:!0}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath)}))return{allowed:!0}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(normalizedPath.startsWith(prefix))return{allowed:!1,reason:`Path blocked: ${normalizedPath} is under ${prefix}`}}if(!((normalizedAgent==="coder"||strippedAgent==="coder")&&options?.declaredScope!=null&&options.declaredScope.length>0&&isInDeclaredScope(normalizedPath,options.declaredScope,dir))){if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>normalizedPath.startsWith(prefix)))return{allowed:!1,reason:`Path ${normalizedPath} not in allowed list for ${normalizedAgent}`}}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return{allowed:!1,reason:`Path ${normalizedPath} not in allowed list for ${normalizedAgent}`}}return{allowed:!0}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),options)}var import_picomatch,pathNormalizationCache,globMatcherCache,DEFAULT_AGENT_AUTHORITY_RULES;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_utils();init_bun_compat();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200});DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}}});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&&QUOTA_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;session.pendingAdvisoryMessages??=[];let rejections=input.rejectionCount??0,resolutionPath;if(rejections>=3)resolutionPath="soundingboard",session.pendingAdvisoryMessages.push(`CONFLICT ESCALATION: ${input.sourceAgent} vs ${input.targetAgent} on task ${input.taskId??"unknown"}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`);else resolutionPath="self_resolve",session.pendingAdvisoryMessages.push(`CONFLICT DETECTED: ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${input.taskId??"unknown"}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`);let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state2();init_telemetry()});function extractCurrentPhase(planContent){if(!planContent)return null;let lines=planContent.split(`
534
534
  `);for(let i=0;i<Math.min(20,lines.length);i++){let progressMatch=lines[i].trim().match(/^## Phase (\d+):?\s*(.*?)\s*\[IN PROGRESS\]/i);if(progressMatch){let phaseNum=progressMatch[1],description=progressMatch[2]?.trim()||"";return`Phase ${phaseNum}: ${description} [IN PROGRESS]`}}for(let i=0;i<Math.min(3,lines.length);i++){let phaseMatch=lines[i].trim().match(/Phase:\s*(\d+)/i);if(phaseMatch)return`Phase ${phaseMatch[1]} [PENDING]`}return null}function extractCurrentTask(planContent){if(!planContent)return null;let lines=planContent.split(`
535
535
  `),inCurrentPhase=!1;for(let line of lines){if(line.startsWith("## ")&&/\[IN PROGRESS\]/i.test(line)){inCurrentPhase=!0;continue}if(inCurrentPhase){if(line.startsWith("## ")||line.trim()==="---")break;if(line.trim().startsWith("- [ ]"))return line.trim()}}return null}function extractDecisions(contextContent,maxChars=500){if(!contextContent)return null;let lines=contextContent.split(`
536
536
  `),decisionsText="",inDecisionsSection=!1;for(let line of lines){if(line.trim()==="## Decisions"){inDecisionsSection=!0;continue}if(inDecisionsSection){if(line.startsWith("## "))break;if(line.startsWith("- "))decisionsText+=`${line}
@@ -1618,10 +1618,17 @@ Flags:
1618
1618
  `).filter((line)=>line.trim()!==""),directivesIssued=[],consumedIds=new Set;for(let line of lines)try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directivesIssued.push(parsed.directiveId);if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}let unconsumed=directivesIssued.filter((id)=>!consumedIds.has(id));if(unconsumed.length===0)return{name:"Steering Directives",status:"✅",detail:"All steering directives acknowledged (or none issued)"};return{name:"Steering Directives",status:"❌",detail:`${unconsumed.length} steering directive(s) not yet acknowledged`}}catch{return{name:"Steering Directives",status:"❌",detail:"Could not read events.jsonl"}}}async function checkCurator(directory){try{if(!loadPluginConfig(directory).curator?.enabled)return{name:"Curator",status:"✅",detail:"Disabled (enable via curator.enabled)"};let summaryPath=path102.join(directory,".swarm/curator-summary.json");if(!existsSync49(summaryPath))return{name:"Curator",status:"✅",detail:"Enabled, no summary yet (waiting for first phase)"};try{let content=readFileSync32(summaryPath,"utf-8"),parsed=JSON.parse(content);if(typeof parsed.schema_version!=="number"||parsed.schema_version!==1)return{name:"Curator",status:"❌",detail:`curator-summary.json has invalid schema_version (expected 1, got ${JSON.stringify(parsed.schema_version)})`};let phaseInfo=parsed.last_phase_covered!==void 0?`phase ${parsed.last_phase_covered}`:"unknown phase",timeInfo=parsed.last_updated?`, updated ${parsed.last_updated}`:"";return{name:"Curator",status:"✅",detail:`Summary present — covering ${phaseInfo}${timeInfo}`}}catch(err){return{name:"Curator",status:"❌",detail:`curator-summary.json is corrupt or invalid: ${err instanceof Error?err.message:"Unknown error"}`}}}catch(err){return{name:"Curator",status:"❌",detail:`Could not check curator state: ${err instanceof Error?err.message:"Unknown error"}`}}}async function getSandboxStatus(){try{let capability=await _internals65.detectSandboxCapability(),mechanism=capability.mechanism??"none",executor=await _internals65.getSandboxExecutor();if(executor!==null){let executorStrength=executor?.strength;if((executorStrength==="weak"||executorStrength==="advisory"?"advisory":capability.strength??executorStrength??"strong")==="advisory")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | Available: advisory only | Strength: ADVISORY (env-scrub, NOT kernel-enforced) | Commands are NOT strongly sandboxed`};return{name:"Sandbox",status:"✅",detail:`Mechanism: ${mechanism.toLowerCase()} | Available: yes | Strength: strong (kernel-enforced) | Sandboxing commands: yes`}}if(mechanism!=="none")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | Available: no (silent pass-through) | Commands NOT sandboxed`};return{name:"Sandbox",status:"⬜",detail:`Mechanism: ${mechanism.toLowerCase()} | Commands not sandboxed`}}catch(error93){return{name:"Sandbox",status:"⬜",detail:`Sandbox status unknown (${error93 instanceof Error?error93.message:"Unknown error"})`}}}async function getDiagnoseData(directory){let checks5=[],versionCache=readVersionCache(),versionDetail=version4,versionStatus="✅";if(versionCache?.npmLatest){let ageMs=Date.now()-versionCache.checkedAt,ageMin=Math.max(0,Math.round(ageMs/60000));if(compareVersions(versionCache.npmLatest,version4)>0)versionStatus="⚠️",versionDetail=`${version4} (npm latest: ${versionCache.npmLatest}, checked ${ageMin}m ago) `+"— run `bunx opencode-swarm update` to refresh";else versionDetail=`${version4} (npm latest: ${versionCache.npmLatest}, checked ${ageMin}m ago)`}checks5.push({name:"Version",status:versionStatus,detail:versionDetail});let plan=await loadPlanJsonOnly(directory);if(plan){if(checks5.push({name:"plan.json",status:"✅",detail:"Valid schema (v1.0.0)"}),plan.migration_status==="migrated")checks5.push({name:"Migration",status:"✅",detail:"Plan was migrated from legacy plan.md"});else if(plan.migration_status==="migration_failed")checks5.push({name:"Migration",status:"❌",detail:"Migration from plan.md failed — review manually"});let dagResult=validateTaskDag(plan);if(dagResult.valid)checks5.push({name:"Task DAG",status:"✅",detail:"All dependencies resolved"});else checks5.push({name:"Task DAG",status:"❌",detail:`Missing dependencies: ${dagResult.missingDeps.join(", ")}`});let evidenceCheck=await checkEvidenceCompleteness(directory,plan);checks5.push(evidenceCheck)}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(planContent){let hasPhases=/^## Phase \d+/m.test(planContent),hasTasks=/^- \[[ x]\]/m.test(planContent);if(hasPhases&&hasTasks)checks5.push({name:"plan.md",status:"✅",detail:"Found with valid phase structure"});else checks5.push({name:"plan.md",status:"❌",detail:"Found but missing phase/task structure"})}else checks5.push({name:"plan.md",status:"❌",detail:"Not found"})}if(await readSwarmFileAsync(directory,"context.md"))checks5.push({name:"context.md",status:"✅",detail:"Found"});else checks5.push({name:"context.md",status:"❌",detail:"Not found"});try{if(loadPluginConfig(directory))checks5.push({name:"Plugin config",status:"✅",detail:"Valid configuration loaded"});else checks5.push({name:"Plugin config",status:"✅",detail:"Using defaults (no custom config)"})}catch{checks5.push({name:"Plugin config",status:"❌",detail:"Invalid configuration"})}checks5.push(await checkSwarmIdentity(plan)),checks5.push(await checkPhaseBoundaries(plan)),checks5.push(await checkOrphanedEvidence(directory,plan)),checks5.push(await checkPlanSync(directory,plan)),checks5.push(await checkConfigBackups(directory)),checks5.push(await checkGitRepository(directory)),checks5.push(await getSandboxStatus()),checks5.push(await checkSpecStaleness(directory,plan)),checks5.push(await checkConfigParseability(directory)),checks5.push(await checkGrammarWasmFiles()),checks5.push(await checkCheckpointManifest(directory)),checks5.push(await checkEventStreamIntegrity(directory)),checks5.push(await checkSteeringDirectives(directory)),checks5.push(await checkCurator(directory)),checks5.push(await checkKnowledgeHealth(directory));try{let evidenceDir=path102.join(directory,".swarm","evidence"),snapshotFiles=existsSync49(evidenceDir)?readdirSync9(evidenceDir).filter((f)=>f.startsWith("agent-tools-")&&f.endsWith(".json")):[];if(snapshotFiles.length>0){let latest=snapshotFiles.sort().pop();checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:`${snapshotFiles.length} snapshot(s) found — latest: ${latest}`})}else checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:"No snapshots yet (snapshots written on next session start)"})}catch{checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:"No snapshots yet (snapshots written on next session start)"})}if(getDeferredWarnings().length>0)checks5.push({name:"Deferred Warnings",status:"⚠️",detail:`${getDeferredWarnings().length} warning(s) deferred from init — see the Deferred Warnings section below (or set OPENCODE_SWARM_DEBUG=1 for full detail)`});let cachePaths=getPluginCachePaths(),cacheRows=[];for(let cachePath of cachePaths)try{if(!existsSync49(cachePath)){cacheRows.push(`⬜ ${cachePath} — absent`);continue}let packageRoot=resolveCachePackageRoot(cachePath),cacheLabel=packageRoot===cachePath?cachePath:`${cachePath} -> ${packageRoot}`,missingGrammarAssets=REQUIRED_CACHE_GRAMMAR_ASSETS.filter((file3)=>!existsSync49(path102.join(packageRoot,"dist","lang","grammars",file3))),pkgJsonPath=path102.join(packageRoot,"package.json");try{let raw=readFileSync32(pkgJsonPath,"utf-8"),parsed=JSON.parse(raw),installedVersion=typeof parsed.version==="string"?parsed.version:"?";if(missingGrammarAssets.length>0){cacheRows.push(`⚠️ ${cacheLabel} — v${installedVersion}, missing grammar assets: ${missingGrammarAssets.join(", ")}; run \`bunx opencode-swarm update\` and restart OpenCode`);continue}cacheRows.push(`✅ ${cacheLabel} — v${installedVersion}`)}catch{cacheRows.push(`⚠️ ${cacheLabel} — present (package.json unreadable)`)}}catch{cacheRows.push(`⚠️ ${cachePath} — status unknown (read error)`)}let hasCacheEntry=cacheRows.some((r)=>r.startsWith("✅")),cacheStatus2=cacheRows.some((r)=>r.startsWith("⚠️"))?"⚠️":hasCacheEntry?"✅":"⬜";checks5.push({name:"Plugin Caches",status:cacheStatus2,detail:cacheRows.join(" | ")});let passCount=checks5.filter((c)=>c.status==="✅"||c.status==="⬜").length,totalCount=checks5.length;return{checks:checks5,passCount,totalCount,allPassed:passCount===totalCount,deferredWarnings:getDeferredWarnings()}}function formatDiagnoseMarkdown(diagnose){let lines=["## Swarm Health Check","",...diagnose.checks.map((c)=>`- ${c.status} **${c.name}**: ${c.detail}`),"",`**Result**: ${diagnose.allPassed?"✅ All checks passed":`⚠️ ${diagnose.passCount}/${diagnose.totalCount} checks passed`}`];if(diagnose.deferredWarnings.length>0){lines.push(""),lines.push("## Deferred Warnings"),lines.push("");for(let warning of diagnose.deferredWarnings)lines.push(`- ${warning}`)}return lines.join(`
1619
1619
  `)}async function handleDiagnoseCommand(directory,_args){let diagnoseData=await getDiagnoseData(directory);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals65;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_gate_bridge();init_manager2();init_utils2();init_manager();init_capability_probe();init_executor();init_effective_spec();init_knowledge_diagnostics();init_version_check();init_warning_buffer();({version:version4}=package_default),sandboxCapabilityProbe=new SandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS=["tree-sitter.wasm","tree-sitter-javascript.wasm","tree-sitter-typescript.wasm"];_internals65={detectSandboxCapability:()=>sandboxCapabilityProbe.detect(),getSandboxExecutor:getExecutor}});var init_diagnose=__esm(()=>{init_diagnose_service()});var exports_config_doctor={};__export(exports_config_doctor,{writeDoctorArtifact:()=>writeDoctorArtifact,writeBackupArtifact:()=>writeBackupArtifact,shouldRunOnStartup:()=>shouldRunOnStartup,runConfigDoctorWithFixes:()=>runConfigDoctorWithFixes,runConfigDoctor:()=>runConfigDoctor,restoreFromBackup:()=>restoreFromBackup,removeStraySwarmDir:()=>removeStraySwarmDir,readDoctorArtifact:()=>readDoctorArtifact,getConfigPaths:()=>getConfigPaths,detectStraySwarmDirs:()=>detectStraySwarmDirs,createConfigBackup:()=>createConfigBackup,applySafeAutoFixes:()=>applySafeAutoFixes});import*as crypto7 from"node:crypto";import*as fs43 from"node:fs";import*as os19 from"node:os";import*as path103 from"node:path";function levenshteinDistance(a,b){let al=a.length,bl=b.length,matrix=[];for(let i=0;i<=al;i++)matrix[i]=[i];for(let j=0;j<=bl;j++)matrix[0][j]=j;for(let i=1;i<=al;i++)for(let j=1;j<=bl;j++){let cost=a[i-1]===b[j-1]?0:1;matrix[i][j]=Math.min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+cost)}return matrix[al][bl]}function emitObjectTypeMismatch(key,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key}-type`,title:`Invalid ${key} type`,description:`"${key}" must be an object, got ${typeof value}`,severity:"error",path:key,currentValue:value,autoFixable:!1})}function isPlainObject5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function collectRawGatesConfigFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs43.existsSync(configPath))continue;try{if(fs43.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs43.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.gates===void 0)continue;if(!isPlainObject5(raw.gates)){findings.push({id:"invalid-gates-config",title:"Invalid gates config",description:`"gates" in ${configPath} must be an object. The loader ignores that section and keeps other valid config sections active.`,severity:"error",path:"gates",currentValue:raw.gates,autoFixable:!1});continue}for(let[sectionName,sectionValue]of Object.entries(raw.gates)){let schema=GateConfigSchema.shape[sectionName];if(!schema){findings.push({id:"unknown-gates-section",title:"Unknown gates config section",description:`Unknown gates section "gates.${sectionName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1});continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[sectionName];if(knownFields&&isPlainObject5(sectionValue)){let knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(sectionValue))if(!knownFieldSet.has(fieldName))findings.push({id:"unknown-gates-key",title:"Unknown gates config key",description:`Unknown gates key "gates.${sectionName}.${fieldName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}.${fieldName}`,currentValue:sectionValue[fieldName],autoFixable:!1})}if(!schema.safeParse(sectionValue).success)findings.push({id:"invalid-gates-section",title:"Invalid gates config section",description:`"gates.${sectionName}" in ${configPath} failed validation. The loader uses defaults for that gate section and keeps other valid config sections active.`,severity:"error",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1})}}catch{}}return findings}function collectRawStrictSectionFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs43.existsSync(configPath))continue;try{if(fs43.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs43.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;let seen=new Set;for(let issue3 of parsed.error.issues){if(issue3.code!=="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let keys=issue3.keys??[];for(let key of keys){let dotted=[...issue3.path.map(String),key].join(".");if(seen.has(dotted))continue;seen.add(dotted),findings.push({id:"unknown-config-key",title:"Unknown config key",description:`Unrecognized key "${dotted}" in ${configPath} is ignored by the loader (the rest of your config is preserved). Fix or remove it.`,severity:"warn",path:dotted,currentValue:void 0,autoFixable:!1})}}}catch{}}return findings}function getRawValueAtPath(raw,issuePath){let node=raw;for(let seg of issuePath){if(node===null||typeof node!=="object")return;node=node[seg]}return node}function collectRawValueConstraintFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory),applyTargetPath=fs43.existsSync(projectConfigPath)?projectConfigPath:userConfigPath,seen=new Set,filesInApplyOrder=applyTargetPath===projectConfigPath?[projectConfigPath,userConfigPath]:[userConfigPath,projectConfigPath];for(let configPath of filesInApplyOrder){if(!fs43.existsSync(configPath))continue;try{if(fs43.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs43.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;for(let issue3 of parsed.error.issues){if(issue3.code==="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let dotted=issue3.path.map(String).join("."),dedupeKey=`${dotted}|${issue3.code}`;if(seen.has(dedupeKey))continue;seen.add(dedupeKey);let current=getRawValueAtPath(raw,issue3.path);if(issue3.code==="too_big"&&dotted.endsWith("fallback_models")&&Array.isArray(current)&&current.length>FALLBACK_MODELS_MAX){let trimmed=current.slice(0,FALLBACK_MODELS_MAX),dropped=current.slice(FALLBACK_MODELS_MAX).map(String),inApplyTarget=configPath===applyTargetPath,drop=`${dropped.length} entr${dropped.length===1?"y":"ies"}`;findings.push({id:"fallback-models-too-many",title:"Too many fallback models",description:`"${dotted}" in ${configPath} lists ${current.length} models; the maximum is ${FALLBACK_MODELS_MAX}. A config that fails validation is discarded in favor of safe defaults. `+(inApplyTarget?`Run /swarm config doctor --fix to trim to the first ${FALLBACK_MODELS_MAX} (drops ${drop}: ${dropped.join(", ")}), or edit the file yourself.`:`Remove ${drop} from that file (would drop: ${dropped.join(", ")}).`),severity:"error",path:dotted,currentValue:current,autoFixable:inApplyTarget,proposedFix:{type:"update",path:dotted,value:trimmed,description:`Trim "${dotted}" to the first ${FALLBACK_MODELS_MAX} models`,risk:"low",lossy:!0}});continue}findings.push({id:"invalid-config-value",title:"Invalid config value",description:`"${dotted||"(root)"}" in ${configPath} is invalid: ${issue3.message}. A config that fails validation is discarded in favor of safe defaults until this is fixed.`,severity:"error",path:dotted,currentValue:current,autoFixable:!1})}}catch{}}return findings}function emitWorktreeIsolationLayeringAdvisory(config3,findings){let parallelization=config3.parallelization,worktreePolicy=config3.worktree?.policy??"auto";if(parallelization?.enabled===!0&&(parallelization.maxConcurrentTasks??1)>1&&worktreePolicy!=="disabled")findings.push({id:"worktree-isolation-baseline-active",title:"Worktree isolation is already active for standard parallel coders",description:"Standard parallel coders already use baseline worktree isolation through the parallel execution profile plus top-level worktree.policy. Lean Turbo and Epic are additive strategies, not requirements for obtaining worktree isolation.",severity:"warn",path:"worktree.policy",currentValue:worktreePolicy,autoFixable:!1})}function getUserConfigDir3(){return process.env.XDG_CONFIG_HOME||path103.join(os19.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path103.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path103.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto7.createHash("sha256").update(content,"utf-8").digest("hex")}function isValidConfigPath(configPath,directory){let pathParts=configPath.replace(/\\/g,"/").split("/");for(let part of pathParts)if(part===".."||part===""){if(part==="..")return!1}let{userConfigPath,projectConfigPath}=getConfigPaths(directory);try{let resolvedConfig=path103.resolve(configPath),resolvedUser=path103.resolve(userConfigPath),resolvedProject=path103.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs43.existsSync(resolvedConfig)){if(fs43.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs43.writeFileSync(tmpPath,content,"utf-8");try{fs43.renameSync(tmpPath,filePath)}catch{try{fs43.unlinkSync(filePath)}catch{}fs43.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs43.existsSync(projectConfigPath))try{content=fs43.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs43.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs43.readFileSync(userConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] user config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}}if(content===null)return null;return{createdAt:Date.now(),configPath,content,contentHash:computeHash(content)}}function writeBackupArtifact(directory,backup){let swarmDir=path103.join(directory,".swarm");if(!fs43.existsSync(swarmDir))fs43.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path103.join(swarmDir,backupFilename),artifact={createdAt:backup.createdAt,configPath:backup.configPath,contentHash:backup.contentHash,content:backup.content,preview:backup.content.substring(0,500)+(backup.content.length>500?"...":"")};return atomicWriteFileSync(backupPath,JSON.stringify(artifact,null,2)),backupPath}function restoreFromBackup(backupPath,directory){if(!fs43.existsSync(backupPath))return null;let swarmDir=path103.resolve(path103.join(directory,".swarm")),resolvedBackup=path103.resolve(backupPath);if(!resolvedBackup.startsWith(swarmDir+path103.sep)&&resolvedBackup!==swarmDir)return null;try{let artifact=JSON.parse(fs43.readFileSync(backupPath,"utf-8"));if(!artifact.content||!artifact.configPath||!artifact.contentHash)return null;if(!isValidConfigPath(artifact.configPath,directory))return null;let computedHash=computeHash(artifact.content),storedHash=artifact.contentHash;if(!/^\d+$/.test(storedHash)&&computedHash!==storedHash)return null;log("[ConfigDoctor] Warning: restoring from backup with legacy numeric hash (pre-SHA-256). Consider re-backing up.",{});let targetPath=artifact.configPath,targetDir=path103.dirname(targetPath);if(!fs43.existsSync(targetDir))fs43.mkdirSync(targetDir,{recursive:!0});return atomicWriteFileSync(targetPath,artifact.content),targetPath}catch{return null}}function readConfigFromFile(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent=null;if(fs43.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs43.readFileSync(projectConfigPath,"utf-8");else if(fs43.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs43.readFileSync(userConfigPath,"utf-8");if(configContent===null)return null;try{return{config:JSON.parse(configContent),configPath}}catch(error93){return log(`[ConfigDoctor] Failed to parse config file: ${configPath}`,{error:error93 instanceof Error?error93.message:String(error93)}),null}}function validateConfigKey(path104,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path104===depPath&&!depInfo.isDefaultValue(value))findings.push({id:"deprecated-field",title:`Deprecated config field: ${depPath}`,description:`Config field "${depPath}" is deprecated. Replacement: ${depInfo.replacement}.`,severity:"info",path:depPath,currentValue:value,autoFixable:!1});switch(path104){case"agents":{if(value!==void 0)findings.push({id:"deprecated-agents-config",title:"Deprecated agents configuration",description:'The "agents" field is deprecated. Use "swarms" instead for multi-swarm support.',severity:"warn",path:"agents",currentValue:value,autoFixable:!1,proposedFix:{type:"remove",path:"agents",description:"Remove deprecated agents config - use swarms instead",risk:"low"}});break}case"guardrails.enabled":{if(value===!1)findings.push({id:"guardrails-disabled",title:"Guardrails disabled",description:"Guardrails have been explicitly disabled. This removes safety limits.",severity:"error",path:"guardrails.enabled",currentValue:value,autoFixable:!1});break}case"guardrails.profiles":{let profiles=value;if(profiles){let validAgents=new Set(ALL_AGENT_NAMES);for(let[agentName,profile]of Object.entries(profiles))if(!validAgents.has(agentName))findings.push({id:"unknown-agent-profile",title:"Unknown agent profile",description:`Profile for unknown agent "${agentName}" will be ignored.`,severity:"info",path:`guardrails.profiles.${agentName}`,currentValue:profile,autoFixable:!0,proposedFix:{type:"remove",path:`guardrails.profiles.${agentName}`,description:`Remove unknown agent profile "${agentName}"`,risk:"low"}})}break}case"automation.mode":{let validModes=["manual","hybrid","auto"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-automation-mode",title:"Invalid automation mode",description:`Invalid automation mode "${value}". Valid: ${validModes.join(", ")}`,severity:"error",path:"automation.mode",currentValue:value,autoFixable:!0,proposedFix:{type:"update",path:"automation.mode",value:"manual",description:'Reset to safe default "manual"',risk:"low"}});break}case"automation.capabilities":{let caps=value;if(caps){let capabilityNames=["plan_sync","phase_preflight","config_doctor_on_startup","evidence_auto_summaries","decision_drift_detection"];for(let[name,capValue]of Object.entries(caps))if(capabilityNames.includes(name)&&typeof capValue!=="boolean")findings.push({id:"invalid-capability-type",title:"Invalid capability type",description:`Capability "${name}" must be boolean, got ${typeof capValue}`,severity:"error",path:`automation.capabilities.${name}`,currentValue:capValue,autoFixable:!0,proposedFix:{type:"update",path:`automation.capabilities.${name}`,value:!1,description:`Reset capability "${name}" to false`,risk:"low"}})}break}case"hooks":{if(emitObjectTypeMismatch("hooks",value,findings),value!==void 0&&typeof value==="object"&&!Array.isArray(value)&&value!==null){let hooks=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks))if(!validHooks.includes(hookName))findings.push({id:"unknown-hook-field",title:"Unknown hook configuration",description:`Unknown hook "${hookName}" will be ignored.`,severity:"info",path:`hooks.${hookName}`,currentValue:hooks[hookName],autoFixable:!0,proposedFix:{type:"remove",path:`hooks.${hookName}`,description:`Remove unknown hook "${hookName}"`,risk:"low"}})}break}case"max_iterations":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-iterations",title:"max_iterations out of bounds",description:`max_iterations must be 1-10, got ${numValue}`,severity:"error",path:"max_iterations",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"max_iterations",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"qa_retry_limit":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-retry-limit",title:"qa_retry_limit out of bounds",description:`qa_retry_limit must be 1-10, got ${numValue}`,severity:"error",path:"qa_retry_limit",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"qa_retry_limit",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"swarms":{if(value!==void 0){if(typeof value!=="object"||Array.isArray(value)||value===null){findings.push({id:"invalid-swarms-type",title:"Invalid swarms type",description:`"swarms" must be an object, got ${typeof value}`,severity:"error",path:"swarms",currentValue:value,autoFixable:!1});break}let swarms=value;if(Object.keys(swarms).length===0)findings.push({id:"empty-swarms",title:"Empty swarms configuration",description:'The "swarms" field is an empty object. No swarm configurations are defined.',severity:"info",path:"swarms",autoFixable:!1});for(let swarmId of Object.keys(swarms))if(swarmId.includes("..")||swarmId.includes("/")||swarmId.includes("\\")||swarmId.includes("\x00"))findings.push({id:"swarm-id-path-traversal",title:"Path traversal in swarm ID",description:`Swarm ID "${swarmId}" contains path traversal characters.`,severity:"error",path:`swarms.${swarmId}`,autoFixable:!1});let validAgents=new Set(ALL_AGENT_NAMES);for(let[swarmId,swarmConfig]of Object.entries(swarms)){let swarm=swarmConfig;if(swarm.agents&&typeof swarm.agents==="object")for(let[agentName]of Object.entries(swarm.agents)){let baseName=stripKnownSwarmPrefix(agentName);if(baseName!==agentName&&agentName.startsWith(`${swarmId}_`)&&validAgents.has(baseName))findings.push({id:"prefixed-swarm-agent-override",title:"Prefixed agent override is ignored",description:`Agent "${agentName}" in swarm "${swarmId}" uses a generated agent name. Per-swarm overrides must use the canonical key "${baseName}", e.g. "swarms.${swarmId}.agents.${baseName}.model". Otherwise the override is ignored and the agent falls back to its default model.`,severity:"warn",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1});else if(!validAgents.has(baseName))findings.push({id:"unknown-swarm-agent",title:"Unknown agent in swarm",description:`Agent "${agentName}" in swarm "${swarmId}" may not be recognized.`,severity:"info",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1})}}}break}case"default_agent":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-default_agent-type",title:"Invalid default_agent type",description:`"default_agent" must be a string, got ${typeof value}`,severity:"error",path:"default_agent",currentValue:value,autoFixable:!1});break}case"auto_select_architect":{if(value!==void 0&&typeof value!=="boolean"&&typeof value!=="string")findings.push({id:"invalid-auto_select_architect-type",title:"Invalid auto_select_architect type",description:`"auto_select_architect" must be a boolean or string, got ${typeof value}`,severity:"error",path:"auto_select_architect",currentValue:value,autoFixable:!1});break}case"pipeline":{emitObjectTypeMismatch("pipeline",value,findings);break}case"phase_complete":{emitObjectTypeMismatch("phase_complete",value,findings);break}case"execution_mode":{let validModes=["strict","balanced","fast"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-execution_mode-type",title:"Invalid execution_mode",description:`"execution_mode" must be one of: ${validModes.join(", ")}, got "${value}"`,severity:"error",path:"execution_mode",currentValue:value,autoFixable:!1});break}case"inject_phase_reminders":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-inject_phase_reminders-type",title:"Invalid inject_phase_reminders type",description:`"inject_phase_reminders" must be a boolean, got ${typeof value}`,severity:"error",path:"inject_phase_reminders",currentValue:value,autoFixable:!1});break}case"gates":{emitObjectTypeMismatch("gates",value,findings);break}case"context_budget":{emitObjectTypeMismatch("context_budget",value,findings);break}case"pricing":{emitObjectTypeMismatch("pricing",value,findings);break}case"guardrails":{emitObjectTypeMismatch("guardrails",value,findings);break}case"watchdog":{emitObjectTypeMismatch("watchdog",value,findings);break}case"self_review":{emitObjectTypeMismatch("self_review",value,findings);break}case"tool_filter":{emitObjectTypeMismatch("tool_filter",value,findings);break}case"authority":{emitObjectTypeMismatch("authority",value,findings);break}case"plan_cursor":{emitObjectTypeMismatch("plan_cursor",value,findings);break}case"context_map":{emitObjectTypeMismatch("context_map",value,findings);break}case"evidence":{emitObjectTypeMismatch("evidence",value,findings);break}case"summaries":{emitObjectTypeMismatch("summaries",value,findings);break}case"auto_review":{emitObjectTypeMismatch("auto_review",value,findings);break}case"repo_graph":{emitObjectTypeMismatch("repo_graph",value,findings);break}case"review_passes":{emitObjectTypeMismatch("review_passes",value,findings);break}case"adversarial_detection":{emitObjectTypeMismatch("adversarial_detection",value,findings);break}case"adversarial_testing":{emitObjectTypeMismatch("adversarial_testing",value,findings);break}case"integration_analysis":{emitObjectTypeMismatch("integration_analysis",value,findings);break}case"docs":{emitObjectTypeMismatch("docs",value,findings);break}case"design_docs":{emitObjectTypeMismatch("design_docs",value,findings);break}case"ui_review":{emitObjectTypeMismatch("ui_review",value,findings);break}case"compaction_advisory":{emitObjectTypeMismatch("compaction_advisory",value,findings);break}case"lint":{emitObjectTypeMismatch("lint",value,findings);break}case"secretscan":{emitObjectTypeMismatch("secretscan",value,findings);break}case"checkpoint":{emitObjectTypeMismatch("checkpoint",value,findings);break}case"apply_patch":{emitObjectTypeMismatch("apply_patch",value,findings);break}case"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",value,findings);break}case"curator":{emitObjectTypeMismatch("curator",value,findings);break}case"architectural_supervision":{emitObjectTypeMismatch("architectural_supervision",value,findings);break}case"knowledge_application":{emitObjectTypeMismatch("knowledge_application",value,findings);break}case"skillPropagation":{emitObjectTypeMismatch("skillPropagation",value,findings);break}case"skill_improver":{emitObjectTypeMismatch("skill_improver",value,findings);break}case"skills":{emitObjectTypeMismatch("skills",value,findings);break}case"spec_writer":{emitObjectTypeMismatch("spec_writer",value,findings);break}case"tool_output":{emitObjectTypeMismatch("tool_output",value,findings);break}case"slop_detector":{emitObjectTypeMismatch("slop_detector",value,findings);break}case"todo_gate":{emitObjectTypeMismatch("todo_gate",value,findings);break}case"incremental_verify":{emitObjectTypeMismatch("incremental_verify",value,findings);break}case"compaction_service":{emitObjectTypeMismatch("compaction_service",value,findings);break}case"prm":{emitObjectTypeMismatch("prm",value,findings);break}case"council":{emitObjectTypeMismatch("council",value,findings);break}case"parallelization":{emitObjectTypeMismatch("parallelization",value,findings);break}case"worktree":{emitObjectTypeMismatch("worktree",value,findings);break}case"turbo":{emitObjectTypeMismatch("turbo",value,findings);break}case"turbo_mode":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-turbo_mode-type",title:"Invalid turbo_mode type",description:`"turbo_mode" must be a boolean, got ${typeof value}`,severity:"error",path:"turbo_mode",currentValue:value,autoFixable:!1});break}case"quiet":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-quiet-type",title:"Invalid quiet type",description:`"quiet" must be a boolean, got ${typeof value}`,severity:"error",path:"quiet",currentValue:value,autoFixable:!1});break}case"version_check":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-version_check-type",title:"Invalid version_check type",description:`"version_check" must be a boolean, got ${typeof value}`,severity:"error",path:"version_check",currentValue:value,autoFixable:!1});break}case"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}default:{let topLevel=path104.split(".")[0];if(KNOWN_TOP_LEVEL_KEYS.has(topLevel))break;let MAX_SUGGESTION_KEY_LENGTH=100,lowerTopLevel=topLevel.toLowerCase(),suggestion,matchCount=0;if(lowerTopLevel.length<=MAX_SUGGESTION_KEY_LENGTH){for(let knownKey of KNOWN_TOP_LEVEL_KEYS)if(levenshteinDistance(lowerTopLevel,knownKey.toLowerCase())<=2){if(matchCount++,matchCount===1)suggestion=knownKey}}if(matchCount===1&&suggestion)findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path104}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path104,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path104}" is not in the schema.`,severity:"warn",path:path104,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path104,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path104&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path104,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path104,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path104}`,description:`Config value at "${path104}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path104,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path104,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path104}[${index}]`,findings,visited)});return}for(let[key,value]of Object.entries(obj)){let newPath=path104?`${path104}.${key}`:key;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory){let findings=[];walkConfigAndValidate(config3,"",findings),findings.push(...collectRawGatesConfigFindings(directory)),findings.push(...collectRawStrictSectionFindings(directory)),findings.push(...collectRawValueConstraintFindings(directory)),emitWorktreeIsolationLayeringAdvisory(config3,findings);let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length},hasAutoFixableIssues=findings.some((f)=>f.autoFixable&&f.proposedFix?.risk==="low"),{userConfigPath,projectConfigPath}=getConfigPaths(directory),configSource="defaults";if(fs43.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs43.existsSync(userConfigPath))configSource=userConfigPath;return{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe2(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result,options={}){let applyLossy=options.applyLossy===!0,appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs43.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs43.readFileSync(projectConfigPath,"utf-8");else if(fs43.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs43.readFileSync(userConfigPath,"utf-8");else return{appliedFixes,updatedConfigPath:null};let config3;try{config3=JSON.parse(configContent)}catch{return{appliedFixes,updatedConfigPath:null}}let safeFixes=result.findings.filter((f)=>f.autoFixable&&f.proposedFix?.risk==="low"&&(applyLossy||!f.proposedFix?.lossy));for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe2(fix.path))continue;let pathParts=fix.path.split("."),current=config3,navigated=!0;for(let i=0;i<pathParts.length-1;i++){let part=pathParts[i];if(current===null||current===void 0){navigated=!1;break}if(typeof current!=="object"||Array.isArray(current)){navigated=!1;break}let obj=current;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null){navigated=!1;break}else if(typeof obj[part]!=="object"){navigated=!1;break}current=obj[part]}if(!navigated)continue;let lastPart=pathParts[pathParts.length-1];switch(fix.type){case"remove":if(current!==null&&current!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(appliedFixes.length>0){let configDir=path103.dirname(configPath);if(!fs43.existsSync(configDir))fs43.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path103.join(directory,".swarm","config-doctor.json");if(!fs43.existsSync(artifactPath))return null;let content=fs43.readFileSync(artifactPath,"utf-8"),artifact=JSON.parse(content),summary=artifact.summary;if(!summary||typeof summary!=="object")return null;let{info:infoVal,warn:warnVal,error:errorVal}=summary;if(typeof infoVal!=="number"||!Number.isFinite(infoVal)||typeof warnVal!=="number"||!Number.isFinite(warnVal)||typeof errorVal!=="number"||!Number.isFinite(errorVal))return null;let ts=artifact.timestamp;if(typeof ts!=="number"||!Number.isFinite(ts))return null;let findingsCount=infoVal+warnVal+errorVal,findings=artifact.findings,autoFixableCount=Array.isArray(findings)?findings.filter((f)=>f.autoFixable===!0).length:0;return{timestamp:new Date(ts).toISOString(),findingsCount,autoFixableCount}}catch{return null}}function writeDoctorArtifact(directory,result){let swarmDir=path103.join(directory,".swarm");if(!fs43.existsSync(swarmDir))fs43.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path103.join(swarmDir,"config-doctor.json"),guiOutput={timestamp:result.timestamp,summary:result.summary,hasAutoFixableIssues:result.hasAutoFixableIssues,configSource:result.configSource,findings:result.findings.map((f)=>({id:f.id,title:f.title,description:f.description,severity:f.severity,path:f.path,autoFixable:f.autoFixable,proposedFix:f.proposedFix?{type:f.proposedFix.type,path:f.proposedFix.path,description:f.proposedFix.description,risk:f.proposedFix.risk,lossy:f.proposedFix.lossy===!0}:null}))};return atomicWriteFileSync(artifactPath,JSON.stringify(guiOutput,null,2)),artifactPath}function shouldRunOnStartup(automationConfig){if(!automationConfig)return!1;if(automationConfig.mode==="manual")return!1;return automationConfig.capabilities?.config_doctor_on_startup===!0}async function runConfigDoctorWithFixes(directory,config3,autoFix=!1,options={}){let result=runConfigDoctor(config3,directory),artifactPath=writeDoctorArtifact(directory,result);if(!autoFix)return{result,backupPath:null,appliedFixes:[],updatedConfigPath:null,artifactPath};let backup=createConfigBackup(directory),backupPath=null;if(backup)backupPath=writeBackupArtifact(directory,backup);let{appliedFixes,updatedConfigPath}=applySafeAutoFixes(directory,result,options);if(appliedFixes.length>0){let freshConfig=readConfigFromFile(directory);if(freshConfig){let newResult=runConfigDoctor(freshConfig.config,directory);writeDoctorArtifact(directory,newResult)}}return{result,backupPath,appliedFixes,updatedConfigPath,artifactPath}}function detectStraySwarmDirs(projectRoot){let findings=[],SKIP_DIRS=new Set(["node_modules",".git","dist",".cache",".next","coverage",".turbo",".vercel",".terraform","__pycache__",".tox"]),MAX_DEPTH2=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries;try{entries=fs43.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path103.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path103.join(fullPath,".git");try{let gitStat=fs43.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path103.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs43.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path103.relative(projectRoot,fullPath).replace(/\\/g,"/"),absolutePath:fullPath,contents:contents.slice(0,20),totalEntries:contents.length});continue}walk(fullPath,depth+1)}}return walk(projectRoot,0),findings}function removeStraySwarmDir(projectRoot,strayPath){let canonicalRoot,canonicalStray;try{canonicalRoot=fs43.realpathSync(projectRoot),canonicalStray=fs43.realpathSync(path103.isAbsolute(strayPath)?strayPath:path103.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path103.join(canonicalRoot,".swarm");if(canonicalStray===rootSwarm||canonicalStray===canonicalRoot)return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!canonicalStray.startsWith(canonicalRoot+path103.sep))return{success:!1,message:"Path is outside project root — refusing to remove"};if(!canonicalStray.replace(/\\/g,"/").endsWith("/.swarm"))return{success:!1,message:"Path is not a .swarm directory — refusing to remove"};try{return fs43.rmSync(canonicalStray,{recursive:!0,force:!0}),{success:!0,message:`Removed stray .swarm directory: ${canonicalStray}`}}catch(err){return{success:!1,message:`Failed to remove: ${err instanceof Error?err.message:String(err)}`}}}var CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES=102400,KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_schema();init_utils();KNOWN_TOP_LEVEL_KEYS=new Set(Object.keys(PluginConfigSchema.shape)),DEPRECATED_FIELDS=new Map([["skill_improver.model",{message:"deprecated",replacement:"agents.skill_improver.model",isDefaultValue:(v)=>v===null}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0}]]);DANGEROUS_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"])});class LanguageRegistry{profiles;extensionIndex;constructor(){this.profiles=new Map,this.extensionIndex=new Map}unregister(id){let profile=this.profiles.get(id);if(!profile)return;if(this.profiles.delete(id),!profile.parserOnly){for(let ext of profile.extensions)if(this.extensionIndex.get(ext)===id)this.extensionIndex.delete(ext)}}register(profile){let existing=this.profiles.get(profile.id);if(existing&&existing!==profile)throw Error(`LanguageRegistry: profile id "${profile.id}" registered twice. Each LanguageProfile.id must be unique. Got: ${profile.displayName} vs existing ${existing.displayName}.`);if(!profile.parserOnly)for(let ext of profile.extensions){let claimedBy=this.extensionIndex.get(ext);if(claimedBy&&claimedBy!==profile.id)throw Error(`LanguageRegistry: extension "${ext}" registered by both "${claimedBy}" and "${profile.id}". A non-parserOnly profile must not collide on extensions. If both languages legitimately share an extension, mark one parserOnly: true.`);this.extensionIndex.set(ext,profile.id)}this.profiles.set(profile.id,profile)}get(id){return this.profiles.get(id)}getById(id){return this.profiles.get(id)}getByExtension(ext){let profileId=this.extensionIndex.get(ext);if(profileId)return this.profiles.get(profileId);return}getAll(){return Array.from(this.profiles.values())}getTier(tier){return Array.from(this.profiles.values()).filter((p)=>p.tier===tier)}}var LANGUAGE_REGISTRY;var init_profiles=__esm(()=>{LANGUAGE_REGISTRY=new LanguageRegistry;LANGUAGE_REGISTRY.register({id:"typescript",displayName:"TypeScript",tier:1,extensions:[".ts",".tsx"],treeSitter:{grammarId:"typescript",wasmFile:"tree-sitter-typescript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"npx tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"npx vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"npx jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"npx mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"npx eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"javascript",displayName:"JavaScript",tier:1,extensions:[".js",".jsx",".mjs",".cjs"],treeSitter:{grammarId:"javascript",wasmFile:"tree-sitter-javascript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"npx tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"npx vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"npx jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"npx mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"npx eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"python",displayName:"Python",tier:1,extensions:[".py",".pyw"],treeSitter:{grammarId:"python",wasmFile:"tree-sitter-python.wasm",commentNodes:["comment"]},build:{detectFiles:["setup.py","pyproject.toml","setup.cfg"],commands:[{name:"pip install",cmd:"pip install -e .",detectFile:"setup.py",priority:10},{name:"build",cmd:"python -m build",detectFile:"pyproject.toml",priority:9}]},test:{detectFiles:["pytest.ini","pyproject.toml","setup.cfg","conftest.py"],frameworks:[{name:"pytest",detect:"pytest.ini",cmd:"pytest",priority:10},{name:"unittest",detect:"setup.py",cmd:"python -m unittest discover",priority:8}]},lint:{detectFiles:["pyproject.toml",".ruff.toml","setup.cfg"],linters:[{name:"ruff",detect:"pyproject.toml",cmd:"ruff check --fix .",priority:10},{name:"flake8",detect:"setup.cfg",cmd:"flake8 .",priority:8}]},audit:{detectFiles:["requirements.txt","Pipfile.lock","pyproject.toml"],command:"pip-audit --format json",outputFormat:"json"},sast:{nativeRuleSet:"python",semgrepSupport:"ga"},prompts:{coderConstraints:["Use type annotations on all function signatures (PEP 484)","Prefer f-strings over .format() or % formatting","Use pathlib.Path over os.path for filesystem operations","Never use bare except:; catch specific exception types","Follow PEP 8 style; max line length 120 characters"],reviewerChecklist:["Verify type annotations are present on all public functions","Check for bare except clauses or overly broad exception handling","Confirm no mutable default arguments (def f(x=[]) anti-pattern)","Validate f-string usage and no format string injection risks","Check imports are organized (stdlib → third-party → local)"]}});LANGUAGE_REGISTRY.register({id:"rust",displayName:"Rust",tier:1,extensions:[".rs"],treeSitter:{grammarId:"rust",wasmFile:"tree-sitter-rust.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["Cargo.toml"],commands:[{name:"cargo build",cmd:"cargo build",detectFile:"Cargo.toml",priority:10},{name:"cargo check",cmd:"cargo check",detectFile:"Cargo.toml",priority:9}]},test:{detectFiles:["Cargo.toml"],frameworks:[{name:"cargo",detect:"Cargo.toml",cmd:"cargo test",priority:10}]},lint:{detectFiles:["Cargo.toml"],linters:[{name:"clippy",detect:"Cargo.toml",cmd:"cargo clippy --fix --allow-dirty",priority:10},{name:"rustfmt",detect:"Cargo.toml",cmd:"cargo fmt",priority:9}]},audit:{detectFiles:["Cargo.lock"],command:"cargo audit --json",outputFormat:"json"},sast:{nativeRuleSet:"rust",semgrepSupport:"ga"},prompts:{coderConstraints:["Prefer owned types over references where ownership is clear; use lifetimes sparingly","Use Result<T, E> and ? operator for error propagation; never unwrap() in library code","Prefer iterators and combinators over explicit loops","Derive standard traits (Debug, Clone, PartialEq) whenever sensible","Avoid unsafe blocks; document any unsafe usage with SAFETY comments"],reviewerChecklist:["Verify no unwrap() or expect() calls in library/production paths","Check for potential panics in indexing, arithmetic overflow, or slice operations","Confirm error types implement std::error::Error and are propagated correctly","Validate lifetime annotations are minimal and correct","Check unsafe blocks have SAFETY comments explaining invariants"]}});LANGUAGE_REGISTRY.register({id:"go",displayName:"Go",tier:1,extensions:[".go"],treeSitter:{grammarId:"go",wasmFile:"tree-sitter-go.wasm",commentNodes:["comment"]},build:{detectFiles:["go.mod"],commands:[{name:"go build",cmd:"go build ./...",detectFile:"go.mod",priority:10},{name:"go vet",cmd:"go vet ./...",detectFile:"go.mod",priority:9}]},test:{detectFiles:["go.mod"],frameworks:[{name:"go-test",detect:"go.mod",cmd:"go test ./...",priority:10}]},lint:{detectFiles:["go.mod",".golangci.yml",".golangci.yaml"],linters:[{name:"golangci-lint",detect:".golangci.yml",cmd:"golangci-lint run --fix",priority:10},{name:"gofmt",detect:"go.mod",cmd:"gofmt -w .",priority:9}]},audit:{detectFiles:["go.mod"],command:"govulncheck -json ./...",outputFormat:"json"},sast:{nativeRuleSet:"go",semgrepSupport:"ga"},prompts:{coderConstraints:["Always check and return errors; never discard error return values","Use idiomatic Go error wrapping with fmt.Errorf and %w verb","Prefer table-driven tests; use t.Run for subtests","Avoid global mutable state; use dependency injection via interfaces","Use context.Context as first parameter for all I/O-bound functions"],reviewerChecklist:["Verify all error return values are checked (no _ = err pattern)","Check goroutine usage — confirm no goroutine leaks or missing WaitGroups","Validate context propagation through call chains","Confirm exported types/functions have doc comments","Check for data races in concurrent code (verify sync usage)"]}});LANGUAGE_REGISTRY.register({id:"java",displayName:"Java",tier:2,extensions:[".java"],treeSitter:{grammarId:"java",wasmFile:"tree-sitter-java.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],commands:[{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:8}]},test:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],frameworks:[{name:"maven",detect:"pom.xml",cmd:"mvn test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["checkstyle.xml","pom.xml"],linters:[{name:"checkstyle",detect:"checkstyle.xml",cmd:"mvn checkstyle:check",priority:10}]},audit:{detectFiles:["pom.xml","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"java",semgrepSupport:"ga"},prompts:{coderConstraints:["Use checked exceptions for recoverable conditions; unchecked for programming errors","Prefer composition over inheritance; favor interfaces over abstract classes","Use Optional<T> for nullable return values rather than returning null","Follow Java naming conventions: PascalCase classes, camelCase methods/fields","Close resources in try-with-resources blocks; never rely on finalizers"],reviewerChecklist:["Check for unclosed resources — verify try-with-resources or explicit close()","Verify null checks are present for all external/injected dependencies","Confirm thread safety for shared mutable state (synchronized, volatile, atomic)","Validate exception handling — no swallowed exceptions or empty catch blocks","Check for proper equals()/hashCode() overrides on value objects"]}});LANGUAGE_REGISTRY.register({id:"kotlin",displayName:"Kotlin",tier:2,extensions:[".kt",".kts"],treeSitter:{grammarId:"kotlin",wasmFile:"tree-sitter-kotlin.wasm",commentNodes:["line_comment","multiline_comment"]},build:{detectFiles:["build.gradle.kts","build.gradle","pom.xml"],commands:[{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:8}]},test:{detectFiles:["build.gradle.kts","build.gradle"],frameworks:[{name:"gradle",detect:"build.gradle.kts",cmd:"gradle test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["build.gradle.kts","build.gradle"],linters:[{name:"ktlint",detect:"build.gradle.kts",cmd:"ktlint --format",priority:10}]},audit:{detectFiles:["build.gradle.kts","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"beta"},prompts:{coderConstraints:["Prefer val over var; use data classes for value objects","Use Kotlin coroutines for async operations; avoid blocking calls on Dispatchers.Main","Leverage extension functions instead of utility classes","Use sealed classes for exhaustive when expressions","Avoid platform types; always declare explicit nullability in API surfaces"],reviewerChecklist:["Verify no non-null assertions (!!) in production code without justification","Check coroutine scope lifecycle — confirm scopes are cancelled when no longer needed","Validate when expressions are exhaustive (sealed class coverage)","Confirm data class equals/hashCode/copy semantics are appropriate","Check for blocking I/O on the wrong coroutine dispatcher"]}});LANGUAGE_REGISTRY.register({id:"csharp",displayName:"C# / .NET",tier:2,extensions:[".cs",".csx"],treeSitter:{grammarId:"csharp",wasmFile:"tree-sitter-c-sharp.wasm",commentNodes:["comment"]},build:{detectFiles:["*.csproj","*.sln","Directory.Build.props"],commands:[{name:"dotnet build",cmd:"dotnet build -v quiet",detectFile:"*.csproj",priority:10},{name:"dotnet build sln",cmd:"dotnet build -v quiet",detectFile:"*.sln",priority:9}]},test:{detectFiles:["*.csproj","*.sln"],frameworks:[{name:"dotnet-test",detect:"*.csproj",cmd:"dotnet test",priority:10}]},lint:{detectFiles:["*.csproj",".editorconfig"],linters:[{name:"dotnet-format",detect:"*.csproj",cmd:"dotnet format",priority:10}]},audit:{detectFiles:["*.csproj","packages.lock.json"],command:"dotnet list package --vulnerable --include-transitive",outputFormat:"text"},sast:{nativeRuleSet:"csharp",semgrepSupport:"ga"},prompts:{coderConstraints:["Use async/await throughout; avoid .Result or .Wait() which can deadlock","Prefer records for immutable value types; use struct only for small value types","Use nullable reference types (NRT) — enable <Nullable>enable</Nullable>","Dispose IDisposable resources with using statements or declarations","Follow C# naming conventions: PascalCase for public members, _camelCase for private fields"],reviewerChecklist:["Verify no .Result or .Wait() calls that could cause deadlocks","Check all IDisposable are properly disposed (using / IAsyncDisposable)","Confirm nullable reference type annotations are present and correct","Validate LINQ queries do not cause N+1 query patterns in EF contexts","Check for missing ConfigureAwait(false) in library code"]}});LANGUAGE_REGISTRY.register({id:"cpp",displayName:"C / C++",tier:2,extensions:[".c",".h",".cpp",".hpp",".cc",".cxx"],treeSitter:{grammarId:"cpp",wasmFile:"tree-sitter-cpp.wasm",commentNodes:["comment"]},build:{detectFiles:["CMakeLists.txt","Makefile","meson.build"],commands:[{name:"cmake",cmd:"cmake --build build",detectFile:"CMakeLists.txt",priority:10},{name:"make",cmd:"make",detectFile:"Makefile",priority:9},{name:"meson",cmd:"meson compile -C builddir",detectFile:"meson.build",priority:8}]},test:{detectFiles:["CMakeLists.txt"],frameworks:[{name:"ctest",detect:"CMakeLists.txt",cmd:"ctest --test-dir build",priority:10}]},lint:{detectFiles:[".clang-tidy","CMakeLists.txt"],linters:[{name:"cppcheck",detect:"CMakeLists.txt",cmd:"cppcheck --error-exitcode=1 .",priority:10},{name:"clang-tidy",detect:".clang-tidy",cmd:"clang-tidy -p build",priority:9}]},audit:{detectFiles:["CMakeLists.txt","vcpkg.json","conanfile.txt"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"cpp",semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer RAII and smart pointers (unique_ptr, shared_ptr) over raw pointers","Use const-correctness throughout; mark all non-mutating methods const","Avoid undefined behaviour: no out-of-bounds access, no use-after-free","Initialize all variables; prefer in-class initializers for member variables","Use std::array or std::vector instead of C-style arrays"],reviewerChecklist:["Verify no raw owning pointers; confirm smart pointer ownership semantics","Check for memory leaks — every new has a corresponding delete or smart pointer","Validate bounds checking on all array/buffer accesses","Confirm no undefined behavior patterns (signed overflow, strict aliasing violations)","Check thread safety for shared data (mutex, atomic, lock-free patterns)"]}});LANGUAGE_REGISTRY.register({id:"swift",displayName:"Swift",tier:2,extensions:[".swift"],treeSitter:{grammarId:"swift",wasmFile:"tree-sitter-swift.wasm",commentNodes:["comment","multiline_comment"]},build:{detectFiles:["Package.swift","*.xcodeproj","*.xcworkspace"],commands:[{name:"swift build",cmd:"swift build",detectFile:"Package.swift",priority:10},{name:"xcodebuild",cmd:"xcodebuild build -quiet",detectFile:"*.xcodeproj",priority:9}]},test:{detectFiles:["Package.swift","*.xcodeproj"],frameworks:[{name:"swift-test",detect:"Package.swift",cmd:"swift test",priority:10},{name:"xcodebuild-test",detect:"*.xcodeproj",cmd:"xcodebuild test -quiet",priority:9}]},lint:{detectFiles:[".swiftlint.yml","Package.swift"],linters:[{name:"swiftlint",detect:".swiftlint.yml",cmd:"swiftlint --fix",priority:10}]},audit:{detectFiles:["Package.resolved","Package.swift"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer value types (structs, enums) over classes; use classes only for reference semantics","Use Swift concurrency (async/await, actors) over GCD for new code","Avoid force unwrap (!) and force cast (as!); use guard let or if let","Use Swift Package Manager for dependencies where possible","Mark types and methods as final when subclassing is not intended"],reviewerChecklist:["Verify no force unwraps (!) or force casts (as!) in production code","Check for retain cycles in closures — confirm [weak self] where needed","Validate Swift concurrency usage — no data races across actor boundaries","Confirm proper error handling with do-try-catch or Result<T,E>","Check value vs reference type choice is appropriate for the use case"]}});LANGUAGE_REGISTRY.register({id:"dart",displayName:"Dart / Flutter",tier:3,extensions:[".dart"],treeSitter:{grammarId:"dart",wasmFile:"tree-sitter-dart.wasm",commentNodes:["comment","documentation_comment"]},build:{detectFiles:["pubspec.yaml"],commands:[{name:"flutter build",cmd:"flutter build apk",detectFile:"pubspec.yaml",priority:10},{name:"dart compile",cmd:"dart compile exe .",detectFile:"pubspec.yaml",priority:9}]},test:{detectFiles:["pubspec.yaml"],frameworks:[{name:"flutter test",detect:"pubspec.yaml",cmd:"flutter test",priority:10},{name:"dart test",detect:"pubspec.yaml",cmd:"dart test",priority:9}]},lint:{detectFiles:["analysis_options.yaml","pubspec.yaml"],linters:[{name:"dart analyze",detect:"pubspec.yaml",cmd:"dart analyze",priority:10}]},audit:{detectFiles:["pubspec.yaml","pubspec.lock"],command:"dart pub outdated --json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"none"},prompts:{coderConstraints:["Use null safety features — prefer late, required, and ? annotations over dynamic","Follow Dart effective style: lowerCamelCase for variables, UpperCamelCase for types","Prefer const constructors where possible for performance","Use async/await over raw Future callbacks","Separate business logic from UI widgets; use BLoC or Provider patterns"],reviewerChecklist:["Verify null safety annotations are correct (no unnecessary ?)","Check that const constructors are used where the widget tree is static","Confirm async operations handle error states (catchError or try-catch)","Validate no direct UI state mutation outside setState or stream","Check for platform-specific code isolation (dart:io vs dart:html)"]}});LANGUAGE_REGISTRY.register({id:"ruby",displayName:"Ruby",tier:3,extensions:[".rb",".rake",".gemspec"],treeSitter:{grammarId:"ruby",wasmFile:"tree-sitter-ruby.wasm",commentNodes:["comment"]},build:{detectFiles:["Gemfile","Rakefile"],commands:[{name:"bundle install",cmd:"bundle install",detectFile:"Gemfile",priority:10},{name:"rake",cmd:"rake",detectFile:"Rakefile",priority:9}]},test:{detectFiles:["Gemfile",".rspec","spec/spec_helper.rb"],frameworks:[{name:"rspec",detect:".rspec",cmd:"bundle exec rspec",priority:10},{name:"minitest",detect:"Rakefile",cmd:"bundle exec rake test",priority:9}]},lint:{detectFiles:[".rubocop.yml","Gemfile"],linters:[{name:"rubocop",detect:".rubocop.yml",cmd:"rubocop --autocorrect",priority:10}]},audit:{detectFiles:["Gemfile.lock"],command:"bundle-audit check --format json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Follow Ruby community style (Rubocop defaults); 120-char line limit","Prefer symbols over strings for hash keys","Use frozen_string_literal: true magic comment in all files","Avoid monkey-patching core classes; prefer refinements","Use keyword arguments for methods with more than 2 parameters"],reviewerChecklist:["Verify frozen_string_literal comment is present in new files","Check for N+1 query patterns in ActiveRecord code","Validate no eval or send with user-controlled input (code injection risk)","Confirm exception handling is specific — no bare rescue","Check for missing validations on ActiveRecord models"]}});LANGUAGE_REGISTRY.register({id:"php",displayName:"PHP",tier:3,extensions:[".php",".phtml",".blade.php"],treeSitter:{grammarId:"php",wasmFile:"tree-sitter-php.wasm",commentNodes:["comment"]},build:{detectFiles:["composer.json"],commands:[{name:"Composer Install",cmd:"composer install --no-interaction --prefer-dist",detectFile:"composer.json",priority:10}]},test:{detectFiles:["Pest.php","phpunit.xml","phpunit.xml.dist"],frameworks:[{name:"Pest",detect:"Pest.php",cmd:"vendor/bin/pest",priority:10},{name:"PHPUnit",detect:"phpunit.xml",cmd:"vendor/bin/phpunit",priority:8},{name:"PHPUnit",detect:"phpunit.xml.dist",cmd:"vendor/bin/phpunit",priority:7}]},lint:{detectFiles:["phpstan.neon","phpstan.neon.dist","pint.json",".php-cs-fixer.php","phpcs.xml"],linters:[{name:"PHPStan",detect:"phpstan.neon",cmd:"vendor/bin/phpstan analyse",priority:10},{name:"PHPStan",detect:"phpstan.neon.dist",cmd:"vendor/bin/phpstan analyse",priority:9},{name:"Pint",detect:"pint.json",cmd:"vendor/bin/pint --test",priority:8},{name:"PHP-CS-Fixer",detect:".php-cs-fixer.php",cmd:"vendor/bin/php-cs-fixer fix --dry-run --diff",priority:7}]},audit:{detectFiles:["composer.lock"],command:"composer audit --locked --format=json",outputFormat:"json"},sast:{nativeRuleSet:"php",semgrepSupport:"ga"},prompts:{coderConstraints:["Follow PSR-12 coding standards","Use strict types declaration: declare(strict_types=1)","Prefer type hints and return type declarations on all functions","Use dependency injection over static methods and singletons","Prefer named constructors and value objects over primitive obsession"],reviewerChecklist:["Verify no user input reaches SQL queries without parameterised binding","Check for XSS — all output must be escaped with htmlspecialchars()","Confirm no eval(), exec(), or shell_exec() with user-controlled input","Validate proper error handling — no bare catch blocks that swallow errors","Challenge any PHP/Laravel documentation or README claim that exceeds what is implemented and CI-verified in v6.49.0 (composer build, PHPUnit/Pest/artisan test, Pint/PHP-CS-Fixer lint, PHPStan static analysis, composer audit, Laravel detection, Blade scanning, 3 Laravel SAST rules). If a PR adds docs claiming broader support, verify it is backed by tests."],testConstraints:["Prefer feature tests for HTTP, middleware, and authentication flows — use Laravel RefreshDatabase or DatabaseTransactions traits","Use unit tests for isolated business logic classes that do not require the full Laravel application container","Pest and PHPUnit coexist in many Laravel repos — php artisan test runs both; do not assume PHPUnit-only","Use .env.testing for test environment configuration; run php artisan config:clear when environment changes affect tests","For database tests, prefer RefreshDatabase over manual setUp/tearDown to avoid state leakage between tests","Run php artisan config:clear and php artisan cache:clear before running tests if environment variables changed","Use separate .env.testing file for test-specific configuration; never rely on .env for CI test runs","For parallel testing with php artisan test --parallel, ensure database connections use separate databases per worker (APP_ENV=testing + test database suffix pattern)"]}})});import{access as access4,readdir as readdir8}from"node:fs/promises";import{extname as extname5,join as join82}from"node:path";function getProfileForFile(filePath){let ext=extname5(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries;try{dirEntries=await readdir8(dir,{withFileTypes:!0}),entries=dirEntries.map((e)=>e.name)}catch{return}for(let profile of LANGUAGE_REGISTRY.getAll())for(let detectFile of profile.build.detectFiles){if(detectFile.includes("*")||detectFile.includes("?")){let regex=new RegExp(`^${detectFile.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);if(dirEntries.some((e)=>!e.isDirectory()&&regex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join82(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries){let ext=extname5(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir8(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join82(projectDir,entry.name))}catch{}let result=[];for(let id of detected){let profile=LANGUAGE_REGISTRY.getById(id);if(profile)result.push(profile)}return result.sort((a,b)=>a.tier-b.tier),result}var init_detector=__esm(()=>{init_profiles()});import*as fs44 from"node:fs";import*as path104 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32",cmd=isWindows?`${command}.exe`:command;try{let available=_internals66.spawnSyncImpl(isWindows?["where",cmd]:["which",cmd],{cwd:process.cwd(),stdin:"ignore",stdout:"ignore",stderr:"ignore",timeout:IS_COMMAND_AVAILABLE_TIMEOUT_MS}).success;return toolchainCache.set(command,available),available}catch{return toolchainCache.set(command,!1),!1}}function checkToolchain(commands){return commands.some((cmd)=>isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs44.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path104.join(dir,matches[0])}catch{}}else{let filePath=path104.join(workingDir,pattern);if(fs44.existsSync(filePath))return filePath}return null}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path104.join(workingDir,"package.json");if(!fs44.existsSync(packageJsonPath))return[];try{let content=fs44.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return[];let found=[];for(let scriptName of scripts)if(pkg.scripts[scriptName])found.push({script:`npm run ${scriptName}`,priority:100});return found}catch{return[]}}function filterByScope(workingDir,scope,changedFiles){if(scope==="all")return findAllBuildFiles(workingDir);if(!changedFiles||changedFiles.length===0)return[];return changedFiles}function findAllBuildFiles(workingDir){let allBuildFiles=new Set;for(let ecosystem of ECOSYSTEMS)for(let pattern of ecosystem.buildFiles)if(pattern.includes("*")){let regex=simpleGlobToRegex(pattern);findFilesRecursive(workingDir,regex,allBuildFiles)}else{let filePath=path104.join(workingDir,pattern);if(fs44.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries=fs44.readdirSync(dir,{withFileTypes:!0});for(let entry of entries){let fullPath=path104.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&&regex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await detectProjectLanguages(workingDir);for(let profile of detectedProfiles){let fullProfile=LANGUAGE_REGISTRY.get(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>b.priority-a.priority),foundCommand=!1;for(let cmd of sortedCommands){if(cmd.detectFile){let detectFilePath=path104.join(workingDir,cmd.detectFile);if(!fs44.existsSync(detectFilePath))continue}let binaryName=cmd.cmd.split(" ")[0];if(isCommandAvailable(binaryName)){commands.push({ecosystem:fullProfile.id,command:cmd.cmd,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let triedBinaries=sortedCommands.map((c)=>c.name||c.cmd.split(" ")[0]).join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,reason}),warn(`[build-discovery] profile ${fullProfile.id}: no binary available, skipping`)}}return{commands,skipped}}async function discoverBuildCommands(workingDir,options){let scope=options?.scope??"all",changedFiles=options?.changedFiles??[],_filesToCheck=filterByScope(workingDir,scope,changedFiles),profileResult=await _internals66.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,coveredEcosystems=new Set;for(let cmd of profileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...profileCommands],skipped=[...profileSkipped];for(let ecosystem of ECOSYSTEMS){if(coveredEcosystems.has(ecosystem.ecosystem)){skipped.push({ecosystem:ecosystem.ecosystem,reason:"Covered by profile detection"});continue}if(!checkToolchain(ecosystem.toolchainCommands)){skipped.push({ecosystem:ecosystem.ecosystem,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}if(!findBuildFiles(workingDir,ecosystem.buildFiles)){skipped.push({ecosystem:ecosystem.ecosystem,reason:`No build file found: ${ecosystem.buildFiles.join(", ")}`});continue}let availableCommands=ecosystem.commands;if(ecosystem.repoDefinedScripts){let repoScripts=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoScripts.length>0)availableCommands=repoScripts.map((s)=>({command:s.script,priority:s.priority}))}for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>b.priority-a.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals66,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:["npm","yarn","pnpm"],commands:[{command:"npm run build",priority:30},{command:"npm run typecheck",priority:20},{command:"npm run check",priority:10}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:20},{command:"cargo check",priority:10}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:10}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m build",priority:20},{command:"python -m py_compile",priority:10}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:10}]},{ecosystem:"java-gradle",buildFiles:["build.gradle","build.gradle.kts","gradle.properties"],toolchainCommands:["gradle","gradlew"],commands:[{command:process.platform==="win32"?"gradlew.bat build":"./gradlew build",priority:20},{command:"gradle build",priority:10}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:10}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:10}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart compile",priority:20},{command:"dart analyze",priority:10}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:20},{command:"cmake -B build && cmake --build build",priority:10}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:10}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["node"],python:["python"],rust:["rust"],go:["go"],java:["java-maven","java-gradle"],kotlin:["java-gradle"],csharp:["dotnet"],cpp:["cpp"],swift:["swift"],dart:["dart"],ruby:[],php:["php-composer"]},toolchainCache=new Map;_internals66={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,spawnSyncImpl:bunSpawnSync};build_discovery=tool({description:"Discover build commands for various ecosystems in a project directory",args:{workingDir:tool.schema.string().describe("Directory to scan for build commands (defaults to current directory)"),scope:tool.schema.string().optional().describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changedFiles:tool.schema.array(tool.schema.string()).optional().describe('List of changed files when scope is "changed"')},async execute(args2,_context){let result=await discoverBuildCommands(args2.workingDir,{scope:args2.scope??"all",changedFiles:args2.changedFiles??[]});return JSON.stringify(result,null,2)}})});var init_tool_names=__esm(()=>{init_tool_metadata()});var exports_tool_doctor={};__export(exports_tool_doctor,{runToolDoctor:()=>runToolDoctor,getBinaryReadinessAdvisory:()=>getBinaryReadinessAdvisory,checkAgentToolMapAlignment:()=>checkAgentToolMapAlignment});function getRegisteredToolKeys(){return new Set(TOOL_NAME_SET)}function checkAgentToolMapAlignment(registeredKeys){let findings=[];for(let[agentName,tools]of Object.entries(AGENT_TOOL_MAP))for(let toolName of tools)if(!registeredKeys.has(toolName))findings.push({id:`agent-tool-map-mismatch-${agentName}-${toolName}`,title:"AGENT_TOOL_MAP alignment gap",description:`Tool "${toolName}" is assigned to agent "${agentName}" in AGENT_TOOL_MAP but is not a registered tool name. The agent will not be able to use this tool.`,severity:"error",path:`AGENT_TOOL_MAP.${agentName}`,currentValue:toolName,autoFixable:!1});return findings}function checkBinaryReadiness(){let findings=[];for(let{binary,language}of BINARY_CHECKLIST)if(!isCommandAvailable(binary))findings.push({id:`missing-binary-${binary}`,title:"Class 3 tool binary not found",description:`Binary "${binary}" is not available on PATH. ${language} linting will not be available. Install ${binary} to enable ${language} language support.`,severity:"warn",path:`toolchain.${binary}`,currentValue:void 0,autoFixable:!1});return findings}function getBinaryReadinessAdvisory(){let findings=checkBinaryReadiness();if(findings.length===0)return null;return["[PRE-FLIGHT ADVISORY] The following Class 3 tool binaries were not found on PATH at session start.","These tools will soft-skip at invocation. Plan tasks accordingly.",...findings.map((f)=>`- MISSING BINARY: ${f.currentValue??f.path?.split(".")[1]??"unknown"} — ${f.description}`)].join(`
1620
1620
  `)}function runToolDoctor(_directory,_pluginRoot){let findings=[],registeredKeys=getRegisteredToolKeys();for(let toolName of TOOL_NAMES)if(!registeredKeys.has(toolName))findings.push({id:`missing-tool-registration-${toolName}`,title:"Missing tool registration",description:`Tool "${toolName}" is defined in TOOL_NAMES but is not present in the plugin tool object derived from TOOL_MANIFEST. This means the tool will not be available at runtime.`,severity:"error",path:`tool.${toolName}`,currentValue:void 0,autoFixable:!1});findings.push(...checkAgentToolMapAlignment(registeredKeys)),findings.push(...checkBinaryReadiness());let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length};return{findings,summary,hasAutoFixableIssues:!1,timestamp:Date.now(),configSource:"src/tools/manifest.ts"}}var BINARY_CHECKLIST;var init_tool_doctor=__esm(()=>{init_discovery();init_constants();init_tool_names();BINARY_CHECKLIST=[{binary:"ruff",language:"Python"},{binary:"cargo",language:"Rust (via clippy)"},{binary:"golangci-lint",language:"Go"},{binary:"mvn",language:"Java (Maven)"},{binary:"gradle",language:"Java (Gradle)"},{binary:"dotnet",language:".NET"},{binary:"swift",language:"Swift"},{binary:"swiftlint",language:"Swift (linting)"},{binary:"dart",language:"Dart"},{binary:"flutter",language:"Flutter/Dart"},{binary:"biome",language:"JS/TS (already in project)"},{binary:"eslint",language:"JS/TS"}]});function formatToolDoctorMarkdown(result){let lines=["## Tool Doctor Report","",`**Tool Registry**: ${result.configSource}`,"","### Summary",`- **Info**: ${result.summary.info}`,`- **Warnings**: ${result.summary.warn}`,`- **Errors**: ${result.summary.error}`,""];if(result.findings.length===0)lines.push("No issues found. All tools are properly registered!");else{lines.push("### Findings","");let errors5=result.findings.filter((f)=>f.severity==="error"),warnings=result.findings.filter((f)=>f.severity==="warn"),infos=result.findings.filter((f)=>f.severity==="info");for(let finding of[...errors5,...warnings,...infos]){let icon=finding.severity==="error"?"❌":finding.severity==="warn"?"⚠️":"ℹ️";if(lines.push(`${icon} **${finding.severity.toUpperCase()}**: ${finding.description}`),finding.autoFixable)lines.push(" - \uD83D\uDD27 Auto-fixable");lines.push("")}if(result.summary.error>0)lines.push("---",""),lines.push(`**BLOCKING**: ${result.summary.error} error-severity finding(s) must be resolved before release. `+"AGENT_TOOL_MAP alignment errors mean an agent's system prompt instructs the model to call a tool that opencode has not registered — the agent's workflow will silently fail at runtime."),lines.push("")}return lines.join(`
1621
- `)}function formatDoctorMarkdown(result){let lines=["## Config Doctor Report","",`**Config Source**: ${result.configSource}`,"","### Summary",`- **Info**: ${result.summary.info}`,`- **Warnings**: ${result.summary.warn}`,`- **Errors**: ${result.summary.error}`,""];if(result.findings.length===0)lines.push("No issues found. Your configuration looks good!");else{lines.push("### Findings","");let errors5=result.findings.filter((f)=>f.severity==="error"),warnings=result.findings.filter((f)=>f.severity==="warn"),infos=result.findings.filter((f)=>f.severity==="info");for(let finding of[...errors5,...warnings,...infos]){let icon=finding.severity==="error"?"❌":finding.severity==="warn"?"⚠️":"ℹ️";if(lines.push(`${icon} **${finding.severity.toUpperCase()}**: ${finding.description}`),finding.autoFixable)lines.push(" - \uD83D\uDD27 Auto-fixable");lines.push("")}}if(result.hasAutoFixableIssues)lines.push("---"),lines.push(""),lines.push("Tip: Some issues can be auto-fixed. Run `/swarm config doctor --fix` to apply fixes.");return lines.join(`
1622
- `)}async function handleDoctorCommand(directory,args2){let enableAutoFix=args2.includes("--fix")||args2.includes("-f"),config3=loadPluginConfig(directory),result=runConfigDoctor(config3,directory),output;if(enableAutoFix&&result.hasAutoFixableIssues){let{runConfigDoctorWithFixes:runConfigDoctorWithFixes2}=await Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)),fixResult=await runConfigDoctorWithFixes2(directory,config3,!0,{applyLossy:!0});output=formatDoctorMarkdown(fixResult.result)}else{let lastRun=readDoctorArtifact(directory),markdown=formatDoctorMarkdown(result);if(lastRun)markdown=`Last run: ${lastRun.timestamp}, ${lastRun.findingsCount} findings (${lastRun.autoFixableCount} auto-fixable)
1621
+ `)}function stripControlChars(s){return s.replace(/[\x00-\x1f\x7f]+/g," ")}function sanitizeForMarkdownCodeSpan(s){return stripControlChars(s).replace(/`/g,"'")}function sanitizeForMarkdownText(s){return stripControlChars(s).replace(/([\\`*_[\]|])/g,"\\$1")}function formatDoctorMarkdown(result){let lines=["## Config Doctor Report","",`**Config Source**: ${result.configSource}`,"","### Summary",`- **Info**: ${result.summary.info}`,`- **Warnings**: ${result.summary.warn}`,`- **Errors**: ${result.summary.error}`,""];if(result.findings.length===0)lines.push("No issues found. Your configuration looks good!");else{lines.push("### Findings","");let errors5=result.findings.filter((f)=>f.severity==="error"),warnings=result.findings.filter((f)=>f.severity==="warn"),infos=result.findings.filter((f)=>f.severity==="info");for(let finding of[...errors5,...warnings,...infos]){let icon=finding.severity==="error"?"❌":finding.severity==="warn"?"⚠️":"ℹ️";if(lines.push(`${icon} **${finding.severity.toUpperCase()}**: ${finding.description}`),finding.autoFixable)lines.push(" - \uD83D\uDD27 Auto-fixable");lines.push("")}}if(result.hasAutoFixableIssues)lines.push("---"),lines.push(""),lines.push("Tip: Some issues can be auto-fixed. Run `/swarm config doctor --fix` to apply fixes.");return lines.join(`
1622
+ `)}async function handleDoctorCommand(directory,args2){let enableAutoFix=args2.includes("--fix")||args2.includes("-f"),meta3=loadPluginConfigWithMeta(directory),config3=meta3.config,result=runConfigDoctor(config3,directory),output;if(enableAutoFix&&result.hasAutoFixableIssues){let{runConfigDoctorWithFixes:runConfigDoctorWithFixes2}=await Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)),fixResult=await runConfigDoctorWithFixes2(directory,config3,!0,{applyLossy:!0});output=formatDoctorMarkdown(fixResult.result)}else{let lastRun=readDoctorArtifact(directory),markdown=formatDoctorMarkdown(result);if(lastRun)markdown=`Last run: ${lastRun.timestamp}, ${lastRun.findingsCount} findings (${lastRun.autoFixableCount} auto-fixable)
1623
1623
 
1624
- `+markdown;output=markdown}let strayDirs=detectStraySwarmDirs(directory);if(strayDirs.length>0)if(enableAutoFix){let fixOutput=`
1624
+ `+markdown;output=markdown}if(meta3.recovery!=="none"){let lines=[`
1625
+ ---
1626
+
1627
+ ## Config Recovery (FR-004)
1628
+
1629
+ `];if(lines.push(`- **Recovery applied**: \`${meta3.recovery}\``),meta3.removedKeys.length>0){lines.push(`- **Removed keys (${meta3.removedKeys.length})**:`);for(let k of meta3.removedKeys)lines.push(` - \`${sanitizeForMarkdownCodeSpan(k)}\``)}if(meta3.warnings.length>0){lines.push(`- **Recovery warnings (${meta3.warnings.length})**:`);for(let w of meta3.warnings)lines.push(` - ${sanitizeForMarkdownText(w)}`)}output+=`${lines.join(`
1630
+ `)}
1631
+ `}let strayDirs=detectStraySwarmDirs(directory);if(strayDirs.length>0)if(enableAutoFix){let fixOutput=`
1625
1632
  ---
1626
1633
 
1627
1634
  ## Stray .swarm Directories
@@ -1998,13 +2005,13 @@ INSTRUCTIONS: Retain ONLY the system prompt, the current task context, and the l
1998
2005
  `))if(line.trim())n++;return n}catch{return 0}}async function countProposals(directory){try{let proposalsDir=validateSwarmPath(directory,"skills/proposals");if(!fsSync9.existsSync(proposalsDir))return 0;let{readdir:readdir10}=await import("node:fs/promises");return(await readdir10(proposalsDir)).filter((f)=>f.endsWith(".md")).length}catch{return 0}}var _internals102;var init_status_service=__esm(()=>{init_loader();init_schema();init_state3();init_extractors();init_knowledge_escalator();init_knowledge_link();init_knowledge_validator();init_utils2();init_memory_link();init_redaction();init_manager();init_state2();init_state4();init_compaction_service();init_context_budget_service();_internals102={loadLeanTurboRunState,hasActiveLeanTurbo,hasActiveFullAuto,getActiveFullAutoSessionID,loadFullAutoRunState}});var init_status=__esm(()=>{init_status_service()});async function handleSyncPlanCommand(directory,_args){let plan=await loadPlan(directory);if(!plan)return`## Plan Sync Report
1999
2006
 
2000
2007
  No active swarm plan found. Nothing to sync.`;return["## Plan Sync Report","","**Status**: ✅ Synced","","The plan.json and plan.md are now synchronized.","","### Current Plan","",derivePlanMarkdown(plan)].join(`
2001
- `)}var init_sync_plan=__esm(()=>{init_manager()});async function handleTurboCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Turbo Mode requires an active session. Use /swarm turbo from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Turbo Mode requires an active session to operate.";let arg0=args2[0]?.toLowerCase(),arg1=args2[1]?.toLowerCase();if(arg0==="status")return buildStatusMessage2(session,directory,sessionID);let isTurboOn=session.turboMode,isLeanActive=session.leanTurboActive===!0,disableTurbo=(reason)=>{if(isLeanActive)try{pauseLeanTurboRun(directory,sessionID,reason)}catch(error93){error48(`[turbo] pauseLeanTurboRun failed: ${error93 instanceof Error?error93.message:String(error93)}`)}try{disableEpicMode(directory,sessionID)}catch(error93){error48(`[turbo] disableEpicMode (cross-clear) failed: ${error93 instanceof Error?error93.message:String(error93)}`)}session.epicModeActive=!1,session.turboMode=!1,session.turboStrategy=void 0,session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0};if(arg0==="off"||arg0==="lean"&&arg1==="off")return disableTurbo("/swarm turbo off"),"Turbo Mode disabled";if(arg0==="standard"&&arg1==="off")return disableTurbo("/swarm turbo standard off"),"Turbo Mode disabled";if(arg0===void 0)if(isTurboOn)return disableTurbo("/swarm turbo (toggle off)"),"Turbo Mode disabled";else return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled";if(arg0==="on"){let strategy="standard";try{let{config:config3}=_internals103.loadPluginConfigWithMeta(directory);if(config3.turbo?.strategy==="lean")strategy="lean"}catch(error93){warn(`[turbo] could not read config for strategy default: ${error93 instanceof Error?error93.message:String(error93)}`)}if(strategy==="lean")return enableLeanTurbo(session,directory,sessionID);if(isLeanActive)disableTurbo("/swarm turbo on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled"}if(arg0==="standard"&&arg1==="on"){if(isLeanActive)disableTurbo("/swarm turbo standard on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled (standard)"}if(arg0==="lean"&&arg1==="on")return enableLeanTurbo(session,directory,sessionID);if(arg0==="lean"&&arg1===void 0)if(isLeanActive)return disableTurbo("/swarm turbo lean (toggle off)"),"Turbo Mode disabled";else return enableLeanTurbo(session,directory,sessionID);if(arg0==="epic"&&arg1==="on"){let leanMsg=enableLeanTurbo(session,directory,sessionID);if(!session.leanTurboActive)return`${leanMsg}
2008
+ `)}var init_sync_plan=__esm(()=>{init_manager()});var TURBO_BYPASS_DISCLOSURE="Bypassed: Stage B (reviewer + test_engineer) for Tier 0-2 tasks; phase_complete Gates 1-5 (completion-verify, drift-verifier, hallucination-guard, mutation-gate, phase-council). Still enforced: Stage A (lint, imports, pre_check_batch); Tier 3 Stage B; Gate 5b (architecture-supervisor); Gate 6 (final-council); Gate 7 (full-auto).";async function handleTurboCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Turbo Mode requires an active session. Use /swarm turbo from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Turbo Mode requires an active session to operate.";let arg0=args2[0]?.toLowerCase(),arg1=args2[1]?.toLowerCase();if(arg0==="status")return buildStatusMessage2(session,directory,sessionID);let isTurboOn=session.turboMode,isLeanActive=session.leanTurboActive===!0,disableTurbo=(reason)=>{if(isLeanActive)try{pauseLeanTurboRun(directory,sessionID,reason)}catch(error93){error48(`[turbo] pauseLeanTurboRun failed: ${error93 instanceof Error?error93.message:String(error93)}`)}try{disableEpicMode(directory,sessionID)}catch(error93){error48(`[turbo] disableEpicMode (cross-clear) failed: ${error93 instanceof Error?error93.message:String(error93)}`)}session.epicModeActive=!1,session.turboMode=!1,session.turboStrategy=void 0,session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0};if(arg0==="off"||arg0==="lean"&&arg1==="off")return disableTurbo("/swarm turbo off"),"Turbo Mode disabled";if(arg0==="standard"&&arg1==="off")return disableTurbo("/swarm turbo standard off"),"Turbo Mode disabled";if(arg0===void 0)if(isTurboOn)return disableTurbo("/swarm turbo (toggle off)"),"Turbo Mode disabled";else return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,`Turbo Mode enabled. ${TURBO_BYPASS_DISCLOSURE}`;if(arg0==="on"){let strategy="standard";try{let{config:config3}=_internals103.loadPluginConfigWithMeta(directory);if(config3.turbo?.strategy==="lean")strategy="lean"}catch(error93){warn(`[turbo] could not read config for strategy default: ${error93 instanceof Error?error93.message:String(error93)}`)}if(strategy==="lean")return enableLeanTurbo(session,directory,sessionID);if(isLeanActive)disableTurbo("/swarm turbo on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,`Turbo Mode enabled. ${TURBO_BYPASS_DISCLOSURE}`}if(arg0==="standard"&&arg1==="on"){if(isLeanActive)disableTurbo("/swarm turbo standard on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,`Turbo Mode enabled (standard). ${TURBO_BYPASS_DISCLOSURE}`}if(arg0==="lean"&&arg1==="on")return enableLeanTurbo(session,directory,sessionID);if(arg0==="lean"&&arg1===void 0)if(isLeanActive)return disableTurbo("/swarm turbo lean (toggle off)"),"Turbo Mode disabled";else return enableLeanTurbo(session,directory,sessionID);if(arg0==="epic"&&arg1==="on"){let leanMsg=enableLeanTurbo(session,directory,sessionID);if(!session.leanTurboActive)return`${leanMsg}
2002
2009
  Epic Mode NOT enabled: Lean Turbo failed to enable (Epic Mode requires Lean Turbo as its promote-dispatch target).`;try{enableEpicMode(directory,sessionID),session.epicModeActive=!0}catch(error93){return error48(`[turbo] enableEpicMode failed: ${error93 instanceof Error?error93.message:String(error93)}`),`${leanMsg}
2003
2010
  Epic Mode could not be enabled: ${error93 instanceof Error?error93.message:String(error93)}`}return`${leanMsg}
2004
2011
  Epic Mode enabled — the architect will use the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → Task (per task in current wave, all in one message) → epic_record_divergence.`}if(arg0==="epic"&&arg1==="off")return disableTurbo("/swarm turbo epic off"),"Turbo Mode + Epic Mode disabled";if(arg0==="epic"&&arg1===void 0){if(session.epicModeActive===!0)return disableTurbo("/swarm turbo epic (toggle off)"),"Turbo Mode + Epic Mode disabled";let leanMsg=enableLeanTurbo(session,directory,sessionID);if(!session.leanTurboActive)return`${leanMsg}
2005
2012
  Epic Mode NOT enabled: Lean Turbo failed to enable.`;try{enableEpicMode(directory,sessionID),session.epicModeActive=!0}catch(error93){return error48(`[turbo] enableEpicMode failed: ${error93 instanceof Error?error93.message:String(error93)}`),`${leanMsg}
2006
2013
  Epic Mode could not be enabled: ${error93 instanceof Error?error93.message:String(error93)}`}return`${leanMsg}
2007
- Epic Mode enabled — the architect will use the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → Task (per task in current wave, all in one message) → epic_record_divergence.`}if(isTurboOn)return disableTurbo("/swarm turbo (toggle off via unknown arg)"),"Turbo Mode disabled";else return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled"}function enableLeanTurbo(session,directory,sessionID){let maxParallelCoders=4,conflictPolicy="serialize";try{let{config:config3}=_internals103.loadPluginConfigWithMeta(directory),leanConfig=config3.turbo?.lean;if(leanConfig)maxParallelCoders=leanConfig.max_parallel_coders??4,conflictPolicy=leanConfig.conflict_policy??"serialize"}catch(error93){warn(`[turbo] could not read lean config: ${error93 instanceof Error?error93.message:String(error93)}`)}let durableError;try{let state=emptyRunState(sessionID,maxParallelCoders);state.status="running",saveLeanTurboRunState(directory,state)}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[turbo] durable run-state write failed: ${durableError}`)}if(durableError)return["Error: Lean Turbo could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");let fullAutoActive=session.fullAutoMode;return session.turboMode=!0,session.turboStrategy="lean",session.leanTurboActive=!0,session.leanTurboCurrentPhase=void 0,["Lean Turbo enabled",`(maxParallelCoders=${maxParallelCoders}, conflict_policy=${conflictPolicy},`,`Full-Auto: ${fullAutoActive?"active":"inactive"})`].join(" ")}function buildStatusMessage2(session,directory,sessionID){if(!session.turboMode)return"Turbo: off";if(session.turboStrategy==="standard"||!session.leanTurboActive)return"Turbo: standard (turboMode=true)";if(isStateUnreadable2(directory))return["Turbo: lean (turboMode=true, leanTurboActive=true)","WARNING: Durable state is unreadable — cannot report full status."].join(`
2014
+ Epic Mode enabled — the architect will use the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → Task (per task in current wave, all in one message) → epic_record_divergence.`}if(isTurboOn)return disableTurbo("/swarm turbo (toggle off via unknown arg)"),"Turbo Mode disabled";else return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,`Turbo Mode enabled. ${TURBO_BYPASS_DISCLOSURE}`}function enableLeanTurbo(session,directory,sessionID){let maxParallelCoders=4,conflictPolicy="serialize";try{let{config:config3}=_internals103.loadPluginConfigWithMeta(directory),leanConfig=config3.turbo?.lean;if(leanConfig)maxParallelCoders=leanConfig.max_parallel_coders??4,conflictPolicy=leanConfig.conflict_policy??"serialize"}catch(error93){warn(`[turbo] could not read lean config: ${error93 instanceof Error?error93.message:String(error93)}`)}let durableError;try{let state=emptyRunState(sessionID,maxParallelCoders);state.status="running",saveLeanTurboRunState(directory,state)}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[turbo] durable run-state write failed: ${durableError}`)}if(durableError)return["Error: Lean Turbo could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");let fullAutoActive=session.fullAutoMode;return session.turboMode=!0,session.turboStrategy="lean",session.leanTurboActive=!0,session.leanTurboCurrentPhase=void 0,[`Lean Turbo enabled. ${TURBO_BYPASS_DISCLOSURE} Per-lane: reviewer gates and file-lock conflict detection.`,`(maxParallelCoders=${maxParallelCoders}, conflict_policy=${conflictPolicy},`,`Full-Auto: ${fullAutoActive?"active":"inactive"})`].join(" ")}function buildStatusMessage2(session,directory,sessionID){if(!session.turboMode)return"Turbo: off";if(session.turboStrategy==="standard"||!session.leanTurboActive)return"Turbo: standard (turboMode=true)";if(isStateUnreadable2(directory))return["Turbo: lean (turboMode=true, leanTurboActive=true)","WARNING: Durable state is unreadable — cannot report full status."].join(`
2008
2015
  `);let state=loadLeanTurboRunState(directory,sessionID);if(!state)return["Turbo: lean (turboMode=true, leanTurboActive=true)","WARNING: Durable state not found."].join(`
2009
2016
  `);let phase=state.phase!==void 0?`phase=${state.phase}`:"phase=unset",laneCount=state.lanes.length,degradedCount=state.degradedTasks.length,maxParallel=state.maxParallelCoders,fullAutoActive=session.fullAutoMode;return["Turbo: lean (turboMode=true, leanTurboActive=true)",`Status: ${state.status}, ${phase}, lanes=${laneCount}, degraded=${degradedCount}`,`maxParallelCoders=${maxParallel}, Full-Auto: ${fullAutoActive?"active":"inactive"}`].join(`
2010
2017
  `)}var _internals103;var init_turbo=__esm(()=>{init_config();init_state2();init_state();init_state4();init_logger();_internals103={loadPluginConfigWithMeta}});import*as path156 from"node:path";async function handleUnlinkCommand(directory,args2){let pointer=readLinkPointer(directory);if(!pointer)return"ℹ️ This worktree is not linked. Nothing to unlink.";let copyBack=!args2.includes("--no-copy"),linkDir=resolveLinkDir(pointer.linkId),totalMerged=0,totalSkipped=0,familySummary="";if(copyBack)try{let result=await migrateKnowledgeFamily(path156.join(directory,".swarm"),linkDir);for(let m of result.perMember)totalMerged+=m.merged,totalSkipped+=m.skipped;familySummary=result.perMember.filter((m)=>m.merged>0||m.skipped>0).map((m)=>` ${m.filename}: ${m.merged} copied, ${m.skipped} kept`).join(`
@@ -2080,8 +2087,8 @@ Subcommands:
2080
2087
  `+`
2081
2088
  `+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},simulate:{handler:(ctx)=>handleSimulateCommand(ctx.directory,ctx.args),description:"Dry-run hidden coupling analysis with configurable thresholds",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},sdd:{handler:(ctx)=>handleSddCommand(ctx.directory,ctx.args),description:"Manage OpenSpec-compatible SDD artifacts and effective spec projection",args:"status|validate|project [--json] [--change <id>] [--dry-run]",details:"Parent command for spec-driven development artifacts. Use sdd status to inspect .swarm/spec.md plus openspec/ artifacts, sdd validate to validate OpenSpec-compatible deltas, and sdd project to materialize the effective spec into .swarm/spec.md for planning.",category:"utility",toolPolicy:"agent"},"sdd status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",subcommandOf:"sdd",args:"[--json]",category:"utility",toolPolicy:"agent"},"sdd validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",subcommandOf:"sdd",args:"[--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",subcommandOf:"sdd",args:"[--dry-run] [--overwrite] [--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd-status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",aliasOf:"sdd status",deprecated:!0},"sdd-validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",aliasOf:"sdd validate",deprecated:!0},"sdd-project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",aliasOf:"sdd project",deprecated:!0},analyze:{handler:(ctx)=>handleAnalyzeCommand(ctx.directory,ctx.args),description:"Analyze spec.md vs plan.md for requirement coverage gaps",args:"",category:"agent",toolPolicy:"none"},clarify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleClarifyCommand),description:"Clarify and refine an existing feature specification",args:"[description-text]",category:"agent",toolPolicy:"none"},specify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleSpecifyCommand),description:"Generate or import a feature specification [description]",args:"[description-text]",category:"agent",toolPolicy:"none"},brainstorm:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleBrainstormCommand),description:"Enter architect MODE: BRAINSTORM — structured seven-phase planning workflow [topic]",args:"[topic-text]",details:"Triggers the architect to run the brainstorm workflow: CONTEXT SCAN, single-question DIALOGUE, APPROACHES, DESIGN SECTIONS, SPEC WRITE + SELF-REVIEW, QA GATE SELECTION, TRANSITION. Use for new plans where requirements need to be drawn out before writing spec.md / plan.md.",category:"agent",toolPolicy:"none"},loop:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleLoopCommand),description:"Enter architect MODE: LOOP — compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [objective]",args:"<objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]",details:`Triggers the architect to run the compound-engineering loop defined in ${BUNDLED_PROJECT_SKILL_ROOT}/loop/SKILL.md: BRAINSTORM (requirements) → PLAN (+ critic gate) → BUILD (execute) → REVIEW (independent reviewer + critic on the diff, report-only) → IMPROVE (phase-wrap retrospective + compounding learning capture), then evaluate stop conditions and loop for another improvement cycle if the objective is unmet and budget remains. Generator and reviewer/critic run in separate contexts; failing assertions must be fixed at the root cause, never weakened, mocked, or skipped. Defense-in-depth stop conditions: objective met, --max-cycles budget (default 3), no-progress/plateau, oscillation, unrecoverable error, or explicit user stop. --autonomy auto (default) runs unattended with hard stops still enforced; --autonomy checkpoint pauses at phase gates for user approval. --depth exhaustive widens exploration. --resume continues an existing loop run from durable .swarm/loop/ state. Distinct from full-auto (autonomous cross-phase oversight) and turbo (parallel lanes within a phase): loop is a user-initiated, gated, compounding workflow.`,category:"agent",toolPolicy:"none"},council:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCouncilCommand),description:"Enter architect MODE: COUNCIL — multi-model deliberation [question] [--spec-review]",args:"<question> [--spec-review]",details:"Triggers the architect to convene a three-agent General Council: Generalist (reviewer model), Skeptic (critic model), and Domain Expert (SME model). "+"The architect first runs 1–3 targeted web searches and passes a compiled RESEARCH CONTEXT "+"to all three agents before dispatching them in parallel. Agents deliberate using the NSED peer-review protocol (Round 1 independent analysis, Round 2 MAINTAIN/CONCEDE/NUANCE for disagreements). The architect synthesizes the final answer directly from convene_general_council output. --spec-review switches to single-pass advisory mode for spec review. Requires council.general.enabled: true and a search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",category:"agent",toolPolicy:"none"},"abort-pr-workflow":{handler:(ctx)=>handleAbortPrWorkflowCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop [mode] [reason]",args:"[PR_REVIEW|PR_FEEDBACK] [reason...]",details:"Human-only escape hatch for an unrecoverable PR_REVIEW or PR_FEEDBACK mechanical gate. When the architect cannot reach complete_pr_workflow — for example a compound `git fetch && git checkout` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — running this clears the durable gate state for the current session and stops the auto-resume loop without depending on the trapped model. The agent itself cannot run this command; it must call the abort_pr_workflow tool (or ask you to run this command). Both paths funnel into the same fail-closed abortPrWorkflow hook, which refuses while the workflow is armed for publication or while PR workflow lanes are still in flight. An audit event is appended to .swarm/events.jsonl.",category:"utility",toolPolicy:"restricted"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand,"PR_REVIEW"),description:"Launch deep PR review with multi-lane analysis [url] [--council]",args:"<pr-url|owner/repo#N|N> [--council]",details:"Launches a structured PR review: reconstructs PR intent via obligation extraction cascade, launches all 6 fixed base explorer lanes through dispatch_lanes_async while the architect keeps doing non-dependent work, polls collect_lane_results incrementally, runs all 11 mandatory repository-agnostic micro-lanes without applicability waivers, validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, then synthesizes only after coverage is closed. Failed obligations retry through the same structured async mode and exact PR head; blocking or direct-Task dispatch is not provenance-equivalent, so unclosed coverage leaves the review BLOCKED rather than degraded. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"pr-feedback":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrFeedbackCommand,"PR_FEEDBACK"),description:"Ingest and close known PR feedback (review comments, CI failures, conflicts) [pr] [instructions]",args:"[url|owner/repo#N|N] [instructions...]",details:"Triggers MODE: PR_FEEDBACK — ingests existing pull-request feedback (review threads, requested changes, CI/check failures, merge conflicts, stale branch state, pasted notes), verifies every claim against source, clusters related problems, fixes confirmed items, validates the branch, and reports closure status for every ledger item. Distinct from /swarm pr-review, which discovers new findings. The PR reference is optional: with none, the architect builds the ledger from the current PR/branch; text after the reference is forwarded as extra instructions. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},"ci-monitor":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCiMonitorCommand),description:"Drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge) [pr]",args:"<pr-url|owner/repo#N|N>",details:"Triggers MODE: CI_MONITOR — takes an already human-reviewed, approved PR, exhaustively researches every CI failure, fixes it end-to-end, iterates until all required checks are green (max 5 fix cycles), then merges via `gh pr merge` with no merge-strategy flag. Invoke only after human review is complete; the skill re-verifies reviewDecision: APPROVED and mergeable state before doing anything destructive. Distinct from /swarm pr-subscribe, which passively watches a PR without a merge terminal. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},"pr subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:'Subscribes the current session to PR state-change events for the specified PR. When pr_monitor.enabled is true, the background polling worker detects CI failures, new comments, review state changes (changes requested / approved), merge conflicts and conflict resolutions, and merge/close events — each gated by its pr_monitor notify_* config flag (notify_ci_success defaults to false). Delivery follows pr_monitor.event_delivery: "prompt" (default) wakes the subscribed session with a structured <pr-activity> message; "advisory" queues session-scoped advisories with dedup tokens for the next turn. Subscriptions are idempotent, capped by pr_monitor.max_subscriptions, and agent-callable. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin). Requires pr_monitor.enabled: true in config.',category:"agent",toolPolicy:"agent"},"pr-subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",aliasOf:"pr subscribe",deprecated:!0},"pr unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:"Unsubscribes the current session from PR state-change events for the specified PR. Removes the active subscription record (idempotent; agent-callable). Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"agent"},"pr-unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",aliasOf:"pr unsubscribe",deprecated:!0},"pr status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",args:"",details:"Displays all active PR subscriptions for the current session. Shows PR URL, last checked time, watching status, and error count per subscription. Also shows total active subscriptions across all sessions.",category:"agent",toolPolicy:"agent",toolNoArgs:!0},"pr-status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",aliasOf:"pr status",deprecated:!0},"ci-simulate":{handler:(ctx)=>handleCiSimulateCommand(ctx.directory,ctx.args),description:"Create a temporary merge-result worktree and run CI before merge queue entry",args:"[--base origin/main] [--head <ref>]",details:"Creates a detached temporary worktree under .swarm/ci-simulate from the base ref, merges the current worktree HEAD (or --head ref), runs fixed local CI gates (typecheck, Biome CI, build, unit/integration/security/smoke tests, drift check), then removes the worktree and prunes metadata. Intended as a pre-queue merge_group simulation helper.",category:"agent",toolPolicy:"agent"},"deep-dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Launch deep codebase audit with parallel explorer waves, dual reviewers, and critic challenge [scope]",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",details:"Runs a read-only deep audit of the specified scope using parallel explorer waves (8-file cap per mission, ~3500 line guardrail), always 2 parallel reviewers for verification, and sequential critic challenge on HIGH/CRITICAL findings. Profiles select explorer lanes: standard (5 lanes), security, ux, architecture, full (all 8 lanes). Emits a structured findings report without mutating source code.",category:"agent",toolPolicy:"none"},"deep dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Alias for /swarm deep-dive — launch deep codebase audit",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"deep-dive"},"deep-research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Launch a multi-source, fact-checked deep research pass and synthesize a cited report [question]",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",details:"Runs the orchestrator-worker deep-research protocol: the architect decomposes the question into subtopics, gathers evidence with web_search and web_fetch across up to N iterative rounds, dispatches parallel sme synthesis workers, verifies every claim against cited sources with dual reviewers, challenges high-stakes claims with the critic, and presents a cited report in chat. Read-only — does not mutate source code, delegate to coder, or call declare_scope. Requires council.general.enabled and a search API key.",category:"agent",toolPolicy:"none"},"deep research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Alias for /swarm deep-research — launch a cited deep research pass",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",category:"agent",aliasOf:"deep-research"},"codebase-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",details:"Runs the codebase-review-swarm workflow: Phase 0 inventory, selected-track depth planning, non-diluting review passes, coverage closure, reviewer validation, critic challenge, and .swarm/review-v8 artifacts. Materializes the bundled skill package if missing, then emits a MODE signal; the architect workflow must not mutate source files.",category:"agent",toolPolicy:"none"},"codebase review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Alias for /swarm codebase-review - launch codebase-review-swarm",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"codebase-review"},"design-docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Generate or sync language-agnostic design docs (domain, technical-spec, behavior-spec, reference/) for the project under build [description]",args:"<description> [--out <dir>] [--lang <name>] [--update]",details:"Triggers the architect to enter MODE: DESIGN_DOCS — delegates to the docs_design agent to author/sync docs/domain.md, docs/technical-spec.md, docs/behavior-spec.md, and docs/reference/* (plus reference/traceability.json and design-changelog.md). Normative docs are 100% language-agnostic; all framework-specific material is quarantined under reference/. --update syncs existing docs to current code/spec instead of generating fresh. Requires design_docs.enabled: true.",category:"agent",toolPolicy:"none"},"design docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Alias for /swarm design-docs — generate or sync design docs",args:"<description> [--out <dir>] [--lang <name>] [--update]",category:"agent",aliasOf:"design-docs"},issue:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleIssueCommand),description:"Ingest a GitHub issue into the swarm workflow [url] [--plan] [--trace] [--no-repro]",args:"<issue-url|owner/repo#N|N> [--plan] [--trace] [--no-repro]",details:"Triggers the architect to enter MODE: ISSUE_INGEST — ingests a GitHub issue, restructures it into a normalized intake note, localizes root cause through hypothesis-driven tracing, and outputs a resolution spec. --plan transitions to plan creation after spec generation. --trace runs the fix workflow end-to-end (implies --plan); compose commit-pr to publish. --no-repro skips the reproduction step. Supports full GitHub URL, owner/repo#N shorthand, or bare issue number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"qa-gates":{handler:(ctx)=>handleQaGatesCommand(ctx.directory,ctx.args,ctx.sessionID),description:"View or modify QA gate profile for the current plan [enable|override <gate>...]",args:"[show|enable|override] <gate>...",details:"show: display spec-level, session-override, and effective QA gates for the current plan. enable: persist gate(s) into the locked-once profile (architect; rejected after critic approval lock). override: session-only ratchet-tighter enable. Valid gates: reviewer, test_engineer, council_mode, sme_enabled, critic_pre_plan, hallucination_guard, sast_enabled, mutation_test, phase_council, drift_check, final_council.",category:"config",toolPolicy:"none"},link:{handler:(ctx)=>handleLinkCommand(ctx.directory,ctx.args),description:"Tie this worktree to a shared swarm knowledge store [name]",details:"Links the current worktree to a shared knowledge store so multiple swarms working on the same project (e.g. separate git worktrees) pool their lessons instead of each keeping an isolated .swarm/knowledge.jsonl. With no name, ties all worktrees of the same repo via the project hash; with a name, ties any worktrees/repos that use the same name. Existing local lessons are merged (deduped) into the shared store. Use `/swarm link status` to inspect.",args:"[<name> | status]",category:"utility",toolPolicy:"none"},"link status":{handler:(ctx)=>handleLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares knowledge via a link",subcommandOf:"link",category:"utility",toolPolicy:"none"},unlink:{handler:(ctx)=>handleUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing swarm knowledge for this worktree [--no-copy]",details:"Unlinks the current worktree from its shared knowledge store and returns it to a local .swarm/knowledge.jsonl. By default the shared lessons are copied back into the local store (deduped) so nothing is lost; pass --no-copy to skip the copy-back.",args:"[--no-copy]",category:"utility",toolPolicy:"none"},promote:{handler:(ctx)=>handlePromoteCommand(ctx.directory,ctx.args),description:"Manually promote lesson to hive knowledge (policy-gated; --force --reason overrides with audit)",details:'Promotes a lesson directly to hive knowledge (--category flag sets category) or references an existing swarm lesson by ID (--from-swarm). Promotion runs the one policy evaluator inside a single cross-process transaction (#1847). A policy failure blocks promotion unless --force --reason "<why>" is supplied, which records a durable, audited override. An exact entry id alone is never authorization to bypass policy. Either direct text or --from-swarm ID is required.',args:"--category <category>, --from-swarm <lesson-id>, <lesson-text>",category:"utility",toolPolicy:"none"},reset:{handler:(ctx)=>handleResetCommand(ctx.directory,ctx.args),description:"Clear swarm state files [--confirm]",details:"DELETES plan.md, context.md, and summaries/ directory from .swarm/. Stops background automation and clears in-memory queues. SAFETY: requires --confirm flag — without it, displays a warning and tips to export first. Before deleting, auto-backs up the state it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept) so it can be restored by copying the files back.",args:"--confirm (required)",category:"utility",clashesWithNativeCcCommand:"/reset",toolPolicy:"restricted"},"reset-session":{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",details:"Deletes only .swarm/session/state.json and any other session files. Clears in-memory agent sessions and delegation chains. Preserves plan, evidence, and knowledge for cross-session continuity. Before deleting, auto-backs up the session files it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept).",args:"",category:"utility",toolPolicy:"restricted"},rollback:{handler:(ctx)=>handleRollbackCommand(ctx.directory,ctx.args),description:"Restore swarm state or project files to a checkpoint",details:"Restores legacy .swarm/ phase checkpoints from checkpoints/phase-<N> when present. Otherwise restores named git checkpoints from .swarm/checkpoints.json by label or list number. Writes rollback event to events.jsonl. Without an argument, lists available checkpoints.",args:"<phase-number|label|list-number>",category:"utility",toolPolicy:"restricted"},retrieve:{handler:(ctx)=>handleRetrieveCommand(ctx.directory,ctx.args),description:"Retrieve full output from a summary <id>",args:"<summary-id>",details:"Loads the full tool output that was previously summarized (referenced by IDs like S1, S2). Use when you need the complete output instead of the truncated summary.",category:"utility",toolPolicy:"agent"},handoff:{handler:(ctx)=>handleHandoffCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Prepare state for clean model switch (new session)",args:"",details:"Generates handoff.md with full session state snapshot, including plan progress, recent decisions, and agent delegation history. Prepended to the next session prompt for seamless model switches.",category:"core",toolPolicy:"none"},turbo:{handler:(ctx)=>handleTurboCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Turbo Mode strategy for the active session [on|off|lean|standard|epic|status]",args:"on, off, lean, standard, epic, status",details:`Toggles Turbo Mode for the current session. Supports three strategies:
2082
2089
 
2083
- `+`**Standard turbo** — skips non-critical QA gates for faster iteration.
2084
- `+`**Lean turbo** — parallel lane execution with per-lane reviewer gates and file-lock conflict detection.
2090
+ `+`**Standard turbo** — ${TURBO_BYPASS_DISCLOSURE}
2091
+ `+`**Lean turbo** — parallel lane execution with per-lane reviewer gates and file-lock conflict detection. ${TURBO_BYPASS_DISCLOSURE}
2085
2092
  `+"**Epic** — additive overlay above Lean Turbo. Auto-decides per-plan parallel-vs-serial via the coupling coefficient `p` and three gates (p-threshold, hot-module, greenfield). When `/swarm turbo epic on` is selected, Lean Turbo is also enabled — Epic dispatches Lean Turbo when it promotes.\n"+`
2086
2093
  Subcommands:
2087
2094
  `+` turbo on — enable turbo (uses lean when config turbo.strategy is "lean", otherwise standard)
@@ -2121,55 +2128,8 @@ automatically — advisory and never blocking.
2121
2128
  4. Act on the verdict: address REJECT/CONCERNS findings before completing the phase.
2122
2129
 
2123
2130
  Do NOT dispatch the supervisor yourself as a reviewer of code — it is summary-only.
2124
- \`write_architecture_supervisor_evidence\` persists only; it does not run the supervisor.`}function buildCouncilWorkflow(council){if(council?.enabled!==!0)return"";return"## COUNCIL WORKFLOW\n\nANTI-CONFUSION: Do NOT confuse the three council modes:\n(1) `council_mode` — per-task full council replacing Stage B.\n(2) `phase_council` — phase-level holistic review at `phase_complete`.\n(3) `final_council` — project-level final review after all phases.\nNone of these use the General Council (3-agent advisory). The General Council is an early workflow option gated by `council.general.enabled`, not a QA gate.\n\n## A. PER-TASK COUNCIL (when `council_mode` is ON)\n\nWhen `council_mode` is enabled in the QA gate profile, Stage B (reviewer + test_engineer) is **replaced** by the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task. Stage A (`pre_check_batch`) still runs as the pre-review gate.\n\n### PREREQUISITES\n- `declare_council_criteria` must be called for each task before council dispatch.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (task-scoped)\nAfter Stage A passes for a task, in a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`, and `explorer` as parallel Agent tasks. Each member receives task-scoped context:\n- `critic` — task diff + task spec + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — task semantic diff summary + blast radius across changed files\n- `sme` — task domain context + knowledge base entries relevant to the task\n- `test_engineer` — changed test files for the task + coverage delta + known mutation gaps\n- `explorer` — task diff + original task intent + prior slop findings\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions)\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_council_verdicts (the per-task tool, NOT submit_phase_council_verdicts)\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_council_verdicts` with the collected verdicts. The per-task council\nverdict replaces the Stage B gate — APPROVE advances the task, REJECT blocks it.\n\n#### STEP 4 — ACT on the verdict\n- **APPROVE**: Task passes. Proceed to the next task.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Increment `roundNumber`\n and re-convene council after fixes. This is tool-enforced: you cannot bypass it.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Task passes — surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block task advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If `roundNumber >= maxRounds` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — per-task council bypass violations\n- ✗ Calling `submit_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Falling back to Stage B (reviewer + test_engineer only) when `council_mode` is ON — the full council replaces Stage B.\n- ✗ Skipping `declare_council_criteria` before dispatching council members.\n- ✗ Using `submit_phase_council_verdicts` for per-task verdicts — use `submit_council_verdicts`.\n\n## B. PHASE COUNCIL (when `phase_council` is ON)\n\nCRITICAL: `submit_phase_council_verdicts` does NOT run council members.\nIt synthesizes verdicts that you must collect BEFORE calling it.\n\nWhen `phase_council` is enabled in the QA gate profile, a phase-level council review is required before calling `phase_complete`. This is additive to whichever per-task mechanism is active — Stage B (reviewer + test_engineer) runs per task by default, or the full 5-member per-task council if `council_mode` is ON.\n\n### WHEN TO RUN PHASE COUNCIL\nAfter ALL tasks in the current phase have been marked `completed` and their\nper-task gates have passed, and BEFORE calling `phase_complete`, convene the\nphase council for a Phase Dossier Assembly — a holistic review of cross-cutting concerns,\nbehavioral cohesion, and the full body of work completed in the phase.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (phase-scoped)\nIn a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`,\nand `explorer` as parallel Agent tasks. Each member receives phase-scoped context:\n- `critic` — full diff for the phase + all task specs + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — phase-wide semantic diff summary + blast radius across all changed files\n- `sme` — phase domain context + knowledge base entries relevant to the phase\n- `test_engineer` — all changed test files for the phase + coverage delta + known mutation gaps\n- `explorer` — full phase diff + original task intents + prior slop findings across all tasks\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions introduced anywhere in the phase)\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_phase_council_verdicts\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_phase_council_verdicts` with:\n- `phaseNumber`: the phase number just completed (integer, e.g. `1`)\n- `swarmId`: the swarm identifier (e.g. `\"mega\"`)\n- `phaseSummary`: a 2–4 sentence plain-language summary of what the phase accomplished\n- `verdicts`: the array of collected `CouncilMemberVerdict` objects\n- `roundNumber`: 1-indexed (default 1 on first council call for this phase)\n\nThis writes `.swarm/evidence/{phase}/phase-council.json`, which Gate 5 in\n`phase_complete` will read and validate.\n\n#### STEP 4 — READ the response\nInspect `membersAbsent`. If non-empty, dispatch the missing members and re-collect.\nInspect `overallVerdict`.\n\nIf `success: false` and `reason: 'insufficient_quorum'`:\ndispatch ALL absent members in a single parallel batch, wait for all verdicts,\nand re-call `submit_phase_council_verdicts`.\n\n#### STEP 5 — ACT on the verdict, then call phase_complete\n- **APPROVE**: Call `phase_complete`. Gate 5 will pass.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note to the team before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Increment `roundNumber`\n and re-convene council after fixes. This is tool-enforced: you cannot bypass it.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Call `phase_complete` and surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the phase council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If `roundNumber >= maxRounds` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — phase council bypass violations\n- ✗ Calling `submit_phase_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Skipping per-task gates because phase council will catch issues — per-task gates are mandatory regardless.\n- ✗ Calling `phase_complete` before council evidence has been written (Gate 5 will block you).\n- ✗ Treating a prior phase's council verdict as valid for a new phase.\n- ✗ Incrementing `roundNumber` without re-dispatching members for the new round.\n- ✗ Using `submit_council_verdicts` for phase verdicts — use `submit_phase_council_verdicts`.\n\n### ROUND 2 DELIBERATION\nIf round 1 produces REJECT or CONCERNS requiring re-work, every prior-round\ndissenter must be re-dispatched for round 2 focused on the areas they flagged.\nRound 2 must produce NEW agent responses — never reuse round 1 verdicts.\n\n### Retry protocol\nOn re-submission after REJECT/CONCERNS: council members receive (a) the previous\nsynthesis findings plus (b) the diff of what changed since the last round.\nMembers verify prior findings are resolved without re-reviewing unchanged code.\nThe architect resolves any `unresolvedConflicts` in `unifiedFeedbackMd` BEFORE\nsending it to the coder — the coder never sees contradictory instructions."}function buildYourToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return`Task (delegation), ${[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().join(", ")}.`}function buildQaGateSelectionDialogue(modeLabel){return`${modeLabel==="BRAINSTORM"?"Now ask the user which QA gates to enable for this plan — do not select on their behalf.":modeLabel==="SPECIFY"?"Ask the user which QA gates to enable for this plan before suggesting the next step.":"No pending gate selection found in `.swarm/context.md`. Ask the user inline now."}
2125
-
2126
- Present the eleven gates with their defaults (DEFAULT_QA_GATES) as a single user-facing question. Offer the user a one-shot choice: accept defaults, or customize. The eleven gates are:
2127
- - reviewer (default: ON) — code review of coder output
2128
- - test_engineer (default: ON) — test verification of coder output
2129
- - sme_enabled (default: ON) — SME consultation during planning/clarification
2130
- - critic_pre_plan (default: ON) — critic review before plan finalization
2131
- - sast_enabled (default: ON) — static security scanning
2132
- - council_mode (default: OFF) — replaces per-task Stage B (reviewer + test_engineer) with the full 5-member council (critic, reviewer, sme, test_engineer, explorer). When enabled, Stage A still runs, but after Stage A passes, all 5 council members review the task instead of just reviewer + test_engineer. Requires council.enabled: true in config. (recommended for high-impact architecture, public APIs, schema/data mutation, security-sensitive code)
2133
- - hallucination_guard (default: OFF) — when enabled, mandatory per-phase API/signature/claim/citation verification via critic_hallucination_verifier at PHASE-WRAP; phase_complete will REJECT phase completion unless .swarm/evidence/{phase}/hallucination-guard.json exists with an APPROVED verdict (recommended for claim-heavy or research-heavy work)
2134
- - mutation_test (default: OFF) — when enabled, runs mutation testing on source files touched this phase via generate_mutants + mutation_test + write_mutation_evidence at PHASE-WRAP; FAIL verdict blocks phase_complete; WARN is non-blocking (recommended for projects with coverage gaps or safety-critical code)
2135
- - phase_council (default: OFF) — when enabled, a full 5-member council (critic, reviewer, sme, test_engineer, explorer) reviews all work completed in a phase holistically at phase_complete time. This is additive to whichever per-task mechanism is active — Stage B (reviewer + test_engineer) by default, or the full 5-member per-task council if council_mode is ON. Requires council.enabled: true in config.
2136
- - drift_check (default: ON) — when enabled, mandatory per-phase drift verification via critic_drift_verifier at PHASE-WRAP; compares implemented changes against spec.md intent; hard-blocks phase_complete when spec.md exists and drift evidence is missing or REJECTED; advisory-only when no spec.md exists (recommended for all projects with a specification)
2137
- - final_council (default: OFF) — when enabled, the full 5-member council (NOT the General Council) reviews the entire project after all phases complete. The architect dispatches the same five council members (\`critic\`, \`reviewer\`, \`sme\`, \`test_engineer\`, \`explorer\`) at project scope, collects \`CouncilMemberVerdict\` objects, and calls \`write_final_council_evidence\`. This is not General Council mode and does not require \`council.general.enabled\`.
2138
-
2139
- Present all four items together in a single message. One message, defaults pre-stated. Wait for the user's answer to all four:
2140
-
2141
- **1. QA Gates** — accept defaults or customize (the eleven gates listed above).
2142
-
2143
- **2. Parallel Coders** — Parallel coders each run in their own isolated git worktree (a separate working directory on its own branch); each coder's work is committed and merged back to the main tree automatically when it finishes, so concurrent coders never overwrite each other's files. This is safe and faster — but only for tasks whose declared file scopes do NOT overlap. Before you ask, INSPECT the plan's tasks: group the dependency-ready tasks whose file scopes are disjoint, and let your RECOMMENDED count be the number of such independent groups, clamped to the 1-6 range. If task scopes overlap or you cannot determine them, recommend 1 (serial). File-scope disjointness is your recommendation to make, not a runtime-enforced guarantee: if overlapping tasks run in parallel a merge conflict will preserve the work in its worktree and surface an advisory, but it stalls progress — so prefer serial whenever you are unsure. Ask: "How many coders should run in parallel? (default: 1, range: 1-6; my recommendation: <N>, because <independent task groups>)"
2144
-
2145
- **3. Commit Frequency** — "Commit frequency for completed tasks? (default: phase-level only; optional per-task checkpoint commit after each task completion)"
2146
-
2147
- **4. Auto-proceed** — "Auto-advance to the next phase without asking 'Ready for Phase N+1?'? (default: false; runtime toggle via \`/swarm auto-proceed on|off\`)"
2148
-
2149
- Wait for the user to answer all four in a single reply. Then apply:
2150
-
2151
- - For gates: record the user's gate selections.
2152
- - For parallel coders: if the user says a number > 1, write a \`## Pending Parallelization Config\` section to \`.swarm/context.md\` alongside the gate selection:
2153
- \`\`\`
2154
- ## Pending Parallelization Config
2155
- - parallelization_enabled: true
2156
- - max_concurrent_tasks: <user's number>
2157
- - council_parallel: false
2158
- - locked: true
2159
- - recorded_at: <ISO timestamp>
2160
- \`\`\`
2161
- If the user accepts the default (1), skip writing this section entirely — serial execution is the default and needs no config.
2162
-
2163
- - For commit frequency: if the user chooses per-task commits, write this section to \`.swarm/context.md\`:
2164
- \`\`\`
2165
- ## Task Completion Commit Policy
2166
- - commit_after_each_completed_task: true
2167
- - recorded_at: <ISO timestamp>
2168
- \`\`\`
2169
- If the user keeps the default phase-level behavior, do not write this section.
2170
-
2171
- - For auto-proceed: record the user's choice in the \`## Pending QA Gate Selection\` section of \`.swarm/context.md\` as \`- auto_proceed: <true|false>\` so it is persisted into the plan's \`execution_profile\` on save_plan.`}function buildAvailableToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().map((t)=>{let desc=TOOL_DESCRIPTIONS[t];return desc?`${t} (${desc})`:t}).join(", ")}function buildSlashCommandsList(){let SKIP_ALIASES=new Set(Object.entries(COMMAND_REGISTRY).filter(([,entry])=>entry.aliasOf).map(([name])=>name)),READ_ONLY_OBSERVATION=new Set(["status","history","agents","config","show-plan","benchmark","export","retrieve"]),CATEGORY_ORDER=["Session Lifecycle","Planning","Execution Modes","Observation","Knowledge","State Management","Diagnostics"],COMMANDS_BY_CATEGORY={"Session Lifecycle":["finalize","reset","reset-session","handoff","archive"],Planning:["specify","clarify","analyze","show-plan","sync-plan","acknowledge-spec-drift","council"],"Execution Modes":["turbo","full-auto","loop"],Observation:["status","history","agents","config","benchmark","export","evidence","evidence summary","retrieve"],Knowledge:["knowledge","knowledge migrate","knowledge quarantine","knowledge restore","promote","curate"],"State Management":["checkpoint","rollback","write-retro"],Diagnostics:["diagnose","preflight","doctor tools","config doctor","simulate","dark-matter"]},lines=[],subcommandMap={};for(let[cmdName,cmdEntry]of Object.entries(COMMAND_REGISTRY)){let entry=cmdEntry;if(entry.subcommandOf){if(!subcommandMap[entry.subcommandOf])subcommandMap[entry.subcommandOf]=[];subcommandMap[entry.subcommandOf].push(cmdName)}}let compoundsInValidCommands=new Set;for(let category of CATEGORY_ORDER){lines.push(`**${category}**`);let commandNames=COMMANDS_BY_CATEGORY[category];for(let name of commandNames){let entry=COMMAND_REGISTRY[name];if(!entry)continue;if(SKIP_ALIASES.has(name))continue;if(entry.subcommandOf&&!VALID_COMMANDS.includes(name))continue;if(lines.push(`- \`/swarm ${name}\` — ${entry.description}`),entry.subcommandOf&&VALID_COMMANDS.includes(name))compoundsInValidCommands.add(name);if(READ_ONLY_OBSERVATION.has(name))continue;if(entry.details)lines.push(` ${entry.details}`);if(entry.args)lines.push(` Args: ${entry.args}`)}for(let parent of commandNames){let subs=subcommandMap[parent];if(!subs)continue;for(let subName of subs){let subEntry=COMMAND_REGISTRY[subName];if(!subEntry)continue;if(compoundsInValidCommands.has(subName)||subEntry.subcommandOf&&VALID_COMMANDS.includes(subName)||SKIP_ALIASES.has(subName))continue;if(lines.push(` - \`/swarm ${subName}\` — ${subEntry.description}`),subEntry.details)lines.push(` ${subEntry.details}`);if(subEntry.args)lines.push(` Args: ${subEntry.args}`)}}}return lines.join(`
2172
- `)}function createArchitectAgent(model,customPrompt,customAppendPrompt,adversarialTesting,council,uiReview,memoryEnabled=!1,architecturalSupervision,designDocsEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let prompt=ARCHITECT_PROMPT;prompt=resolvePrompt(prompt,customPrompt,customAppendPrompt),prompt=prompt?.replace("{{YOUR_TOOLS}}",buildYourToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{AVAILABLE_TOOLS}}",buildAvailableToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{SLASH_COMMANDS}}",buildSlashCommandsList()),prompt=prompt?.replace(/\{\{QA_GATE_DIALOGUE_SPECIFY\}\}/g,buildQaGateSelectionDialogue("SPECIFY"))?.replace(/\{\{QA_GATE_DIALOGUE_BRAINSTORM\}\}/g,buildQaGateSelectionDialogue("BRAINSTORM"))?.replace(/\{\{QA_GATE_DIALOGUE_PLAN\}\}/g,buildQaGateSelectionDialogue("PLAN"));let councilBlock=buildCouncilWorkflow(council),hasPlaceholder=prompt?.includes("{{COUNCIL_WORKFLOW}}")===!0;if(councilBlock==="")prompt=prompt?.replace(/\n\n\{\{COUNCIL_WORKFLOW\}\}\n\n/g,`
2131
+ \`write_architecture_supervisor_evidence\` persists only; it does not run the supervisor.`}function buildCouncilWorkflow(council){if(council?.enabled!==!0)return"";return"## COUNCIL WORKFLOW\n\nANTI-CONFUSION: Do NOT confuse the three council modes:\n(1) `council_mode` — per-task full council replacing Stage B.\n(2) `phase_council` — phase-level holistic review at `phase_complete`.\n(3) `final_council` — project-level final review after all phases.\nNone of these use the General Council (3-agent advisory). The General Council is an early workflow option gated by `council.general.enabled`, not a QA gate.\n\n## A. PER-TASK COUNCIL (when `council_mode` is ON)\n\nWhen `council_mode` is enabled in the QA gate profile, Stage B (reviewer + test_engineer) is **replaced** by the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task. Stage A (`pre_check_batch`) still runs as the pre-review gate.\n\n### PREREQUISITES\n- `declare_council_criteria` must be called for each task before council dispatch.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (task-scoped)\nAfter Stage A passes for a task, in a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`, and `explorer` as parallel Agent tasks. Each member receives task-scoped context:\n- `critic` — task diff + task spec + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — task semantic diff summary + blast radius across changed files\n- `sme` — task domain context + knowledge base entries relevant to the task\n- `test_engineer` — changed test files for the task + coverage delta + known mutation gaps\n- `explorer` — task diff + original task intent + prior slop findings\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions)\n→ REQUIRED: the `reviewer` member dispatch MUST include a literal `ACCEPTANCE:` line per ACCEPTANCE FIELD RESOLUTION above (same text as the coder delegation for this task). A missing line is BLOCKED by ACCEPTANCE_FIELD_REQUIRED before that member runs. The other four members are not gated by this rule.\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_council_verdicts (the per-task tool, NOT submit_phase_council_verdicts)\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_council_verdicts` with the collected verdicts. The per-task council\nverdict replaces the Stage B gate — APPROVE advances the task, REJECT blocks it.\n\n#### STEP 4 — ACT on the verdict\n- **APPROVE**: Task passes. Proceed to the next task.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Increment `roundNumber`\n and re-convene council after fixes. This is tool-enforced: you cannot bypass it.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Task passes — surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block task advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If `roundNumber >= maxRounds` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — per-task council bypass violations\n- ✗ Calling `submit_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Falling back to Stage B (reviewer + test_engineer only) when `council_mode` is ON — the full council replaces Stage B.\n- ✗ Skipping `declare_council_criteria` before dispatching council members.\n- ✗ Using `submit_phase_council_verdicts` for per-task verdicts — use `submit_council_verdicts`.\n\n## B. PHASE COUNCIL (when `phase_council` is ON)\n\nCRITICAL: `submit_phase_council_verdicts` does NOT run council members.\nIt synthesizes verdicts that you must collect BEFORE calling it.\n\nWhen `phase_council` is enabled in the QA gate profile, a phase-level council review is required before calling `phase_complete`. This is additive to whichever per-task mechanism is active — Stage B (reviewer + test_engineer) runs per task by default, or the full 5-member per-task council if `council_mode` is ON.\n\n### WHEN TO RUN PHASE COUNCIL\nAfter ALL tasks in the current phase have been marked `completed` and their\nper-task gates have passed, and BEFORE calling `phase_complete`, convene the\nphase council for a Phase Dossier Assembly — a holistic review of cross-cutting concerns,\nbehavioral cohesion, and the full body of work completed in the phase.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (phase-scoped)\nIn a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`,\nand `explorer` as parallel Agent tasks. Each member receives phase-scoped context:\n- `critic` — full diff for the phase + all task specs + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — phase-wide semantic diff summary + blast radius across all changed files\n- `sme` — phase domain context + knowledge base entries relevant to the phase\n- `test_engineer` — all changed test files for the phase + coverage delta + known mutation gaps\n- `explorer` — full phase diff + original task intents + prior slop findings across all tasks\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions introduced anywhere in the phase)\n→ REQUIRED: the `reviewer` member dispatch MUST include a literal `ACCEPTANCE:` line per ACCEPTANCE FIELD RESOLUTION above (phase-scoped: concatenate the verbatim FR/SC text for every task in this phase when fr_refs is non-empty, otherwise a one-line phase-derived DONE restatement). A missing line is BLOCKED by ACCEPTANCE_FIELD_REQUIRED before that member runs. The other four members are not gated by this rule.\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_phase_council_verdicts\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_phase_council_verdicts` with:\n- `phaseNumber`: the phase number just completed (integer, e.g. `1`)\n- `swarmId`: the swarm identifier (e.g. `\"mega\"`)\n- `phaseSummary`: a 2–4 sentence plain-language summary of what the phase accomplished\n- `verdicts`: the array of collected `CouncilMemberVerdict` objects\n- `roundNumber`: 1-indexed (default 1 on first council call for this phase)\n\nThis writes `.swarm/evidence/{phase}/phase-council.json`, which Gate 5 in\n`phase_complete` will read and validate.\n\n#### STEP 4 — READ the response\nInspect `membersAbsent`. If non-empty, dispatch the missing members and re-collect.\nInspect `overallVerdict`.\n\nIf `success: false` and `reason: 'insufficient_quorum'`:\ndispatch ALL absent members in a single parallel batch, wait for all verdicts,\nand re-call `submit_phase_council_verdicts`.\n\n#### STEP 5 — ACT on the verdict, then call phase_complete\n- **APPROVE**: Call `phase_complete`. Gate 5 will pass.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note to the team before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Increment `roundNumber`\n and re-convene council after fixes. This is tool-enforced: you cannot bypass it.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Call `phase_complete` and surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the phase council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If `roundNumber >= maxRounds` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — phase council bypass violations\n- ✗ Calling `submit_phase_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Skipping per-task gates because phase council will catch issues — per-task gates are mandatory regardless.\n- ✗ Calling `phase_complete` before council evidence has been written (Gate 5 will block you).\n- ✗ Treating a prior phase's council verdict as valid for a new phase.\n- ✗ Incrementing `roundNumber` without re-dispatching members for the new round.\n- ✗ Using `submit_council_verdicts` for phase verdicts — use `submit_phase_council_verdicts`.\n\n### ROUND 2 DELIBERATION\nIf round 1 produces REJECT or CONCERNS requiring re-work, every prior-round\ndissenter must be re-dispatched for round 2 focused on the areas they flagged.\nRound 2 must produce NEW agent responses — never reuse round 1 verdicts.\n\n### Retry protocol\nOn re-submission after REJECT/CONCERNS: council members receive (a) the previous\nsynthesis findings plus (b) the diff of what changed since the last round.\nMembers verify prior findings are resolved without re-reviewing unchanged code.\nThe architect resolves any `unresolvedConflicts` in `unifiedFeedbackMd` BEFORE\nsending it to the coder — the coder never sees contradictory instructions."}function buildYourToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return`Task (delegation), ${[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().join(", ")}.`}function buildAvailableToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().map((t)=>{let desc=TOOL_DESCRIPTIONS[t];return desc?`${t} (${desc})`:t}).join(", ")}function buildSlashCommandsList(){let SKIP_ALIASES=new Set(Object.entries(COMMAND_REGISTRY).filter(([,entry])=>entry.aliasOf).map(([name])=>name)),READ_ONLY_OBSERVATION=new Set(["status","history","agents","config","show-plan","benchmark","export","retrieve"]),CATEGORY_ORDER=["Session Lifecycle","Planning","Execution Modes","Observation","Knowledge","State Management","Diagnostics"],COMMANDS_BY_CATEGORY={"Session Lifecycle":["finalize","reset","reset-session","handoff","archive"],Planning:["specify","clarify","analyze","show-plan","sync-plan","acknowledge-spec-drift","council"],"Execution Modes":["turbo","full-auto","loop"],Observation:["status","history","agents","config","benchmark","export","evidence","evidence summary","retrieve"],Knowledge:["knowledge","knowledge migrate","knowledge quarantine","knowledge restore","promote","curate"],"State Management":["checkpoint","rollback","write-retro"],Diagnostics:["diagnose","preflight","doctor tools","config doctor","simulate","dark-matter"]},lines=[],subcommandMap={};for(let[cmdName,cmdEntry]of Object.entries(COMMAND_REGISTRY)){let entry=cmdEntry;if(entry.subcommandOf){if(!subcommandMap[entry.subcommandOf])subcommandMap[entry.subcommandOf]=[];subcommandMap[entry.subcommandOf].push(cmdName)}}let compoundsInValidCommands=new Set;for(let category of CATEGORY_ORDER){lines.push(`**${category}**`);let commandNames=COMMANDS_BY_CATEGORY[category];for(let name of commandNames){let entry=COMMAND_REGISTRY[name];if(!entry)continue;if(SKIP_ALIASES.has(name))continue;if(entry.subcommandOf&&!VALID_COMMANDS.includes(name))continue;if(lines.push(`- \`/swarm ${name}\` — ${entry.description}`),entry.subcommandOf&&VALID_COMMANDS.includes(name))compoundsInValidCommands.add(name);if(READ_ONLY_OBSERVATION.has(name))continue;if(entry.details)lines.push(` ${entry.details}`);if(entry.args)lines.push(` Args: ${entry.args}`)}for(let parent of commandNames){let subs=subcommandMap[parent];if(!subs)continue;for(let subName of subs){let subEntry=COMMAND_REGISTRY[subName];if(!subEntry)continue;if(compoundsInValidCommands.has(subName)||subEntry.subcommandOf&&VALID_COMMANDS.includes(subName)||SKIP_ALIASES.has(subName))continue;if(lines.push(` - \`/swarm ${subName}\` — ${subEntry.description}`),subEntry.details)lines.push(` ${subEntry.details}`);if(subEntry.args)lines.push(` Args: ${subEntry.args}`)}}}return lines.join(`
2132
+ `)}function createArchitectAgent(model,customPrompt,customAppendPrompt,adversarialTesting,council,uiReview,memoryEnabled=!1,architecturalSupervision,designDocsEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let prompt=ARCHITECT_PROMPT;prompt=resolvePrompt(prompt,customPrompt,customAppendPrompt),prompt=prompt?.replace("{{YOUR_TOOLS}}",buildYourToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{AVAILABLE_TOOLS}}",buildAvailableToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{SLASH_COMMANDS}}",buildSlashCommandsList());let councilBlock=buildCouncilWorkflow(council),hasPlaceholder=prompt?.includes("{{COUNCIL_WORKFLOW}}")===!0;if(councilBlock==="")prompt=prompt?.replace(/\n\n\{\{COUNCIL_WORKFLOW\}\}\n\n/g,`
2173
2133
 
2174
2134
  `);else if(hasPlaceholder)prompt=prompt?.replace(/\{\{COUNCIL_WORKFLOW\}\}/g,councilBlock);else prompt=`${prompt??""}
2175
2135
 
@@ -2519,7 +2479,12 @@ DELEGATION ENVELOPE FIELDS — include these in every delegation for traceabilit
2519
2479
 
2520
2480
  Before delegating to {{AGENT_PREFIX}}reviewer: call check_gate_status for the current task_id and include the gate results in the GATES field of the reviewer message. Format: GATES: lint=PASS/FAIL, sast_scan=PASS/FAIL, secretscan=PASS/FAIL (use PASS/FAIL/skipped for each gate). If no gates have been run yet, use GATES: none.
2521
2481
 
2522
- ACCEPTANCE FIELD RESOLUTION — before every {{AGENT_PREFIX}}coder (and {{AGENT_PREFIX}}reviewer) delegation, populate that delegation's ACCEPTANCE field like this: (1) read the current task's \`fr_refs\` from the plan; (2) if \`fr_refs\` is non-empty, look up EVERY listed FR-###/SC-### id in the current \`.swarm/spec.md\` and copy each one's full requirement text into ACCEPTANCE VERBATIM — byte-for-byte, no summarizing or paraphrasing, and concatenate all of them when a task maps to more than one; (3) if \`fr_refs\` is empty or absent, populate ACCEPTANCE with a task-derived one-line restatement of what DONE looks like instead (the same pattern as \`acceptanceCriteria\` above). ACCEPTANCE must never be empty — lacking a spec mapping is normal and is not a reason to omit it.
2482
+ ACCEPTANCE FIELD RESOLUTION — REQUIRED on every {{AGENT_PREFIX}}coder and {{AGENT_PREFIX}}reviewer Task dispatch. A dispatch with no ACCEPTANCE: line is BLOCKED by the delegation gate before the agent runs (ACCEPTANCE_FIELD_REQUIRED). Resolve it as:
2483
+ 1. Read the current task's \`fr_refs\` from the plan.
2484
+ 2. If \`fr_refs\` is non-empty: look up EVERY listed FR-###/SC-### id in the current \`.swarm/spec.md\` and copy each one's full requirement text into ACCEPTANCE VERBATIM — byte-for-byte, no summarizing or paraphrasing, and concatenate all of them when a task maps to more than one.
2485
+ 3. When the task has no spec mapping: if \`fr_refs\` is empty or absent, populate ACCEPTANCE with a task-derived one-line restatement of what DONE looks like instead (the same pattern as \`acceptanceCriteria\` above).
2486
+ ACCEPTANCE must never be empty — lacking a spec mapping is normal and is not a reason to omit it.
2487
+ NOTE: the plan-task \`acceptance\` field is a different thing. Writing acceptance on the plan task does NOT satisfy this rule. The delegation prompt needs its own literal \`ACCEPTANCE:\` line.
2523
2488
 
2524
2489
  <!-- BEHAVIORAL_GUIDANCE_START -->
2525
2490
  PARTIAL GATE RATIONALIZATIONS — automated gates ≠ agent review. Running SOME gates is NOT compliance:
@@ -2697,7 +2662,7 @@ FILE: src/auth/login.ts
2697
2662
  INPUT: Validate email format, password >= 8 chars
2698
2663
  OUTPUT: Modified file
2699
2664
  CONSTRAINT: Do not modify other functions
2700
- ACCEPTANCE: [copied verbatim from spec.md, or a task-derived DONE restatement see ACCEPTANCE FIELD RESOLUTION]
2665
+ ACCEPTANCE: FR-007 The login endpoint SHALL reject passwords shorter than 8 characters with HTTP 400 and a localized error message.
2701
2666
  SKILLS: file:.claude/skills/engineering-conventions/SKILL.md
2702
2667
 
2703
2668
  {{AGENT_PREFIX}}reviewer
@@ -2705,11 +2670,13 @@ TASK: Review login validation
2705
2670
  FILE: src/auth/login.ts
2706
2671
  CHECK: [security, correctness, edge-cases]
2707
2672
  GATES: lint=PASS, sast_scan=PASS, secretscan=PASS
2708
- ACCEPTANCE: [copied verbatim from spec.md, or a task-derived DONE restatement see ACCEPTANCE FIELD RESOLUTION; same text as the coder delegation for this task]
2673
+ ACCEPTANCE: FR-007 The login endpoint SHALL reject passwords shorter than 8 characters with HTTP 400 and a localized error message.
2709
2674
  SKILLS_USED_BY_CODER: file:.claude/skills/engineering-conventions/SKILL.md
2710
2675
  OUTPUT: VERDICT + RISK + ISSUES + ACCEPTANCE_SATISFACTION
2711
2676
  SKILLS: file:.claude/skills/engineering-conventions/SKILL.md
2712
2677
 
2678
+ NOTE (ACCEPTANCE examples above): the FR-### form applies when fr_refs is non-empty. When the task has no fr_refs, ACCEPTANCE instead carries a one-line task-derived DONE restatement, e.g. "DONE = login rejects <8-char passwords with HTTP 400; the 6 happy-path tests pass." The reviewer delegation for the same task uses the identical ACCEPTANCE text as the coder delegation.
2679
+
2713
2680
  {{AGENT_PREFIX}}test_engineer
2714
2681
  TASK: Generate and run login validation tests
2715
2682
  FILE: src/auth/login.ts