opencode-swarm 7.109.4 → 7.110.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.opencode/skills/swarm/SKILL.md +186 -0
- package/.opencode/skills/swarm-ci-monitor/SKILL.md +369 -0
- package/.opencode/skills/swarm-pr-feedback/SKILL.md +86 -17
- package/dist/cli/{curator-zn1kmwmz.js → curator-4qqzpd85.js} +1 -1
- package/dist/cli/{curator-llm-factory-3hf9xpnd.js → curator-llm-factory-y4kvr1ph.js} +1 -1
- package/dist/cli/{guardrail-explain-hjz1k6w0.js → guardrail-explain-10hh57cr.js} +2 -2
- package/dist/cli/{hive-promoter-j81yj97d.js → hive-promoter-wvxqyayt.js} +1 -1
- package/dist/cli/{index-y3nx3ss0.js → index-1mc2yfc2.js} +12 -8
- package/dist/cli/{index-nvmy7xmj.js → index-khj0knr0.js} +2 -2
- package/dist/cli/{index-zh3qh6m7.js → index-xhsba2sn.js} +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/config/bundled-skills.d.ts +1 -1
- package/dist/index.js +2 -2
- package/package.json +3 -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.109.4",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",".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-pr-feedback",".opencode/skills/swarm-pr-subscribe",".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/worktree-retry-cleanup",".opencode/skills/skill-edit-validation",".opencode/skills/merge-queue-readiness",".opencode/skills/gate-attribution",".opencode/skills/ci-failure-batching","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 .","drift:check":"bun run scripts/drift-check.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"},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","critic_oversight","explorer","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","critic_oversight","explorer","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"]},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"]},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","critic_oversight","explorer","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:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","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","coder"]},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)}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.110.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",".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/worktree-retry-cleanup",".opencode/skills/skill-edit-validation",".opencode/skills/merge-queue-readiness",".opencode/skills/gate-attribution",".opencode/skills/ci-failure-batching","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 .","drift:check":"bun run scripts/drift-check.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"},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","critic_oversight","explorer","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","critic_oversight","explorer","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"]},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"]},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","critic_oversight","explorer","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:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","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","coder"]},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)}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
|
|
|
@@ -157,7 +157,7 @@ Audit (no architect needed): \`/swarm epic status | last | decide | calibration\
|
|
|
157
157
|
|
|
158
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 isActiveStatus(status){return!INACTIVE_STATUSES.has(status??"")}var KNOWLEDGE_SCHEMA_VERSION=2,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,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,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.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,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,AutomationModeSchema,AutomationCapabilitiesSchema,AutomationConfigSchemaBase,AutomationConfigSchema,KnowledgeConfigSchema,MemoryConfigSchema,CuratorConfigSchema,ArchitecturalSupervisionConfigSchema,KnowledgeApplicationConfigSchema,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(3).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)}),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)}),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}),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(),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),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}),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"])}),SkillPropagationConfigSchema=exports_external.object({enabled:exports_external.boolean().default(!0),enforce:exports_external.boolean().default(!1)}),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(),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)}).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}))}).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}})),pr_monitor:PrMonitorConfigSchema.optional(),external_skills:ExternalSkillsConfigSchema.optional(),skills:SkillsConfigSchema.optional()})});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 console.warn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),console.warn("[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(error48){if(!(error48 instanceof Error&&("code"in error48)&&error48.code==="ENOENT")){let errorMessage=error48 instanceof Error?error48.message:String(error48);return console.warn(`[opencode-swarm] ⚠️ CONFIG LOAD FAILURE — config exists at ${configPath} but could not be loaded: ${errorMessage}`),console.warn("[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,console.warn("[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)};console.warn("[opencode-swarm] external_skills config validation failed:"),console.warn(esResult.error.format()),console.warn("[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)){console.warn("[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){console.warn(`[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))console.warn(`[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)console.warn(`[opencode-swarm] gates.${key} config validation failed; that gate section will use defaults and other config sections remain active:`),console.warn(sectionResult.error.format()),delete cleanedGates[key]}let gatesResult=GateConfigSchema.safeParse(cleanedGates);if(gatesResult.success)return{...raw,gates:gatesResult.data};console.warn("[opencode-swarm] gates config validation failed after section cleanup; quality gates will use defaults and other config sections remain active:"),console.warn(gatesResult.error.format());let cleaned={...raw};return delete cleaned.gates,cleaned}function sanitizeSectionConfigs(raw){return sanitizeGatesConfig(sanitizeExternalSkillsConfig(raw))}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(rawUserConfig){let userParseResult=PluginConfigSchema.safeParse(sanitizeSectionConfigs(rawUserConfig??{}));if(userParseResult.success)return console.warn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),userParseResult.data}return console.warn("[opencode-swarm] Merged config validation failed:"),console.warn(result.error.format()),console.warn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}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 console.warn(`[opencode-swarm] Config file too large (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Config file too large after read (max 100 KB): ${configPath}`),console.warn("[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 console.warn(`[opencode-swarm] Invalid config at ${configPath}: expected an object`),console.warn("[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(error48){if(error48.code==="ENOENT")return{config:null,fileExisted:!1,hadError:!1};return console.warn(`[opencode-swarm] Failed to load config from ${configPath}:`,error48 instanceof Error?error48.message:String(error48)),{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(rawUserConfig){let userParseResult=PluginConfigSchema.safeParse(sanitizeSectionConfigs(rawUserConfig??{}));if(userParseResult.success)return console.warn("[opencode-swarm] Project config ignored due to validation errors. Using user config."),userParseResult.data}return console.warn("[opencode-swarm] Merged config validation failed:"),console.warn(result.error.format()),console.warn("[opencode-swarm] ⚠️ SECURITY: Falling back to conservative defaults with guardrails ENABLED. Fix the config file to restore custom configuration."),PluginConfigSchema.parse({guardrails:{enabled:!0}})}if(loadedFromFile&&configHadErrors)return PluginConfigSchema.parse({...mergedRaw,guardrails:{enabled:!0}});return result.data}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(error48){console.warn(`[opencode-swarm] Error reading prompt file ${promptPath}:`,error48 instanceof Error?error48.message:String(error48))}let appendPromptPath=path.join(promptsDir,`${agentName}_append.md`);if(fs.existsSync(appendPromptPath))try{result.appendPrompt=fs.readFileSync(appendPromptPath,"utf-8")}catch(error48){console.warn(`[opencode-swarm] Error reading append prompt ${appendPromptPath}:`,error48 instanceof Error?error48.message:String(error48))}return result}var CONFIG_FILENAME="opencode-swarm.json",PROMPTS_DIR_NAME="opencode-swarm",MAX_CONFIG_FILE_BYTES=102400;var init_loader=__esm(()=>{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()}),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,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 addDeferredWarning(warning){if(deferredWarnings.length<50)deferredWarnings.push(warning)}function getDeferredWarnings(){return[...deferredWarnings]}function clearDeferredWarnings(){deferredWarnings.length=0}var deferredWarnings;var init_warning_buffer=__esm(()=>{deferredWarnings=[]});function resolvePrompt(base,custom2,append){if(custom2)return custom2;if(append)return`${base}
|
|
159
159
|
|
|
160
|
-
${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path2 from"node:path";function warnBundledSkillSyncFailure(err){let message=err instanceof Error?err.message:String(err);console.warn(`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${message}`)}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}),files=[];for(let entry of entries){let relativeEntry=path2.join(relativeDir,entry.name),sourcePath=path2.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))continue;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 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 fsp.mkdir(path2.dirname(destPath),{recursive:!0}),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 syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){try{let sourceRoot=path2.join(packageRoot,".opencode","skills"),opencodeDir=path2.join(projectDirectory,".opencode"),skillsDir=path2.join(opencodeDir,"skills");if(!await ensureNotSymlinkedDirectoryAsync(opencodeDir))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(destDir))continue;if(await copyBundledDirectoryBoundedAsync(sourceDir,destDir),!quiet)console.warn(`[opencode-swarm] Synchronized bundled skill .opencode/skills/${slug}/SKILL.md for first-class /swarm command support`)}}catch(err){if(!quiet)warnBundledSkillSyncFailure(err)}}var BUNDLED_PROJECT_SKILLS,MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000;var init_bundled_skills=__esm(()=>{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-pr-feedback","swarm-pr-subscribe","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr","worktree-retry-cleanup","skill-edit-validation","merge-queue-readiness","gate-attribution","ci-failure-batching"]});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=()=>{};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 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=mergedEnv2!==void 0?{...options,env:mergedEnv2}:options,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)}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}
|
|
160
|
+
${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path2 from"node:path";function warnBundledSkillSyncFailure(err){let message=err instanceof Error?err.message:String(err);console.warn(`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${message}`)}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}),files=[];for(let entry of entries){let relativeEntry=path2.join(relativeDir,entry.name),sourcePath=path2.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))continue;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 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 fsp.mkdir(path2.dirname(destPath),{recursive:!0}),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 syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){try{let sourceRoot=path2.join(packageRoot,".opencode","skills"),opencodeDir=path2.join(projectDirectory,".opencode"),skillsDir=path2.join(opencodeDir,"skills");if(!await ensureNotSymlinkedDirectoryAsync(opencodeDir))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(destDir))continue;if(await copyBundledDirectoryBoundedAsync(sourceDir,destDir),!quiet)console.warn(`[opencode-swarm] Synchronized bundled skill .opencode/skills/${slug}/SKILL.md for first-class /swarm command support`)}}catch(err){if(!quiet)warnBundledSkillSyncFailure(err)}}var BUNDLED_PROJECT_SKILLS,MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000;var init_bundled_skills=__esm(()=>{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","worktree-retry-cleanup","skill-edit-validation","merge-queue-readiness","gate-attribution","ci-failure-batching"]});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=()=>{};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 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=mergedEnv2!==void 0?{...options,env:mergedEnv2}:options,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)}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}});var exports_runner_client={};__export(exports_runner_client,{probe:()=>probe,execute:()=>execute,buildDefaultPolicy:()=>buildDefaultPolicy,_resetProbeCache:()=>_resetProbeCache,_internals:()=>_internals4,RUNNER_EXIT_CODES:()=>RUNNER_EXIT_CODES});import{spawn,spawnSync}from"node:child_process";import*as fs4 from"node:fs";import*as os2 from"node:os";import*as path6 from"node:path";import{fileURLToPath}from"node:url";function findRunnerBinary(){let arch=process.arch==="x64"?"x64":"arm64",platform="win32",packagePaths=[path6.resolve(_runtimeDir,"..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe"),path6.resolve(_runtimeDir,"..","..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe")];for(let p of packagePaths)try{if(fs4.existsSync(p))return p}catch{}try{let result=spawnSync("where",["swarm-sandbox-runner.exe"],{windowsHide:!0,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","ignore"]});if(result.status===0&&result.stdout?.trim())return result.stdout.trim().split(`
|
|
162
162
|
`)[0]?.trim()??null}catch{}return null}function probe(){if(_cachedProbe!==void 0)return _cachedProbe;if(process.platform!=="win32")return _cachedProbe={available:!1,mode:"none",capabilities:null,error:"not Windows"},_cachedProbe;let binary=_internals4.findRunnerBinary();if(!binary)return _cachedProbe={available:!1,mode:"none",capabilities:null,error:"runner binary not found"},warn("Sandbox runner binary not found — degrading to weak sandbox"),_cachedProbe;try{let result=_internals4.spawnRunner(binary,["--probe"],{windowsHide:!0,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","pipe"],cwd:os2.tmpdir()});if(result.error)return _cachedProbe={available:!1,mode:"none",capabilities:null,error:`probe spawn error: ${result.error.code??result.error.message}`},warn(`Sandbox runner probe failed: ${_cachedProbe.error}`),_cachedProbe;if(result.status!==0)return _cachedProbe={available:!1,mode:"none",capabilities:null,error:`probe exited with code ${result.status}`},warn(`Sandbox runner probe failed: ${_cachedProbe.error}`),_cachedProbe;let capabilities=JSON.parse(result.stdout?.trim()??"{}"),mode="none";if(capabilities.app_container_available)mode="app-container";else if(capabilities.restricted_token_available)mode="restricted-token";return _cachedProbe={available:mode!=="none",mode,capabilities},_cachedProbe}catch(err){let msg=err instanceof Error?err.message:String(err);return _cachedProbe={available:!1,mode:"none",capabilities:null,error:`probe threw: ${msg}`},warn(`Sandbox runner probe threw: ${msg}`),_cachedProbe}}async function execute(command,policy,mode="auto"){let binary=_internals4.findRunnerBinary();if(!binary)throw Error("runner binary not found");let policyJson=JSON.stringify(policy),args2=["--policy-stdin","--mode",mode,"--",...command];return new Promise((resolve5,reject)=>{let proc,timeout=setTimeout(()=>{proc?.kill(),reject(Error("runner execution timeout"))},policy.wall_clock_timeout_ms+5000),unref=timeout.unref;if(typeof unref==="function")unref.call(timeout);try{proc=_internals4.spawnAsync(binary,args2,{windowsHide:!0,stdio:["pipe","pipe","pipe"],cwd:policy.workspace_roots[0]??os2.tmpdir()})}catch(err){clearTimeout(timeout),reject(err);return}proc.stdin?.write(policyJson),proc.stdin?.end();let stdout="",stderr="",events=[];proc.stdout?.on("data",(chunk)=>{stdout+=chunk.toString()}),proc.stderr?.on("data",(chunk)=>{let lines=chunk.toString().split(`
|
|
163
163
|
`);for(let line of lines){let trimmed=line.trim();if(!trimmed)continue;try{let event=JSON.parse(trimmed);if(event.type){events.push(event);continue}}catch{}stderr+=`${trimmed}
|