opencode-swarm 7.134.1 → 7.134.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{config-doctor-4avzz3rh.js → config-doctor-wk7xzrma.js} +2 -2
- package/dist/cli/{curation-policy-8vkzjtwb.js → curation-policy-npgspa14.js} +2 -2
- package/dist/cli/{curator-llm-factory-2qk8q4y9.js → curator-llm-factory-tpc0qg6x.js} +13 -13
- package/dist/cli/{curator-3vsvhwav.js → curator-njzxdyav.js} +13 -13
- package/dist/cli/{evidence-summary-service-mrzsjpg4.js → evidence-summary-service-pay9409b.js} +1 -1
- package/dist/cli/{guardrail-explain-tw521x47.js → guardrail-explain-75pr3e9z.js} +14 -14
- package/dist/cli/{guardrail-log-e3jrwdw8.js → guardrail-log-783svw0e.js} +3 -3
- package/dist/cli/{hive-promoter-sdy5qjzn.js → hive-promoter-nrxjatdx.js} +13 -13
- package/dist/cli/{index-1v5mby7t.js → index-0dszfjf3.js} +1 -1
- package/dist/cli/{index-463k8mfr.js → index-1bytvz73.js} +2 -2
- package/dist/cli/{index-mz6sqtm9.js → index-225t7m1j.js} +15 -15
- package/dist/cli/{index-kwm7hz18.js → index-4cnwvmsm.js} +5 -5
- package/dist/cli/{index-9z1q181f.js → index-746ga67b.js} +1 -1
- package/dist/cli/{index-k742ecbm.js → index-8fhg2nt2.js} +2 -2
- package/dist/cli/{index-pz49rx4y.js → index-9299e7d5.js} +2 -2
- package/dist/cli/{index-6b69mp0r.js → index-a0nk83rk.js} +2 -2
- package/dist/cli/{index-8t9xpn1a.js → index-asd9n0ms.js} +1 -1
- package/dist/cli/{index-zjw32rv9.js → index-ca44jww3.js} +1 -1
- package/dist/cli/{index-358f9h8p.js → index-cav39zjt.js} +58 -38
- package/dist/cli/{index-c0e3vhv9.js → index-n48xwynh.js} +1 -1
- package/dist/cli/{index-m8ajf6wb.js → index-njfcm1tn.js} +3 -3
- package/dist/cli/{index-bq2848a3.js → index-ss26e2d4.js} +1 -1
- package/dist/cli/{index-y2esw64s.js → index-v8m282zt.js} +1 -1
- package/dist/cli/{index-2j8f71c3.js → index-x60gpbt5.js} +4 -4
- package/dist/cli/{index-0541h76w.js → index-y8vqsm2g.js} +1 -1
- package/dist/cli/index.js +13 -13
- package/dist/cli/{knowledge-escalator-v09w0jmg.js → knowledge-escalator-b3b91k0t.js} +3 -3
- package/dist/cli/{knowledge-events-qp19r2he.js → knowledge-events-kyw0s745.js} +1 -1
- package/dist/cli/{knowledge-store-n5pvv0s3.js → knowledge-store-5watc2b2.js} +1 -1
- package/dist/cli/{knowledge-validator-qg31ycbb.js → knowledge-validator-a4wxkgbc.js} +4 -4
- package/dist/cli/{scan-cursor-wtzfvkh2.js → scan-cursor-gcd771kn.js} +2 -2
- package/dist/cli/{schema-erk5bz43.js → schema-6eghf6gt.js} +1 -1
- package/dist/cli/{skill-generator-nxs65tq3.js → skill-generator-8dswjh14.js} +5 -5
- package/dist/hooks/shell-write-detect.d.ts +1 -1
- package/dist/index.js +3 -3
- package/package.json +1 -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.134.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@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","critic_finding_validator"],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]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}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_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},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_finding_validator","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_finding_validator","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"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","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","critic_finding_validator"]},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_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","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. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,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.134.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@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","critic_finding_validator"],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]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}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_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},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_finding_validator","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_finding_validator","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"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},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_finding_validator","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","critic_finding_validator"]},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_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","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. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,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
|
|
|
@@ -186,7 +186,7 @@ ${USAGE}`}}var USAGE,KNOWN_MODES;var init_abort_pr_workflow=__esm(()=>{init_pr_w
|
|
|
186
186
|
`),KNOWN_MODES=new Set(["PR_REVIEW","PR_FEEDBACK"])});var exports_runner_client={};__export(exports_runner_client,{probe:()=>probe,execute:()=>execute,buildDefaultPolicy:()=>buildDefaultPolicy,_resetProbeCache:()=>_resetProbeCache,_internals:()=>_internals7,RUNNER_EXIT_CODES:()=>RUNNER_EXIT_CODES});import{spawn as spawn2,spawnSync as spawnSync2}from"node:child_process";import*as fs8 from"node:fs";import*as os3 from"node:os";import*as path12 from"node:path";import{fileURLToPath}from"node:url";function findRunnerBinary(){let arch=process.arch==="x64"?"x64":"arm64",platform="win32",packagePaths=[path12.resolve(_runtimeDir,"..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe"),path12.resolve(_runtimeDir,"..","..","..","..","binaries",`win32-${arch}`,"swarm-sandbox-runner.exe")];for(let p of packagePaths)try{if(fs8.existsSync(p))return p}catch{}try{let result=spawnSync2("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(`
|
|
187
187
|
`)[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=_internals7.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=_internals7.spawnRunner(binary,["--probe"],{windowsHide:!0,encoding:"utf-8",timeout:2000,stdio:["ignore","pipe","pipe"],cwd:os3.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=_internals7.findRunnerBinary();if(!binary)throw Error("runner binary not found");let policyJson=JSON.stringify(policy),args2=["--policy-stdin","--mode",mode,"--",...command];return new Promise((resolve9,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=_internals7.spawnAsync(binary,args2,{windowsHide:!0,stdio:["pipe","pipe","pipe"],cwd:policy.workspace_roots[0]??os3.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(`
|
|
188
188
|
`);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}
|
|
189
|
-
`}}),proc.on("error",(err)=>{clearTimeout(timeout),reject(err)}),proc.on("close",(code)=>{clearTimeout(timeout);let runnerMode=events.find((e)=>e.type==="start")?.mode??mode;resolve9({exitCode:code??1,stdout,stderr,events,mode:runnerMode})})})}function _resetProbeCache(){_cachedProbe=void 0}function buildDefaultPolicy(workspaceRoot,runId){let id=runId??`swarm-${crypto.randomUUID?.()??Date.now()}`,appData=process.env.LOCALAPPDATA??path12.join(os3.homedir(),"AppData","Local"),tempRoot=path12.join(appData,"opencode-swarm","sandbox",id,"temp");return{schema_version:1,run_id:id,workspace_roots:[workspaceRoot],writable_roots:[workspaceRoot],read_only_subpaths:[".git",".codex",".agents",".swarm"],temp_root:tempRoot,temp_cap_bytes:524288000,memory_cap_bytes:2147483648,child_process_cap:16,wall_clock_timeout_ms:600000,network_mode:"off",env_allowlist:["PATH","TEMP","TMP","USERPROFILE","SYSTEMROOT"],env_overrides:{HTTP_PROXY:"http://127.0.0.1:1",HTTPS_PROXY:"http://127.0.0.1:1"},path_stubs:["ssh.exe","curl.exe","wget.exe","scp.exe","sftp.exe"],private_desktop:!0,deny_alternate_data_streams:!0,deny_unc_paths:!0,deny_device_paths:!0,deny_symlink_egress:!0}}var _runtimeDir,RUNNER_EXIT_CODES,_cachedProbe,_internals7;var init_runner_client=__esm(()=>{init_logger();_runtimeDir=fileURLToPath(new URL(".",import.meta.url)),RUNNER_EXIT_CODES={SUCCESS:0,CHILD_NON_ZERO:1,POLICY_VIOLATION:64,QUOTA_EXCEEDED:65,WALL_CLOCK_TIMEOUT:66,LAUNCHER_MISCONFIG:67,OS_API_FAILURE:68,PROBE_FAILED:69},_internals7={findRunnerBinary,spawnRunner:spawnSync2,spawnAsync:spawn2}});var exports_capability_probe={};__export(exports_capability_probe,{isWindowsSandboxAvailable:()=>isWindowsSandboxAvailable,isSandboxExecAvailable:()=>isSandboxExecAvailable,isBubblewrapAvailable:()=>isBubblewrapAvailable,SandboxCapabilityProbe:()=>SandboxCapabilityProbe});import{execFile,spawnSync as spawnSync3}from"node:child_process";import*as os4 from"node:os";function withProbeTimeout(cmd,args2,ms){return new Promise((resolve9,reject)=>{let controller=new AbortController,timer=setTimeout(()=>{controller.abort(),proc?.kill()},ms),unref=timer.unref;if(typeof unref==="function")unref.call(timer);let proc;try{proc=execFile(cmd,args2,{signal:controller.signal,timeout:ms,windowsHide:!0,cwd:os4.tmpdir()},(error49,stdout,_stderr)=>{if(clearTimeout(timer),error49){let exc=error49;if(exc.code==="ENOENT"||exc.code==="ENOTFOUND")reject(Error("binary not found"));else reject(error49);return}resolve9(stdout?.trim()??"")})}catch(spawnError){clearTimeout(timer),reject(spawnError)}})}async function probeLinux(){try{if((await withProbeTimeout("bwrap",["--version"],2000)).length>0)return{status:"enabled",strength:"strong",mechanism:"Bubblewrap",platform:"linux"};return{status:"disabled",mechanism:"Bubblewrap",platform:"linux",error:"binary returned empty version"}}catch(err){let msg=err instanceof Error?err.message:String(err);if(msg==="binary not found")return{status:"unsupported",mechanism:"Bubblewrap",platform:"linux",error:msg};return{status:"disabled",mechanism:"Bubblewrap",platform:"linux",error:msg}}}async function probeMacOS(){try{if((await withProbeTimeout("sandbox-exec",["--version"],2000)).length>0)return{status:"enabled",strength:"strong",mechanism:"sandbox-exec",platform:"darwin"};return{status:"disabled",mechanism:"sandbox-exec",platform:"darwin",error:"binary returned empty version"}}catch(err){let msg=err instanceof Error?err.message:String(err);if(msg==="binary not found")return{status:"unsupported",mechanism:"sandbox-exec",platform:"darwin",error:msg};return{status:"disabled",mechanism:"sandbox-exec",platform:"darwin",error:msg}}}function probeWindows(){try{let{probe:runnerProbe}=(init_runner_client(),__toCommonJS(exports_runner_client)),result=runnerProbe();if(result.available)return{status:"enabled",strength:"strong",platform:"win32",mechanism:`native-runner/${result.mode}`}}catch{}try{let result=spawnSync3("cmd",["/c","echo","ok"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error)return{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:`cmd.exe probe failed: ${result.error.code}`};return result.status===0?{status:"enabled",strength:"advisory",platform:"win32",mechanism:"PowerShell wrapper"}:{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:"cmd.exe probe returned non-zero"}}catch(err){return{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:String(err)}}}function isBubblewrapAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="linux"}function isSandboxExecAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="darwin"}function isWindowsSandboxAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="win32"}class SandboxCapabilityProbe{async detect(){if(_cached!==void 0)return _cached;let platform=process.platform;switch(platform){case"linux":_cached=await probeLinux();break;case"darwin":_cached=await probeMacOS();break;case"win32":_cached=probeWindows();break;default:_cached={status:"unsupported",mechanism:"unknown",platform,error:`unsupported platform: ${platform}`}}return _cached}}var _cached;var init_capability_probe=()=>{};import{spawnSync as spawnSync4}from"node:child_process";function probeBwrap(){try{let result=spawnSync4("bwrap",["--version"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error){let code=result.error.code;if(code&&BWRAP_UNAVAILABLE_CODES.has(code))return warn(`Sandbox disabled: bwrap error (${code}). Falling through to tool-layer enforcement.`),!1;return warn(`Sandbox disabled: bwrap spawn error (${result.error.message}). Falling through to tool-layer enforcement.`),!1}return result.status===BWRAP_VERSION_EXIT&&result.stdout.trim().length>0}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`Sandbox disabled: probe threw (${message}). Falling through to tool-layer enforcement.`),!1}}function shellEscape(s){return s.replace(/'/g,"'\\''")}class BubblewrapSandboxExecutor{mechanism="Bubblewrap";_scopePaths;_tempDir;_available;_disabledReason;constructor(scopePaths=[],tempDir){this._scopePaths=scopePaths,this._tempDir=tempDir,this._available=!1,this._disabledReason=null;try{if(!_internals8.probeBwrap())this._disabledReason="bwrap not available or not functional",warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`);else this._available=!0}catch(err){let message=err instanceof Error?err.message:String(err);this._disabledReason=`constructor threw: ${message}`,this._available=!1,warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`)}}isAvailable(){return this._available}disable(reason){this._available=!1,this._disabledReason=reason,warn(`Sandbox disabled: ${reason}. Falling through to tool-layer enforcement.`)}wrapCommand(command,scopePaths,tempDir,envOverrides){if(!this._available)throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");let temp=tempDir??this._tempDir??"/tmp",bindArgs=[...this._scopePaths,...scopePaths].flatMap((p)=>["--bind",`'${shellEscape(p)}'`,`'${shellEscape(p)}'`]),envArgs=[];if(envOverrides)for(let[key,value]of Object.entries(envOverrides)){if(!isValidEnvKey(key))continue;if(value===null)envArgs.push("--unsetenv",key);else envArgs.push("--setenv",key,value)}return`bwrap ${["--unshare-user","--unshare-net","--unshare-ipc","--die-with-parent","--new-session","--cap-drop","ALL",...bindArgs,"--dev","/dev","--size",
|
|
189
|
+
`}}),proc.on("error",(err)=>{clearTimeout(timeout),reject(err)}),proc.on("close",(code)=>{clearTimeout(timeout);let runnerMode=events.find((e)=>e.type==="start")?.mode??mode;resolve9({exitCode:code??1,stdout,stderr,events,mode:runnerMode})})})}function _resetProbeCache(){_cachedProbe=void 0}function buildDefaultPolicy(workspaceRoot,runId){let id=runId??`swarm-${crypto.randomUUID?.()??Date.now()}`,appData=process.env.LOCALAPPDATA??path12.join(os3.homedir(),"AppData","Local"),tempRoot=path12.join(appData,"opencode-swarm","sandbox",id,"temp");return{schema_version:1,run_id:id,workspace_roots:[workspaceRoot],writable_roots:[workspaceRoot],read_only_subpaths:[".git",".codex",".agents",".swarm"],temp_root:tempRoot,temp_cap_bytes:524288000,memory_cap_bytes:2147483648,child_process_cap:16,wall_clock_timeout_ms:600000,network_mode:"off",env_allowlist:["PATH","TEMP","TMP","USERPROFILE","SYSTEMROOT"],env_overrides:{HTTP_PROXY:"http://127.0.0.1:1",HTTPS_PROXY:"http://127.0.0.1:1"},path_stubs:["ssh.exe","curl.exe","wget.exe","scp.exe","sftp.exe"],private_desktop:!0,deny_alternate_data_streams:!0,deny_unc_paths:!0,deny_device_paths:!0,deny_symlink_egress:!0}}var _runtimeDir,RUNNER_EXIT_CODES,_cachedProbe,_internals7;var init_runner_client=__esm(()=>{init_logger();_runtimeDir=fileURLToPath(new URL(".",import.meta.url)),RUNNER_EXIT_CODES={SUCCESS:0,CHILD_NON_ZERO:1,POLICY_VIOLATION:64,QUOTA_EXCEEDED:65,WALL_CLOCK_TIMEOUT:66,LAUNCHER_MISCONFIG:67,OS_API_FAILURE:68,PROBE_FAILED:69},_internals7={findRunnerBinary,spawnRunner:spawnSync2,spawnAsync:spawn2}});var exports_capability_probe={};__export(exports_capability_probe,{isWindowsSandboxAvailable:()=>isWindowsSandboxAvailable,isSandboxExecAvailable:()=>isSandboxExecAvailable,isBubblewrapAvailable:()=>isBubblewrapAvailable,SandboxCapabilityProbe:()=>SandboxCapabilityProbe});import{execFile,spawnSync as spawnSync3}from"node:child_process";import*as os4 from"node:os";function withProbeTimeout(cmd,args2,ms){return new Promise((resolve9,reject)=>{let controller=new AbortController,timer=setTimeout(()=>{controller.abort(),proc?.kill()},ms),unref=timer.unref;if(typeof unref==="function")unref.call(timer);let proc;try{proc=execFile(cmd,args2,{signal:controller.signal,timeout:ms,windowsHide:!0,cwd:os4.tmpdir()},(error49,stdout,_stderr)=>{if(clearTimeout(timer),error49){let exc=error49;if(exc.code==="ENOENT"||exc.code==="ENOTFOUND")reject(Error("binary not found"));else reject(error49);return}resolve9(stdout?.trim()??"")})}catch(spawnError){clearTimeout(timer),reject(spawnError)}})}async function probeLinux(){try{if((await withProbeTimeout("bwrap",["--version"],2000)).length>0)return{status:"enabled",strength:"strong",mechanism:"Bubblewrap",platform:"linux"};return{status:"disabled",mechanism:"Bubblewrap",platform:"linux",error:"binary returned empty version"}}catch(err){let msg=err instanceof Error?err.message:String(err);if(msg==="binary not found")return{status:"unsupported",mechanism:"Bubblewrap",platform:"linux",error:msg};return{status:"disabled",mechanism:"Bubblewrap",platform:"linux",error:msg}}}async function probeMacOS(){try{if((await withProbeTimeout("sandbox-exec",["--version"],2000)).length>0)return{status:"enabled",strength:"strong",mechanism:"sandbox-exec",platform:"darwin"};return{status:"disabled",mechanism:"sandbox-exec",platform:"darwin",error:"binary returned empty version"}}catch(err){let msg=err instanceof Error?err.message:String(err);if(msg==="binary not found")return{status:"unsupported",mechanism:"sandbox-exec",platform:"darwin",error:msg};return{status:"disabled",mechanism:"sandbox-exec",platform:"darwin",error:msg}}}function probeWindows(){try{let{probe:runnerProbe}=(init_runner_client(),__toCommonJS(exports_runner_client)),result=runnerProbe();if(result.available)return{status:"enabled",strength:"strong",platform:"win32",mechanism:`native-runner/${result.mode}`}}catch{}try{let result=spawnSync3("cmd",["/c","echo","ok"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error)return{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:`cmd.exe probe failed: ${result.error.code}`};return result.status===0?{status:"enabled",strength:"advisory",platform:"win32",mechanism:"PowerShell wrapper"}:{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:"cmd.exe probe returned non-zero"}}catch(err){return{status:"disabled",platform:"win32",mechanism:"PowerShell wrapper",error:String(err)}}}function isBubblewrapAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="linux"}function isSandboxExecAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="darwin"}function isWindowsSandboxAvailable(){return _cached?.status==="enabled"&&_cached?.platform==="win32"}class SandboxCapabilityProbe{async detect(){if(_cached!==void 0)return _cached;let platform=process.platform;switch(platform){case"linux":_cached=await probeLinux();break;case"darwin":_cached=await probeMacOS();break;case"win32":_cached=probeWindows();break;default:_cached={status:"unsupported",mechanism:"unknown",platform,error:`unsupported platform: ${platform}`}}return _cached}}var _cached;var init_capability_probe=()=>{};import{spawnSync as spawnSync4}from"node:child_process";function probeBwrap(){try{let result=spawnSync4("bwrap",["--version"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error){let code=result.error.code;if(code&&BWRAP_UNAVAILABLE_CODES.has(code))return warn(`Sandbox disabled: bwrap error (${code}). Falling through to tool-layer enforcement.`),!1;return warn(`Sandbox disabled: bwrap spawn error (${result.error.message}). Falling through to tool-layer enforcement.`),!1}return result.status===BWRAP_VERSION_EXIT&&result.stdout.trim().length>0}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`Sandbox disabled: probe threw (${message}). Falling through to tool-layer enforcement.`),!1}}function shellEscape(s){return s.replace(/'/g,"'\\''")}class BubblewrapSandboxExecutor{mechanism="Bubblewrap";_scopePaths;_tempDir;_available;_disabledReason;constructor(scopePaths=[],tempDir){this._scopePaths=scopePaths,this._tempDir=tempDir,this._available=!1,this._disabledReason=null;try{if(!_internals8.probeBwrap())this._disabledReason="bwrap not available or not functional",warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`);else this._available=!0}catch(err){let message=err instanceof Error?err.message:String(err);this._disabledReason=`constructor threw: ${message}`,this._available=!1,warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`)}}isAvailable(){return this._available}disable(reason){this._available=!1,this._disabledReason=reason,warn(`Sandbox disabled: ${reason}. Falling through to tool-layer enforcement.`)}wrapCommand(command,scopePaths,tempDir,envOverrides){if(!this._available)throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");let temp=tempDir??this._tempDir??"/tmp",bindArgs=[...this._scopePaths,...scopePaths].flatMap((p)=>["--bind",`'${shellEscape(p)}'`,`'${shellEscape(p)}'`]),envArgs=[];if(envOverrides)for(let[key,value]of Object.entries(envOverrides)){if(!isValidEnvKey(key))continue;if(value===null)envArgs.push("--unsetenv",key);else envArgs.push("--setenv",key,value)}return`bwrap ${["--unshare-user","--unshare-net","--unshare-ipc","--die-with-parent","--new-session","--cap-drop","ALL",...bindArgs,"--dev","/dev","--size",String(TMPFS_SIZE_BYTES),"--tmpfs",`'${shellEscape(temp)}'`,"--ro-bind","/etc","/etc","--ro-bind","/usr","/usr","--ro-bind","/lib","/lib","--ro-bind","/lib64","/lib64","--proc","/proc","--unshare-pid",...envArgs,"--","bash","-c",`'${shellEscape(command)}'`].join(" ")}`}getEnvOverrides(){return{}}}var BWRAP_VERSION_EXIT=0,BWRAP_UNAVAILABLE_CODES,TMPFS_SIZE_BYTES=524288000,_internals8;var init_bubblewrap_executor=__esm(()=>{init_logger();init_executor();BWRAP_UNAVAILABLE_CODES=new Set(["ENOENT","EACCES","ENOSPC"]);_internals8={probeBwrap}});var exports_bubblewrap={};__export(exports_bubblewrap,{BubblewrapSandboxExecutor:()=>BubblewrapSandboxExecutor});var init_bubblewrap=__esm(()=>{init_bubblewrap_executor()});import{spawnSync as spawnSync5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync3}from"node:fs";import*as os5 from"node:os";import*as path13 from"node:path";function probeSandboxExec(){try{let result=spawnSync5("sandbox-exec",["--version"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error){let code=result.error.code;if(code&&SANDBOX_UNAVAILABLE_CODES.has(code))return warn(`Sandbox disabled: sandbox-exec error (${code}). Falling through to tool-layer enforcement.`),!1;return warn(`Sandbox disabled: spawn error (${result.error.message}). Falling through to tool-layer enforcement.`),!1}return result.status===0}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`Sandbox disabled: probe threw (${message}). Falling through to tool-layer enforcement.`),!1}}function shellEscape2(s){return s.replace(/'/g,"'\\''")}function sbplEscapePath(path14){return path14.split("").filter((ch)=>{let cp=ch.codePointAt(0);return cp>=32&&cp!==127}).join("").replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}function buildSandboxProfile(scopePaths,tempDir,envOverrides){let rwPaths=[...scopePaths];if(tempDir)rwPaths.push(tempDir);let rwAllowLines=rwPaths.map((p)=>`(allow file-write* (subpath "${sbplEscapePath(p)}"))`).join(`
|
|
190
190
|
`),envLines=[];if(envOverrides)for(let[key,value]of Object.entries(envOverrides)){if(!isValidEnvKey(key))continue;if(value===null)envLines.push(`(unsetenv ${key})`);else{let escaped=value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");envLines.push(`(setenv ${key} "${escaped}")`)}}return`(version 1)
|
|
191
191
|
(allow default)
|
|
192
192
|
(allow file-read* (subpath "/usr"))
|
|
@@ -689,7 +689,7 @@ in`);return tk},In(tk,iterable){if((iterable.behind(1)||tokens.mkToken("EMPTY"))
|
|
|
689
689
|
`)}};module.exports=()=>compose(filterNonNull,map2(tokens.applyTokenizerVisitor(SkipRepeatedNewLines)),lookahead)});var require_assignment_word=__commonJS((exports,module)=>{var map2=require_map_iterable(),isValidName=require_is_valid_name();module.exports=function(){return map2((tk,idx,ctx)=>{if(tk._.maybeStartOfSimpleCommand)ctx.commandPrefixNotAllowed=!1;if(!ctx.commandPrefixNotAllowed&&tk.is("WORD")&&tk.value.indexOf("=")>0&&isValidName(tk.value.slice(0,tk.value.indexOf("="))))return tk.changeTokenType("ASSIGNMENT_WORD",tk.value);return ctx.commandPrefixNotAllowed=!0,tk})}});var require_syntaxerror_oncontinue=__commonJS((exports,module)=>{var map2=require_map_iterable();module.exports=function(){return map2((tk)=>{if(tk&&tk.is("CONTINUE"))throw SyntaxError("Unclosed "+tk.value);return tk})}});var require_rules=__commonJS((exports)=>{exports.parameterExpansion=require_parameter_expansion();exports.commandExpansion=require_command_expansion();exports.arithmeticExpansion=require_arithmetic_expansion();exports.aliasSubstitution=require_alias_substitution2();exports.defaultNodeType=require_default_node_type();exports.fieldSplitting=require_field_splitting();exports.tildeExpanding=require_tilde_expanding();exports.pathExpansion=require_path_expansion();exports.quoteRemoval=require_quote_removal();exports.identifySimpleCommandNames=require_identify_simplecommand_names();exports.identifyMaybeSimpleCommands=require_identify_maybe_simple_commands();exports.operatorTokens=require_operator_tokens();exports.reservedWords=require_reserved_words();exports.separator=require_separator();exports.linebreakIn=require_linebreak_in();exports.forNameVariable=require_for_name_variable();exports.functionName=require_function_name();exports.ioNumber=require_io_number();exports.newLineList=require_new_line_list();exports.assignmentWord=require_assignment_word();exports.syntaxerrorOnContinue=require_syntaxerror_oncontinue()});var require_grammar=__commonJS((exports,module)=>{module.exports={start:"complete_command",bnf:{complete_command:[["list separator EOF"," return yy.checkAsync($list, $separator)"],["list EOF"," return $list "],["separator list EOF"," return $list "],["separator list separator EOF"," return yy.checkAsync($list, $separator)"]],list:[["list separator and_or","$$ = yy.listAppend($list, $and_or, $separator);"],["and_or","$$ = yy.list($and_or);"]],and_or:[["pipeline","$$ = $pipeline;"],["and_or AND_IF linebreak pipeline","$$ = yy.andAndOr($and_or, $pipeline);"],["and_or OR_IF linebreak pipeline","$$ = yy.orAndOr($and_or, $pipeline);"]],pipeline:[["pipe_sequence","$$ = yy.pipeLine($pipe_sequence);"],["Bang pipe_sequence","$$ = yy.bangPipeLine($pipe_sequence);"]],pipe_sequence:[["command","$$ = yy.pipeSequence($command);"],["pipe_sequence PIPE linebreak command","$$ = yy.pipeSequenceAppend($pipe_sequence, $command);"]],command:["simple_command","compound_command",["compound_command redirect_list","$$ = yy.addRedirections($compound_command, $redirect_list)"],"function_definition"],compound_command:["brace_group","subshell","for_clause","case_clause","if_clause","while_clause","until_clause"],subshell:[["OPEN_PAREN compound_list CLOSE_PAREN","$$ = yy.subshell($compound_list, $OPEN_PAREN.loc, $CLOSE_PAREN.loc);"]],compound_list:[["term","$$ = $term;"],["NEWLINE_LIST term","$$ = $term;"],["term separator","$$ = yy.checkAsync($term, $separator);"],["NEWLINE_LIST term separator","$$ = yy.checkAsync($term, $separator);"]],term:[["term separator and_or","$$ = yy.termAppend($term, $and_or, $separator);"],["and_or","$$ = yy.term($and_or);"]],for_clause:[["For name linebreak do_group","$$ = yy.forClauseDefault($name, $do_group, $For.loc);"],["For name LINEBREAK_IN separator do_group","$$ = yy.forClauseDefault($name, $do_group, $For.loc);"],["For name In separator do_group","$$ = yy.forClauseDefault($name, $do_group, $For.loc);"],["For name in wordlist separator do_group","$$ = yy.forClause($name, $wordlist, $do_group, $For.loc);"]],name:["NAME"],in:["In"],wordlist:["wordlist_repetition_plus0"],case_clause:[["Case WORD linebreak in linebreak case_list Esac","$$ = yy.caseClause($WORD, $case_list, $Case.loc, $Esac.loc);"],["Case WORD linebreak in linebreak case_list_ns Esac","$$ = yy.caseClause($WORD, $case_list_ns, $Case.loc, $Esac.loc);"],["Case WORD linebreak in linebreak Esac","$$ = yy.caseClause($WORD, null, $Case.loc, $Esac.loc);"]],case_list_ns:[["case_list case_item_ns","$$ = yy.caseListAppend($case_list, $case_item_ns);"],["case_item_ns","$$ = yy.caseList($case_item_ns);"]],case_list:[["case_list case_item","$$ = yy.caseListAppend($case_list, $case_item);"],["case_item","$$ = yy.caseList($case_item);"]],case_item_ns:[["pattern CLOSE_PAREN linebreak","$$ = yy.caseItem($pattern, null, $pattern[0].loc, $CLOSE_PAREN.loc);"],["pattern CLOSE_PAREN compound_list linebreak","$$ = yy.caseItem($pattern, $compound_list, $pattern[0].loc, $compound_list.loc);"],["OPEN_PAREN pattern CLOSE_PAREN linebreak","$$ = yy.caseItem($pattern, null, $OPEN_PAREN.loc, $CLOSE_PAREN.loc );"],["OPEN_PAREN pattern CLOSE_PAREN compound_list linebreak","$$ = yy.caseItem($pattern, $compound_list, $OPEN_PAREN.loc, $compound_list.loc);"]],case_item:[["pattern CLOSE_PAREN linebreak DSEMI linebreak","$$ = yy.caseItem($pattern, null, $pattern[0].loc, $DSEMI.loc);"],["pattern CLOSE_PAREN compound_list DSEMI linebreak","$$ = yy.caseItem($pattern, $compound_list, $pattern[0].loc, $DSEMI.loc);"],["OPEN_PAREN pattern CLOSE_PAREN linebreak DSEMI linebreak","$$ = yy.caseItem($pattern, null, $OPEN_PAREN.loc, $DSEMI.loc );"],["OPEN_PAREN pattern CLOSE_PAREN compound_list DSEMI linebreak","$$ = yy.caseItem($pattern, $compound_list, $OPEN_PAREN.loc, $DSEMI.loc);"]],pattern:[["WORD","$$ = yy.pattern($WORD);"],["pattern PIPE WORD","$$ = yy.patternAppend($pattern, $WORD);"]],if_clause:[["If compound_list Then compound_list else_part Fi","$$ = yy.ifClause($2, $4, $else_part, $If.loc, $Fi.loc);"],["If compound_list Then compound_list Fi","$$ = yy.ifClause($2, $4, null, $If.loc, $Fi.loc);"]],else_part:[["Elif compound_list Then compound_list","$$ = yy.ifClause($2, $4, null, $Elif.loc, $4.loc);"],["Elif compound_list Then compound_list else_part","$$ = yy.ifClause($2, $4, $else_part, $Elif.loc, $else_part.loc);"],["Else compound_list","$$ = yy.elseClause($compound_list, $Else);"]],while_clause:[["While compound_list do_group","$$ = yy.while($2, $3, $While);"]],until_clause:[["Until compound_list do_group","$$ = yy.until($2, $3, $Until);"]],function_definition:[["fname OPEN_PAREN CLOSE_PAREN linebreak function_body","$$ = yy.functionDefinition($fname, $function_body);"]],function_body:[["compound_command","$$ = [$compound_command, null];"],["compound_command redirect_list","$$ = [$compound_command, $redirect_list];"]],fname:["NAME"],brace_group:[["Lbrace compound_list Rbrace","$$ = yy.braceGroup($compound_list, $Lbrace.loc, $Rbrace.loc);"]],do_group:[["Do compound_list Done","$$ = yy.doGroup($compound_list, $Do.loc, $Done.loc);"]],simple_command:[["cmd_prefix cmd_word cmd_suffix","$$ =yy.command($cmd_prefix, $cmd_word, $cmd_suffix);"],["cmd_prefix cmd_word","$$ =yy.command($cmd_prefix, $cmd_word, null);"],["cmd_prefix","$$ =yy.commandAssignment($cmd_prefix);"],["cmd_name cmd_suffix","$$ =yy.command(null, $cmd_name, $cmd_suffix);"],["cmd_name","$$ =yy.command(null, $cmd_name);"]],cmd_name:[["WORD","$$ =yy.commandName(yytext) /* Apply rule 7a */;"]],cmd_word:[["WORD","$$ = yytext\t/* Apply rule 7B */;"]],cmd_prefix:[["io_redirect","$$ = yy.prefix($io_redirect);"],["cmd_prefix io_redirect","$$ = yy.prefixAppend($1, $2);"],["ASSIGNMENT_WORD","$$ = yy.prefix($1);"],["cmd_prefix ASSIGNMENT_WORD","$$ = yy.prefixAppend($1, $2);"]],cmd_suffix:[["io_redirect","$$ = yy.suffix($io_redirect);"],["cmd_suffix io_redirect","$$ = yy.suffixAppend($cmd_suffix, $io_redirect);"],["WORD","$$ = yy.suffix($1);"],["cmd_suffix WORD","$$ = yy.suffixAppend($cmd_suffix, $2);"]],redirect_list:[["io_redirect","$$ = [$io_redirect];"],["redirect_list io_redirect","$$ = $redirect_list.concat($io_redirect);"]],io_redirect:[["io_file","$$ = $io_file;"],["IO_NUMBER io_file","$$ = yy.numberIoRedirect($io_file, $1);"],"io_here","IO_NUMBER io_here"],io_file:[["LESS filename","$$ =yy.ioRedirect($1, $filename);"],["LESSAND filename","$$ =yy.ioRedirect($1, $filename);"],["GREAT filename","$$ =yy.ioRedirect($1, $filename);"],["GREATAND filename","$$ =yy.ioRedirect($1, $filename);"],["DGREAT filename","$$ =yy.ioRedirect($1, $filename);"],["LESSGREAT filename","$$ =yy.ioRedirect($1, $filename);"],["CLOBBER filename","$$ =yy.ioRedirect($1, $filename);"]],filename:["WORD"],io_here:["DLESS here_end","DLESSDASH here_end"],here_end:["WORD"],linebreak:["NEWLINE_LIST",""],separator:["SEPARATOR_OP","NEWLINE_LIST"],wordlist_repetition_plus0:[["WORD","$$ = [$1];"],["wordlist_repetition_plus0 WORD","$1.push($2);"]]}}});var require_io_file_operators=__commonJS((exports,module)=>{var ioFileOperators=module.exports=["LESS","DLESS","DGREAT","LESSAND","GREATAND","GREAT","LESSGREAT","CLOBBER"];ioFileOperators.isOperator=function(tk){for(let op of ioFileOperators)if(tk.type===op)return!0;return!1}});var require_parameter_operators=__commonJS((exports,module)=>{var parameterOps={["^([a-zA-Z_][a-zA-Z0-9_]*):\\-(.*)$"]:{op:"useDefaultValue",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*):\\=(.*)$"]:{op:"assignDefaultValue",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*):\\?(.*)$"]:{op:"indicateErrorIfNull",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*):\\+(.*)$"]:{op:"useAlternativeValue",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\-(.*)$"]:{op:"useDefaultValueIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\=(.*)$"]:{op:"assignDefaultValueIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\?(.*)$"]:{op:"indicateErrorIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\+(.*)$"]:{op:"useAlternativeValueIfUnset",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\%\\%(.*)$"]:{op:"removeLargestSuffixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\#\\#(.*)$"]:{op:"removeLargestPrefixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\%(.*)$"]:{op:"removeSmallestSuffixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^([a-zA-Z_][a-zA-Z0-9_]*)\\#(.*)$"]:{op:"removeSmallestPrefixPattern",parameter:(m)=>m[1],word:(m)=>m[2],expand:["word"]},["^\\#([a-zA-Z_][a-zA-Z0-9_]*)$"]:{op:"stringLength",parameter:(m)=>m[1]},["^([1-9][0-9]*)$"]:{kind:"positional",parameter:(m)=>Number(m[1])},"^!$":{kind:"last-background-pid"},"^\\@$":{kind:"positional-list"},"^\\-$":{kind:"current-option-flags"},"^\\#$":{kind:"positional-count"},"^\\?$":{kind:"last-exit-status"},"^\\*$":{kind:"positional-string"},"^\\$$":{kind:"shell-process-id"},"^0$":{kind:"shell-script-name"}};module.exports=parameterOps});var require_reserved_words2=__commonJS((exports,module)=>{module.exports={if:"If",then:"Then",else:"Else",elif:"Elif",fi:"Fi",do:"Do",done:"Done",case:"Case",esac:"Esac",while:"While",until:"Until",for:"For",in:"In","{":"Lbrace","}":"Rbrace","!":"Bang"}});var require_enums=__commonJS((exports)=>{exports.IOFileOperators=require_io_file_operators();exports.operators=require_operators();exports.parameterOperators=require_parameter_operators();exports.reservedWords=require_reserved_words2()});var require_built_grammar=__commonJS((exports,module)=>{var parser=function(){var o=function(k,v,o2,l){for(o2=o2||{},l=k.length;l--;o2[k[l]]=v);return o2},$V0=[1,9],$V1=[1,28],$V2=[1,6],$V3=[1,29],$V4=[1,34],$V5=[1,30],$V6=[1,26],$V7=[1,31],$V8=[1,32],$V9=[1,33],$Va=[1,27],$Vb=[1,25],$Vc=[1,36],$Vd=[1,38],$Ve=[1,39],$Vf=[1,40],$Vg=[1,41],$Vh=[1,42],$Vi=[1,43],$Vj=[1,44],$Vk=[1,45],$Vl=[1,46],$Vm=[1,5],$Vn=[6,31,84],$Vo=[1,50],$Vp=[1,51],$Vq=[6,13,27,29,31,32,39,41,42,44,49,50,51,53,54,55,56,57,60,61,62,63,69,71,73,75,76,77,78,79,80,81,83],$Vr=[6,9,11,29,31,44,49,51,53,54,55,61,62,63,84],$Vs=[1,52],$Vt=[6,9,11,15,29,31,44,49,51,53,54,55,61,62,63,84],$Vu=[1,62],$Vv=[6,9,11,15,29,31,44,49,51,53,54,55,61,62,63,71,73,75,76,77,78,79,80,81,83,84],$Vw=[6,9,11,15,29,31,42,44,49,51,53,54,55,61,62,63,69,71,73,75,76,77,78,79,80,81,83,84],$Vx=[6,9,11,15,29,31,42,44,49,51,53,54,55,61,62,63,71,73,75,76,77,78,79,80,81,83,84],$Vy=[1,66],$Vz=[1,78],$VA=[1,86],$VB=[13,27,32,39,41,42,50,56,57,60,69,71,73,75,76,77,78,79,80,81,83],$VC=[2,102],$VD=[1,93],$VE=[1,99],$VF=[29,44,49,51,53,54,55,61,62,63],$VG=[29,31,44,49,51,53,54,55,61,62,63,84],$VH=[1,112],$VI=[2,101],$VJ=[29,31,44,49,51,53,54,55,61,62,63],$VK=[2,37],$VL=[31,42,84],$VM=[27,42,44],$VN=[1,140],$VO=[1,141],$VP=[1,151],$VQ=[1,152],$VR=[1,161],$VS=[15,29],$VT=[44,49],$VU=[1,166],parser2={trace:function(){},yy:{},symbols_:{error:2,complete_command:3,list:4,separator:5,EOF:6,and_or:7,pipeline:8,AND_IF:9,linebreak:10,OR_IF:11,pipe_sequence:12,Bang:13,command:14,PIPE:15,simple_command:16,compound_command:17,redirect_list:18,function_definition:19,brace_group:20,subshell:21,for_clause:22,case_clause:23,if_clause:24,while_clause:25,until_clause:26,OPEN_PAREN:27,compound_list:28,CLOSE_PAREN:29,term:30,NEWLINE_LIST:31,For:32,name:33,do_group:34,LINEBREAK_IN:35,In:36,in:37,wordlist:38,NAME:39,wordlist_repetition_plus0:40,Case:41,WORD:42,case_list:43,Esac:44,case_list_ns:45,case_item_ns:46,case_item:47,pattern:48,DSEMI:49,If:50,Then:51,else_part:52,Fi:53,Elif:54,Else:55,While:56,Until:57,fname:58,function_body:59,Lbrace:60,Rbrace:61,Do:62,Done:63,cmd_prefix:64,cmd_word:65,cmd_suffix:66,cmd_name:67,io_redirect:68,ASSIGNMENT_WORD:69,io_file:70,IO_NUMBER:71,io_here:72,LESS:73,filename:74,LESSAND:75,GREAT:76,GREATAND:77,DGREAT:78,LESSGREAT:79,CLOBBER:80,DLESS:81,here_end:82,DLESSDASH:83,SEPARATOR_OP:84,$accept:0,$end:1},terminals_:{2:"error",6:"EOF",9:"AND_IF",11:"OR_IF",13:"Bang",15:"PIPE",27:"OPEN_PAREN",29:"CLOSE_PAREN",31:"NEWLINE_LIST",32:"For",35:"LINEBREAK_IN",36:"In",39:"NAME",41:"Case",42:"WORD",44:"Esac",49:"DSEMI",50:"If",51:"Then",53:"Fi",54:"Elif",55:"Else",56:"While",57:"Until",60:"Lbrace",61:"Rbrace",62:"Do",63:"Done",69:"ASSIGNMENT_WORD",71:"IO_NUMBER",73:"LESS",75:"LESSAND",76:"GREAT",77:"GREATAND",78:"DGREAT",79:"LESSGREAT",80:"CLOBBER",81:"DLESS",83:"DLESSDASH",84:"SEPARATOR_OP"},productions_:[0,[3,3],[3,2],[3,3],[3,4],[4,3],[4,1],[7,1],[7,4],[7,4],[8,1],[8,2],[12,1],[12,4],[14,1],[14,1],[14,2],[14,1],[17,1],[17,1],[17,1],[17,1],[17,1],[17,1],[17,1],[21,3],[28,1],[28,2],[28,2],[28,3],[30,3],[30,1],[22,4],[22,5],[22,5],[22,6],[33,1],[37,1],[38,1],[23,7],[23,7],[23,6],[45,2],[45,1],[43,2],[43,1],[46,3],[46,4],[46,4],[46,5],[47,5],[47,5],[47,6],[47,6],[48,1],[48,3],[24,6],[24,5],[52,4],[52,5],[52,2],[25,3],[26,3],[19,5],[59,1],[59,2],[58,1],[20,3],[34,3],[16,3],[16,2],[16,1],[16,2],[16,1],[67,1],[65,1],[64,1],[64,2],[64,1],[64,2],[66,1],[66,2],[66,1],[66,2],[18,1],[18,2],[68,1],[68,2],[68,1],[68,2],[70,2],[70,2],[70,2],[70,2],[70,2],[70,2],[70,2],[74,1],[72,2],[72,2],[82,1],[10,1],[10,0],[5,1],[5,1],[40,1],[40,2]],performAction:function(yytext,yyleng,yylineno,yy,yystate,$$,_$){var $0=$$.length-1;switch(yystate){case 1:return yy.checkAsync($$[$0-2],$$[$0-1]);case 2:case 3:return $$[$0-1];case 4:return yy.checkAsync($$[$0-2],$$[$0-3]);case 5:this.$=yy.listAppend($$[$0-2],$$[$0],$$[$0-1]);break;case 6:this.$=yy.list($$[$0]);break;case 7:case 26:case 27:case 86:this.$=$$[$0];break;case 8:this.$=yy.andAndOr($$[$0-3],$$[$0]);break;case 9:this.$=yy.orAndOr($$[$0-3],$$[$0]);break;case 10:this.$=yy.pipeLine($$[$0]);break;case 11:this.$=yy.bangPipeLine($$[$0]);break;case 12:this.$=yy.pipeSequence($$[$0]);break;case 13:this.$=yy.pipeSequenceAppend($$[$0-3],$$[$0]);break;case 16:this.$=yy.addRedirections($$[$0-1],$$[$0]);break;case 25:this.$=yy.subshell($$[$0-1],$$[$0-2].loc,$$[$0].loc);break;case 28:case 29:this.$=yy.checkAsync($$[$0-1],$$[$0]);break;case 30:this.$=yy.termAppend($$[$0-2],$$[$0],$$[$0-1]);break;case 31:this.$=yy.term($$[$0]);break;case 32:this.$=yy.forClauseDefault($$[$0-2],$$[$0],$$[$0-3].loc);break;case 33:case 34:this.$=yy.forClauseDefault($$[$0-3],$$[$0],$$[$0-4].loc);break;case 35:this.$=yy.forClause($$[$0-4],$$[$0-2],$$[$0],$$[$0-5].loc);break;case 39:case 40:this.$=yy.caseClause($$[$0-5],$$[$0-1],$$[$0-6].loc,$$[$0].loc);break;case 41:this.$=yy.caseClause($$[$0-4],null,$$[$0-5].loc,$$[$0].loc);break;case 42:case 44:this.$=yy.caseListAppend($$[$0-1],$$[$0]);break;case 43:case 45:this.$=yy.caseList($$[$0]);break;case 46:this.$=yy.caseItem($$[$0-2],null,$$[$0-2][0].loc,$$[$0-1].loc);break;case 47:this.$=yy.caseItem($$[$0-3],$$[$0-1],$$[$0-3][0].loc,$$[$0-1].loc);break;case 48:this.$=yy.caseItem($$[$0-2],null,$$[$0-3].loc,$$[$0-1].loc);break;case 49:this.$=yy.caseItem($$[$0-3],$$[$0-1],$$[$0-4].loc,$$[$0-1].loc);break;case 50:this.$=yy.caseItem($$[$0-4],null,$$[$0-4][0].loc,$$[$0-1].loc);break;case 51:this.$=yy.caseItem($$[$0-4],$$[$0-2],$$[$0-4][0].loc,$$[$0-1].loc);break;case 52:this.$=yy.caseItem($$[$0-4],null,$$[$0-5].loc,$$[$0-1].loc);break;case 53:this.$=yy.caseItem($$[$0-4],$$[$0-2],$$[$0-5].loc,$$[$0-1].loc);break;case 54:this.$=yy.pattern($$[$0]);break;case 55:this.$=yy.patternAppend($$[$0-2],$$[$0]);break;case 56:this.$=yy.ifClause($$[$0-4],$$[$0-2],$$[$0-1],$$[$0-5].loc,$$[$0].loc);break;case 57:this.$=yy.ifClause($$[$0-3],$$[$0-1],null,$$[$0-4].loc,$$[$0].loc);break;case 58:this.$=yy.ifClause($$[$0-2],$$[$0],null,$$[$0-3].loc,$$[$0].loc);break;case 59:this.$=yy.ifClause($$[$0-3],$$[$0-1],$$[$0],$$[$0-4].loc,$$[$0].loc);break;case 60:this.$=yy.elseClause($$[$0],$$[$0-1]);break;case 61:this.$=yy.while($$[$0-1],$$[$0],$$[$0-2]);break;case 62:this.$=yy.until($$[$0-1],$$[$0],$$[$0-2]);break;case 63:this.$=yy.functionDefinition($$[$0-4],$$[$0]);break;case 64:this.$=[$$[$0],null];break;case 65:this.$=[$$[$0-1],$$[$0]];break;case 67:this.$=yy.braceGroup($$[$0-1],$$[$0-2].loc,$$[$0].loc);break;case 68:this.$=yy.doGroup($$[$0-1],$$[$0-2].loc,$$[$0].loc);break;case 69:this.$=yy.command($$[$0-2],$$[$0-1],$$[$0]);break;case 70:this.$=yy.command($$[$0-1],$$[$0],null);break;case 71:this.$=yy.commandAssignment($$[$0]);break;case 72:this.$=yy.command(null,$$[$0-1],$$[$0]);break;case 73:this.$=yy.command(null,$$[$0]);break;case 74:this.$=yy.commandName(yytext);break;case 75:this.$=yytext;break;case 76:case 78:this.$=yy.prefix($$[$0]);break;case 77:case 79:this.$=yy.prefixAppend($$[$0-1],$$[$0]);break;case 80:case 82:this.$=yy.suffix($$[$0]);break;case 81:case 83:this.$=yy.suffixAppend($$[$0-1],$$[$0]);break;case 84:case 105:this.$=[$$[$0]];break;case 85:this.$=$$[$0-1].concat($$[$0]);break;case 87:this.$=yy.numberIoRedirect($$[$0],$$[$0-1]);break;case 90:case 91:case 92:case 93:case 94:case 95:case 96:this.$=yy.ioRedirect($$[$0-1],$$[$0]);break;case 106:$$[$0-1].push($$[$0]);break}},table:[{3:1,4:2,5:3,7:4,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,31:$V2,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl,84:$Vm},{1:[3]},{5:47,6:[1,48],31:$V2,84:$Vm},{4:49,7:4,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vn,[2,6],{9:$Vo,11:$Vp}),o($Vq,[2,103]),o($Vq,[2,104]),o($Vr,[2,7]),o($Vr,[2,10],{15:$Vs}),{12:53,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vt,[2,12]),o($Vt,[2,14]),o($Vt,[2,15],{70:35,72:37,18:54,68:55,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vt,[2,17]),o($Vt,[2,71],{70:35,72:37,65:56,68:57,42:[1,59],69:[1,58],71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vt,[2,73],{70:35,72:37,66:60,68:61,42:$Vu,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,18]),o($Vv,[2,19]),o($Vv,[2,20]),o($Vv,[2,21]),o($Vv,[2,22]),o($Vv,[2,23]),o($Vv,[2,24]),{27:[1,63]},o($Vw,[2,76]),o($Vw,[2,78]),o($Vx,[2,74]),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:64,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:68,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{33:69,39:[1,70]},{42:[1,71]},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:72,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:73,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:74,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{27:[2,66]},o($Vw,[2,86]),{70:75,72:76,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vw,[2,88]),{42:$Vz,74:77},{42:$Vz,74:79},{42:$Vz,74:80},{42:$Vz,74:81},{42:$Vz,74:82},{42:$Vz,74:83},{42:$Vz,74:84},{42:$VA,82:85},{42:$VA,82:87},{6:[1,88],7:89,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{1:[2,2]},{5:91,6:[1,90],31:$V2,84:$Vm},o($VB,$VC,{10:92,31:$VD}),o($VB,$VC,{10:94,31:$VD}),o([27,32,39,41,42,50,56,57,60,69,71,73,75,76,77,78,79,80,81,83],$VC,{10:95,31:$VD}),o($Vr,[2,11],{15:$Vs}),o($Vt,[2,16],{70:35,72:37,68:96,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,84]),o($Vt,[2,70],{70:35,72:37,68:61,66:97,42:$Vu,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vw,[2,77]),o($Vw,[2,79]),o($Vx,[2,75]),o($Vt,[2,72],{70:35,72:37,68:98,42:$VE,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vx,[2,80]),o($Vx,[2,82]),{29:[1,100]},{61:[1,101]},o($VF,[2,26],{5:102,31:$V2,84:$Vm}),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,30:103,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($VG,[2,31],{9:$Vo,11:$Vp}),{29:[1,104]},{10:105,31:$VD,35:[1,106],36:[1,107],37:108,62:$VC},o([31,35,36,62],[2,36]),{10:109,31:$VD,36:$VC},{51:[1,110]},{34:111,62:$VH},{34:113,62:$VH},o($Vw,[2,87]),o($Vw,[2,89]),o($Vw,[2,90]),o($Vw,[2,97]),o($Vw,[2,91]),o($Vw,[2,92]),o($Vw,[2,93]),o($Vw,[2,94]),o($Vw,[2,95]),o($Vw,[2,96]),o($Vw,[2,98]),o($Vw,[2,100]),o($Vw,[2,99]),{1:[2,1]},o($Vn,[2,5],{9:$Vo,11:$Vp}),{1:[2,3]},{6:[1,114],7:89,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{8:115,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o([13,27,32,36,39,41,42,44,50,56,57,60,62,69,71,73,75,76,77,78,79,80,81,83],$VI),{8:116,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{14:117,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,85]),o($Vt,[2,69],{70:35,72:37,68:98,42:$VE,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vx,[2,81]),o($Vx,[2,83]),o([27,32,41,50,56,57,60],$VC,{10:118,31:$VD}),o($Vv,[2,67]),o($VJ,[2,28],{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,7:119,13:$V0,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($VF,[2,27],{5:120,31:$V2,84:$Vm}),o($Vv,[2,25]),{34:121,62:$VH},{5:122,31:$V2,84:$Vm},{5:123,31:$V2,42:$VK,84:$Vm},{38:124,40:125,42:[1,126]},{36:[1,128],37:127},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:129,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,61]),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:130,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,62]),{1:[2,4]},o($Vr,[2,8]),o($Vr,[2,9]),o($Vt,[2,13]),{17:132,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,32:$V3,41:$V5,50:$V7,56:$V8,57:$V9,59:131,60:$Va},o($VG,[2,30],{9:$Vo,11:$Vp}),o($VJ,[2,29],{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,7:119,13:$V0,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,32]),{34:133,62:$VH},{34:134,62:$VH},{5:135,31:$V2,84:$Vm},o([31,84],[2,38],{42:[1,136]}),o($VL,[2,105]),o($VM,$VC,{10:137,31:$VD}),o([27,31,42,44],$VK),{52:138,53:[1,139],54:$VN,55:$VO},{63:[1,142]},o($Vt,[2,63]),o($Vt,[2,64],{70:35,72:37,68:55,18:143,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,33]),o($Vv,[2,34]),{34:144,62:$VH},o($VL,[2,106]),{27:$VP,42:$VQ,43:145,44:[1,147],45:146,46:149,47:148,48:150},{53:[1,153]},o($Vv,[2,57]),{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:154,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:155,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},o($Vv,[2,68]),o($Vt,[2,65],{70:35,72:37,68:96,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($Vv,[2,35]),{27:$VP,42:$VQ,44:[1,156],46:158,47:157,48:150},{44:[1,159]},o($Vv,[2,41]),o($VM,[2,45]),{44:[2,43]},{15:$VR,29:[1,160]},{42:$VQ,48:162},o($VS,[2,54]),o($Vv,[2,56]),{51:[1,163]},{53:[2,60]},o($Vv,[2,39]),o($VM,[2,44]),{44:[2,42]},o($Vv,[2,40]),o($VT,$VC,{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,30:65,7:67,10:164,28:165,13:$V0,27:$V1,31:$VU,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),{42:[1,167]},{15:$VR,29:[1,168]},{7:67,8:7,12:8,13:$V0,14:10,16:11,17:12,19:13,20:16,21:17,22:18,23:19,24:20,25:21,26:22,27:$V1,28:169,30:65,31:$Vy,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,58:23,60:$Va,64:14,67:15,68:24,69:$Vb,70:35,71:$Vc,72:37,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl},{44:[2,46],49:[1,170]},{10:172,31:$VD,44:$VC,49:[1,171]},o($VT,$VI,{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,7:67,30:103,13:$V0,27:$V1,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),o($VS,[2,55]),o($VT,$VC,{8:7,12:8,14:10,16:11,17:12,19:13,64:14,67:15,20:16,21:17,22:18,23:19,24:20,25:21,26:22,58:23,68:24,70:35,72:37,30:65,7:67,10:173,28:174,13:$V0,27:$V1,31:$VU,32:$V3,39:$V4,41:$V5,42:$V6,50:$V7,56:$V8,57:$V9,60:$Va,69:$Vb,71:$Vc,73:$Vd,75:$Ve,76:$Vf,77:$Vg,78:$Vh,79:$Vi,80:$Vj,81:$Vk,83:$Vl}),{52:175,53:[2,58],54:$VN,55:$VO},o($VM,$VC,{10:176,31:$VD}),o($VM,$VC,{10:177,31:$VD}),{44:[2,47]},{44:[2,48],49:[1,178]},{10:180,31:$VD,44:$VC,49:[1,179]},{53:[2,59]},o($VM,[2,50]),o($VM,[2,51]),o($VM,$VC,{10:181,31:$VD}),o($VM,$VC,{10:182,31:$VD}),{44:[2,49]},o($VM,[2,52]),o($VM,[2,53])],defaultActions:{34:[2,66],48:[2,2],88:[2,1],90:[2,3],114:[2,4],149:[2,43],155:[2,60],158:[2,42],172:[2,47],175:[2,59],180:[2,49]},parseError:function(str,hash3){if(hash3.recoverable)this.trace(str);else{let _parseError2=function(msg,hash4){this.message=msg,this.hash=hash4};var _parseError=_parseError2;throw _parseError2.prototype=Error,new _parseError2(str,hash3)}},parse:function(input){var self=this,stack=[0],tstack=[],vstack=[null],lstack=[],table=this.table,yytext="",yylineno=0,yyleng=0,recovering=0,TERROR=2,EOF=1,args2=lstack.slice.call(arguments,1),lexer=Object.create(this.lexer),sharedState={yy:{}};for(var k in this.yy)if(Object.prototype.hasOwnProperty.call(this.yy,k))sharedState.yy[k]=this.yy[k];if(lexer.setInput(input,sharedState.yy),sharedState.yy.lexer=lexer,sharedState.yy.parser=this,typeof lexer.yylloc>"u")lexer.yylloc={};var yyloc=lexer.yylloc;lstack.push(yyloc);var ranges=lexer.options&&lexer.options.ranges;if(typeof sharedState.yy.parseError==="function")this.parseError=sharedState.yy.parseError;else this.parseError=Object.getPrototypeOf(this).parseError;function popStack(n){stack.length=stack.length-2*n,vstack.length=vstack.length-n,lstack.length=lstack.length-n}_token_stack:var lex=function(){var token=lexer.lex()||EOF;if(typeof token!=="number")token=self.symbols_[token]||token;return token};var symbol2,preErrorSymbol,state,action,a,r,yyval={},p,len,newState,expected;while(!0){if(state=stack[stack.length-1],this.defaultActions[state])action=this.defaultActions[state];else{if(symbol2===null||typeof symbol2>"u")symbol2=lex();action=table[state]&&table[state][symbol2]}if(typeof action>"u"||!action.length||!action[0]){var errStr="";expected=[];for(p in table[state])if(this.terminals_[p]&&p>TERROR)expected.push("'"+this.terminals_[p]+"'");if(lexer.showPosition)errStr="Parse error on line "+(yylineno+1)+`:
|
|
690
690
|
`+lexer.showPosition()+`
|
|
691
691
|
Expecting `+expected.join(", ")+", got '"+(this.terminals_[symbol2]||symbol2)+"'";else errStr="Parse error on line "+(yylineno+1)+": Unexpected "+(symbol2==EOF?"end of input":"'"+(this.terminals_[symbol2]||symbol2)+"'");this.parseError(errStr,{text:lexer.match,token:this.terminals_[symbol2]||symbol2,line:lexer.yylineno,loc:yyloc,expected})}if(action[0]instanceof Array&&action.length>1)throw Error("Parse Error: multiple actions possible at state: "+state+", token: "+symbol2);switch(action[0]){case 1:if(stack.push(symbol2),vstack.push(lexer.yytext),lstack.push(lexer.yylloc),stack.push(action[1]),symbol2=null,!preErrorSymbol){if(yyleng=lexer.yyleng,yytext=lexer.yytext,yylineno=lexer.yylineno,yyloc=lexer.yylloc,recovering>0)recovering--}else symbol2=preErrorSymbol,preErrorSymbol=null;break;case 2:if(len=this.productions_[action[1]][1],yyval.$=vstack[vstack.length-len],yyval._$={first_line:lstack[lstack.length-(len||1)].first_line,last_line:lstack[lstack.length-1].last_line,first_column:lstack[lstack.length-(len||1)].first_column,last_column:lstack[lstack.length-1].last_column},ranges)yyval._$.range=[lstack[lstack.length-(len||1)].range[0],lstack[lstack.length-1].range[1]];if(r=this.performAction.apply(yyval,[yytext,yyleng,yylineno,sharedState.yy,action[1],vstack,lstack].concat(args2)),typeof r<"u")return r;if(len)stack=stack.slice(0,-1*len*2),vstack=vstack.slice(0,-1*len),lstack=lstack.slice(0,-1*len);stack.push(this.productions_[action[1]][0]),vstack.push(yyval.$),lstack.push(yyval._$),newState=table[stack[stack.length-2]][stack[stack.length-1]],stack.push(newState);break;case 3:return!0}}return!0}};function Parser(){this.yy={}}return Parser.prototype=parser2,parser2.Parser=Parser,new Parser}();if(typeof exports<"u")exports.parser=parser,exports.Parser=parser.Parser,exports.parse=function(){return parser.parse.apply(parser,arguments)},exports.main=function(args2){if(!args2[1])console.log("Usage: "+args2[0]+" FILE"),process.exit(1);var source=__require("fs").readFileSync(__require("path").normalize(args2[1]),"utf8");return exports.parser.parse(source)}});var require_posix=__commonJS((exports,module)=>{var astBuilder=require_ast_builder(),tokenizer=require_tokenizer(),phaseCatalog=require_rules(),grammarSource=require_grammar(),enums=require_enums(),lexerPhases=()=>[phaseCatalog.newLineList,phaseCatalog.operatorTokens,phaseCatalog.separator,phaseCatalog.reservedWords,phaseCatalog.linebreakIn,phaseCatalog.ioNumber,phaseCatalog.identifyMaybeSimpleCommands,phaseCatalog.assignmentWord,phaseCatalog.parameterExpansion,phaseCatalog.arithmeticExpansion,phaseCatalog.commandExpansion,phaseCatalog.forNameVariable,phaseCatalog.functionName,phaseCatalog.identifySimpleCommandNames,phaseCatalog.aliasSubstitution,phaseCatalog.tildeExpanding,phaseCatalog.parameterExpansion.resolve,phaseCatalog.commandExpansion.resolve,phaseCatalog.arithmeticExpansion.resolve,phaseCatalog.fieldSplitting.split,phaseCatalog.pathExpansion,phaseCatalog.quoteRemoval,phaseCatalog.syntaxerrorOnContinue,phaseCatalog.defaultNodeType];module.exports={inherits:null,init:(posixMode,utils)=>{let grammar=null;try{grammar=require_built_grammar()}catch(err){}return{enums,phaseCatalog,lexerPhases:lexerPhases(utils),tokenizer,grammarSource,grammar,astBuilder}}}});var require_word_expansion=__commonJS((exports,module)=>{var map2=require_map_iterable(),tokenOrEmpty=require_tokens().tokenOrEmpty,convertToWord=()=>map2((tk)=>{if(tk.is("TOKEN"))return tk.changeTokenType("WORD",tk.value);return tk});function start(state,source,reducers){let char=source&&source.shift();if(char===void 0)return{nextReduction:reducers.end,tokensToEmit:tokenOrEmpty(state),nextState:state.resetCurrent().saveCurrentLocAsStart()};if(state.escaping&&char===`
|
|
692
|
-
`)return{nextReduction:reducers.start,nextState:state.setEscaping(!1).removeLastChar()};if(!state.escaping&&char==="\\")return{nextReduction:reducers.start,nextState:state.setEscaping(!0).appendChar(char)};if(!state.escaping&&char==="'")return{nextReduction:reducers.singleQuoting,nextState:state.appendChar(char)};if(!state.escaping&&char==='"')return{nextReduction:reducers.doubleQuoting,nextState:state.appendChar(char)};if(!state.escaping&&char==="$")return{nextReduction:reducers.expansionStart,nextState:state.appendChar(char).appendEmptyExpansion()};if(!state.escaping&&char==="`")return{nextReduction:reducers.expansionCommandTick,nextState:state.appendChar(char).appendEmptyExpansion()};return{nextReduction:reducers.start,nextState:state.appendChar(char).setEscaping(!1)}}module.exports={inherits:"posix",init:(posixMode)=>{let phaseCatalog=posixMode.phaseCatalog,lexerPhases=[convertToWord,phaseCatalog.parameterExpansion,phaseCatalog.arithmeticExpansion,phaseCatalog.commandExpansion,phaseCatalog.tildeExpanding,phaseCatalog.parameterExpansion.resolve,phaseCatalog.commandExpansion.resolve,phaseCatalog.arithmeticExpansion.resolve,phaseCatalog.fieldSplitting.split,phaseCatalog.pathExpansion,phaseCatalog.quoteRemoval,phaseCatalog.defaultNodeType],reducers=Object.assign({},posixMode.tokenizer.reducers,{start});return Object.assign({},posixMode,{lexerPhases,tokenizer:()=>posixMode.tokenizer({},reducers)})}}});var require_src=__commonJS((exports,module)=>{var shellLexer=require_shell_lexer(),utils=require_utils2(),modes={bash:require_bash(),posix:require_posix(),"word-expansion":require_word_expansion()};function loadPlugin(name){let modePlugin=modes[name];if(modePlugin.inherits)return modePlugin.init(loadPlugin(modePlugin.inherits),utils);return modePlugin.init(null,utils)}module.exports=function(sourceCode,options){try{options=options||{},options.mode=options.mode||"posix";let mode=loadPlugin(options.mode),Parser=mode.grammar.Parser,astBuilder=mode.astBuilder,parser=new Parser;return parser.lexer=shellLexer(mode,options),parser.yy=astBuilder(options),parser.parse(sourceCode)}catch(err){if(err instanceof SyntaxError)throw err;throw Error(err.stack||err.message)}}});import*as path54 from"node:path";function buildDedupeKey(category,operator,path55){return`${category}|${operator}|${path55??"null"}`}function detectProcessSubstitutionWrites(command){let results=[],writeProcSubPattern=/>\s*\(([^)]+)\)/g;while(!0){let match=writeProcSubPattern.exec(command);if(match===null)break;let innerCommand=match[1].trim();if(!innerCommand)continue;let stages=innerCommand.split("|").map((s)=>s.trim());for(let stage of stages){let builtinResult=detectBuiltinWritesFromString(stage);if(builtinResult)results.push(builtinResult);let appendMatch=stage.match(/^\s*(.*?)\s*>>(\s*)(\S+)\s*$/);if(appendMatch){let path55=appendMatch[3];if(path55&&!isNullDevice(path55))results.push({category:"redirect",operator:">>",path:path55})}else{let writeMatch=stage.match(/^\s*(.*?)\s*>(?!>)(\s*)(\S+)\s*$/);if(writeMatch){let path55=writeMatch[3];if(path55&&!isNullDevice(path55))results.push({category:"redirect",operator:">",path:path55})}}}}return results}function detectBuiltinWritesFromString(cmd){let tokens=cmd.trim().split(/\s+/);if(tokens.length===0)return null;let name=tokens[0].toLowerCase();if(BUILTIN_WRITE_COMMANDS.has(name)){for(let i=tokens.length-1;i>=1;i--)if(!tokens[i].startsWith("-"))return{category:"builtin_write",operator:name,path:tokens[i]}}return null}function wordText(node){if(!node||typeof node!=="object")return null;if(isBashWord(node))return node.text;return null}function isBashWord(node){return!!node&&typeof node==="object"&&node.type==="Word"&&typeof node.text==="string"}function collectLeafCommands(node,out){if(!node||typeof node!=="object")return;switch(node.type){case"Script":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"Pipeline":case"Sequence":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"CompoundList":if(out.push(node),Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"LogicalExpression":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"And":case"Or":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"Subshell":if(out.push(node),node.list)collectLeafCommands(node.list,out);break;case"ProcessSubstitution":{let opNode=node.op;if(opNode&&typeof opNode==="object"){if(opNode.type?.toUpperCase()==="GREAT"){if(node.command)collectLeafCommands(node.command,out)}}}break;default:out.push(node);break}}function getCommandName(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(typeof c.name==="string")return c.name;return wordText(c.name)}function getSuffixWords(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];return suffix.map((s)=>wordText(s)??"")}function getRedirections(cmd){if(!cmd||typeof cmd!=="object")return[];let c=cmd;if(Array.isArray(c.redirections))return c.redirections;let results=[],suffix=c.suffix,prefix=c.prefix;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item))results.push(item)}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item))results.push(item)}return results}function isRedirectNode(node){return!!(node&&typeof node==="object"&&node.type==="Redirect")}function operatorLabel(op){if(!op||typeof op!=="object")return"unknown";let opType=op.type?.toUpperCase();switch(opType){case"GREAT":return">";case"DGREAT":return">>";case"CLOBBER":return">|";case"LESS":return"<";case"DLESS":return"<<";case"DLESSDASH":return"<<-";case"LESSAND":return"<&";case"GREATAND":return">&";case"LESSGREAT":return"<>";default:return opType||"unknown"}}function extractRedirectPath(fileNode){let text=wordText(fileNode);if(!text)return null;return text}function isNullDevice(path55){return path55==="/dev/null"||path55==="/dev/zero"||path55==="/dev/urandom"}function isNumeric(s){return/^\d+$/.test(s)}function detectRedirects(cmd){let results=[];results.push(...detectHereDocMarkers(cmd));let redirections=getRedirections(cmd);for(let redirect of redirections){if(!redirect||typeof redirect!=="object")continue;let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")continue;let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))continue;let fileNode=r.file,path55=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType))results.push({category:"redirect",operator:opLabel,path:path55});else if(REDIRECT_HERE_TOKENS.has(opType))results.push({category:"here_doc",operator:opLabel,path:path55})}return results}function detectHereDocMarkers(cmd){let results=[];if(!cmd||typeof cmd!=="object")return results;let suffix=cmd.suffix;if(!Array.isArray(suffix))return results;for(let item of suffix){if(!item||typeof item!=="object")continue;if(isHereDocMarker(item))results.push({category:"here_doc",operator:item.text==="<<-"?"<<-":"<<",path:null})}return results}function isHereDocMarker(node){if(!node||typeof node!=="object")return!1;let type=node.type?.toLowerCase();return type==="dless"||type==="dlessdash"}function detectBuiltinWrites(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(lowerName==="dd"){let suffixWords2=getSuffixWords(cmd);for(let word of suffixWords2)if(word.startsWith("of=")){let path55=word.slice(3);if(path55&&!isNullDevice(path55))results.push({category:"builtin_write",operator:"dd of=",path:path55})}return results}if(!BUILTIN_WRITE_COMMANDS.has(lowerName))return results;let suffixWords=getSuffixWords(cmd);if(lowerName==="truncate"){for(let word of suffixWords)if(!word.startsWith("-")&&!isNumeric(word)){results.push({category:"builtin_write",operator:"truncate",path:word});break}}else for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"builtin_write",operator:name,path:word});break}}return results}function detectInplaceEdit(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INPLACE_EDIT_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd);if(!suffixWords.some((word)=>{if(lowerName==="sed")return word.startsWith("-i")&&word.length>1;return word==="-i"||word.startsWith("-i")}))return[];let scriptPattern=/^[ssy]\/.*\/[gim]*$/,quotedScriptPattern=/^["'].*["']$/,flagArgs=new Set(["-e","-E","-f","-i"]),combinedFlagArgs=/^-[paaneA]+[eEf]/,sedInplaceSuffix=/^-i[a-z]+/i,skipIndices=new Set;for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word.startsWith("-")){if(flagArgs.has(word)||combinedFlagArgs.test(word)||sedInplaceSuffix.test(word)){if(skipIndices.add(i),i+1<suffixWords.length)skipIndices.add(i+1)}}else if(scriptPattern.test(word)||quotedScriptPattern.test(word))skipIndices.add(i)}let candidates=suffixWords.map((word,i)=>({word,i})).filter(({i})=>!skipIndices.has(i));if(candidates.length>0){let file2=candidates[0].word;results.push({category:"inplace_edit",operator:`${name} -i`,path:file2})}return results}function detectInterpreterEval(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INTERPRETER_EVAL_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd),relevantFlags={python:["-c"],python3:["-c"],python2:["-c"],node:["-e","-p","-pe"],bun:["-e","-p","-pe"],ruby:["-e"],perl:["-e","-E"],php:["-r","-R","-F"]}[lowerName]??[];if(!suffixWords.some((word)=>relevantFlags.some((f)=>word===f||word.startsWith(`${f}=`))))return[];return results.push({category:"interpreter_eval",operator:`${name} [eval]`,path:null}),results}function detectNetworkDownloaders(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!NETWORK_DOWNLOAD_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="curl")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-o"&&i+1<suffixWords.length){let path55=suffixWords[i+1];if(!path55.startsWith("-"))results.push({category:"network_download",operator:"curl -o",path:path55})}else if(word.startsWith("-o")&&word.length>2)results.push({category:"network_download",operator:"curl -o",path:word.slice(2)})}else if(lowerName==="wget")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-O"&&i+1<suffixWords.length){let path55=suffixWords[i+1];if(!path55.startsWith("-"))results.push({category:"network_download",operator:"wget -O",path:path55})}else if(word.startsWith("-O")&&word.length>2)results.push({category:"network_download",operator:"wget -O",path:word.slice(2)})}else if(lowerName==="scp")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")&&(word.includes(":")||word.startsWith("/")||word.startsWith("."))){results.push({category:"network_download",operator:"scp",path:word});break}}return results}function detectArchiveExtract(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!ARCHIVE_EXTRACT_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="tar"){if(suffixWords.some((word)=>{if(word==="--extract"||word==="--get")return!0;if(word.startsWith("-")&&word.includes("x"))return!0;return!1}))for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"tar -x",path:word});break}if(word.startsWith("--file=")&&word.length>7){results.push({category:"archive_extract",operator:"tar -x",path:word.slice(7)});break}}}else if(lowerName==="unzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"unzip",path:word});break}}else if(lowerName==="gunzip"||lowerName==="gzip"||lowerName==="bzip2"||lowerName==="xz"||lowerName==="7z"||lowerName==="rar"){if(suffixWords.includes("-d")||suffixWords.includes("--decompress")||lowerName==="gunzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:`${name} [decompress]`,path:word});break}}}return results}function detectGitDestructive(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;if(name.toLowerCase()!==GIT_COMMAND)return[];let suffixWords=getSuffixWords(cmd);if(suffixWords.length===0)return[];let first=suffixWords[0].toLowerCase();if(first==="checkout"){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length){let path55=suffixWords[dashDashIdx+1],op=path55==="."?"git checkout -- .":"git checkout --";results.push({category:"git_destructive",operator:op,path:path55})}}else if(first==="restore"){let hasHard=suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")),hasForce=suffixWords.some((w)=>w==="--force"||w==="-f"||w.startsWith("-")&&w.includes("f"));if(hasHard||hasForce){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length)results.push({category:"git_destructive",operator:"git restore",path:suffixWords[dashDashIdx+1]});else results.push({category:"git_destructive",operator:"git restore",path:null})}}else if(first==="reset"){if(suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")))results.push({category:"git_destructive",operator:"git reset --hard",path:null})}else if(first==="clean"){if(suffixWords.some((w)=>w==="-n"||w==="--dry-run"||w.startsWith("-")&&w.includes("n")))return results;let hasForce=suffixWords.some((w)=>w==="-f"||w==="--force"||w.startsWith("-")&&w.includes("f")),hasDir=suffixWords.some((w)=>w==="-d"||w==="--dir"||w.startsWith("-")&&w.includes("d"));if(hasForce&&hasDir)results.push({category:"git_destructive",operator:"git clean -fd",path:null})}return results}function splitWindowsCommands(command){let commands=[],current="",inSingleQuote=!1,inDoubleQuote=!1,parenDepth=0;for(let i=0;i<command.length;i++){let ch=command[i];if(ch==="'"&&!inDoubleQuote)inSingleQuote=!inSingleQuote;else if(ch==='"'&&!inSingleQuote)inDoubleQuote=!inDoubleQuote;else if(ch==="("&&!inSingleQuote&&!inDoubleQuote)parenDepth++;else if(ch===")"&&!inSingleQuote&&!inDoubleQuote)parenDepth--;if(ch==="|"&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());current="";continue}if((ch==="&"||ch==="|")&&i+1<command.length&&command[i+1]===ch&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());commands.push(ch==="&"?"&&":"||"),current="",i++;continue}if(ch==="&"&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(!(i+1<command.length&&command[i+1]==="&")){if(current.trim())commands.push(current.trim());current="";continue}}current+=ch}if(current.trim())commands.push(current.trim());return commands.filter((c)=>c!=="&&"&&c!=="||")}function detectPowerShellWrites(command){let results=[],trimmed=command.trim();if(!trimmed)return results;let innerCommand=trimmed,cmdMatch=trimmed.match(/^(?:powershell|pwsh)\s+(?:-Command|-C)\s+(.*)$/i);if(cmdMatch){if(innerCommand=cmdMatch[1].trim(),innerCommand.startsWith('"')&&innerCommand.endsWith('"')||innerCommand.startsWith("'")&&innerCommand.endsWith("'"))innerCommand=innerCommand.slice(1,-1)}let redirectMatch=innerCommand.match(/^(.*?)\s+((?:>){1,2})\s*(\S+)$/);if(redirectMatch){let beforeRedirect=redirectMatch[1],op=redirectMatch[2],path55=redirectMatch[3];if(!/\d>\s*$|\s\d>&$/.test(`${beforeRedirect} ${op}`))results.push({category:"redirect",operator:op,path:path55})}let leadingRedirect=innerCommand.match(/^((?:>){1,2})\s+(\S+)$/);if(leadingRedirect)results.push({category:"redirect",operator:leadingRedirect[1],path:leadingRedirect[2]});let iwrMatch=trimmed.match(/^(?:Invoke-WebRequest|curl)\s.*?(?:-OutFile\s+(\S+)|-o\s+(\S+))/i);if(iwrMatch){let path55=iwrMatch[1]||iwrMatch[2];if(path55)results.push({category:"network_download",operator:"Invoke-WebRequest -OutFile",path:path55})}function detectPsContentCmdlet(cmd){let cmdletMatch=cmd.match(/^(Out-File|Set-Content|Add-Content|Clear-Content)\b/i);if(!cmdletMatch)return null;let cmdletName=cmdletMatch[1],rest=cmd.slice(cmdletMatch[0].length).trim(),pathFlagMatch=rest.match(/(?:-Path|-FilePath|-LiteralPath)\s+("([^"]+)"|'([^']+)'|(\S+))/i);if(pathFlagMatch){let path55=pathFlagMatch[2]??pathFlagMatch[3]??pathFlagMatch[4]??"";return{category:"redirect",operator:cmdletName,path:path55}}let tokens=rest.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[];for(let token of tokens){if(token.startsWith("-"))continue;let path55=token.replace(/^["']|["']$/g,"");return{category:"redirect",operator:cmdletName,path:path55}}return null}let contentResult=detectPsContentCmdlet(innerCommand);if(contentResult)results.push(contentResult);let pipeContentMatch=innerCommand.match(/\|\s*(Out-File|Set-Content|Add-Content|Clear-Content)\b\s*(.*)$/i);if(pipeContentMatch){let cmdletName=pipeContentMatch[1],tokens=pipeContentMatch[2].trim().match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[];for(let token of tokens){if(token.startsWith("-"))continue;let path55=token.replace(/^["']|["']$/g,"");if(path55){results.push({category:"redirect",operator:cmdletName,path:path55});break}}}function detectPsFileOp(cmd){let opMatch=cmd.match(/^(Copy-Item|Move-Item|Remove-Item)\b/i);if(!opMatch)return null;let cmdletName=opMatch[1],rest=cmd.slice(opMatch[0].length).trim(),destFlagMatch=rest.match(/-Destination\s+(\S+|"[^"]+"|'[^']+')/i);if(destFlagMatch){let path55=destFlagMatch[1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path55}}let tokens=[],flagTakingValue=new Set(["-Path","-LiteralPath","-Exclude","-Include","-Filter"]),switchFlags=new Set(["-Recurse","-Force","-Confirm","-WhatIf","-PassThru","-Verbose","-Debug"]),parts=rest.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[],i=0;while(i<parts.length){let part=parts[i];if(flagTakingValue.has(part)&&i+1<parts.length){let value=parts[i+1];if(!value.startsWith("-"))tokens.push(value);i+=2}else if(switchFlags.has(part))i++;else if(part.startsWith("-"))i++;else tokens.push(part),i++}if(tokens.length>=2){let path55=tokens[tokens.length-1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path55}}else if(tokens.length===1){let path55=tokens[0].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path55}}return null}let fileOp=detectPsFileOp(innerCommand);if(fileOp)results.push(fileOp);let pipeFileOpMatch=innerCommand.match(/\|\s*(Copy-Item|Move-Item)\b\s*(.*)$/i);if(pipeFileOpMatch){let cmdletName=pipeFileOpMatch[1],afterCmdlet=pipeFileOpMatch[2].trim(),destFlagMatch=afterCmdlet.match(/-Destination\s+(\S+|"[^"]+"|'[^']+')/i);if(destFlagMatch){let path55=destFlagMatch[1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path55})}else{let nonFlagTokens=(afterCmdlet.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[]).filter((t)=>!t.startsWith("-")&&t.length>0);if(nonFlagTokens.length>0){let path55=nonFlagTokens[nonFlagTokens.length-1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path55})}}}let aliasRedirectMatch=trimmed.match(/^(echo|write)\s+(\S+.*?)\s*(?:>|\s{2,})/i);if(aliasRedirectMatch){let _aliasPart=aliasRedirectMatch[0],_afterAlias=trimmed.slice(aliasRedirectMatch[0].length),fullRedirectMatch=trimmed.match(/((?:>){1,2})\s*(\S+)$/);if(fullRedirectMatch)results.push({category:"redirect",operator:fullRedirectMatch[1],path:fullRedirectMatch[2]})}let bareAliasMatch=trimmed.match(/^(echo|write)\s+.*?\s+((?:>){1,2})\s*(\S+)$/i);if(bareAliasMatch)results.push({category:"redirect",operator:bareAliasMatch[2],path:bareAliasMatch[3]});return results}function detectCmdWrites(command){let results=[],trimmed=command.trim();if(!trimmed)return results;let innerCommand=trimmed,cmdWrapperMatch=trimmed.match(/^cmd(?:\.exe)?\s+\/[ck]\s+(.*)$/i);if(cmdWrapperMatch){if(innerCommand=cmdWrapperMatch[1].trim(),innerCommand.startsWith('"')&&innerCommand.endsWith('"')||innerCommand.startsWith("'")&&innerCommand.endsWith("'"))innerCommand=innerCommand.slice(1,-1)}let redirectMatch=innerCommand.match(/^(.*?)\s+((?:>){1,2})\s*(\S+)$/);if(redirectMatch){let beforeRedirect=redirectMatch[1],op=redirectMatch[2],path55=redirectMatch[3];if(!/\d>&?$/.test(beforeRedirect))results.push({category:"redirect",operator:op,path:path55})}let leadingRedirect=innerCommand.match(/^((?:>){1,2})\s+(\S+)$/);if(leadingRedirect)results.push({category:"redirect",operator:leadingRedirect[1],path:leadingRedirect[2]});function detectCmdCopy(cmd){let directMatch=cmd.match(/^copy\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(directMatch)return{category:"builtin_write",operator:"copy",path:directMatch[2].replace(/^["']|["']$/g,"")};let ifExistMatch=cmd.match(/if\s+exist\s+\S+.*?copy\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(ifExistMatch)return{category:"builtin_write",operator:"copy",path:ifExistMatch[2].replace(/^["']|["']$/g,"")};return null}function detectCmdMove(cmd){let directMatch=cmd.match(/^move\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(directMatch)return{category:"builtin_write",operator:"move",path:directMatch[2].replace(/^["']|["']$/g,"")};let ifExistMatch=cmd.match(/if\s+exist\s+\S+.*?move\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(ifExistMatch)return{category:"builtin_write",operator:"move",path:ifExistMatch[2].replace(/^["']|["']$/g,"")};return null}let copyResult=detectCmdCopy(innerCommand);if(copyResult)results.push(copyResult);let moveResult=detectCmdMove(innerCommand);if(moveResult)results.push(moveResult);let renMatch=innerCommand.match(/^ren\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(renMatch){let dest=(renMatch[2]||"").replace(/^["']|["']$/g,"");if(dest)results.push({category:"builtin_write",operator:"ren",path:dest})}function detectCmdDel(cmd){let delMatch=cmd.match(/^del\s+/i);if(!delMatch)return null;let tokens=(cmd.slice(delMatch[0].length).trim().match(/(\/?[^\s]+|"[^"]*"|'[^']*')/g)??[]).filter((t)=>!t.startsWith("/"));if(tokens.length>0)return{category:"builtin_write",operator:"del",path:tokens[0].replace(/^["']|["']$/g,"")};return null}let delResult=detectCmdDel(innerCommand);if(delResult)results.push(delResult);let rdMatch=innerCommand.match(/^rd\s+(?:\/s\s+|\/q\s+)*(\S+)/i);if(rdMatch){let path55=rdMatch[1].replace(/^["']|["']$/g,"");if(!path55.startsWith("/"))results.push({category:"builtin_write",operator:"rd",path:path55})}let mdMatch=trimmed.match(/^md\s+(\S+)/i);if(mdMatch){let path55=mdMatch[1].replace(/^["']|["']$/g,"");if(!path55.startsWith("/"))results.push({category:"builtin_write",operator:"md",path:path55})}let echoMatch=trimmed.match(/^echo\s+(\S+.*?)\s+((?:>){1,2})\s*(\S+)$/i);if(echoMatch)results.push({category:"redirect",operator:echoMatch[2],path:echoMatch[3]});let echoDotMatch=trimmed.match(/^echo\.\s+((?:>){1,2})\s*(\S+)$/i);if(echoDotMatch)results.push({category:"redirect",operator:echoDotMatch[1],path:echoDotMatch[2]});let setMatch=trimmed.match(/^set\s+\S+\s*=\s*\S*\s*((?:>){1,2})\s*(\S+)$/i);if(setMatch)results.push({category:"redirect",operator:setMatch[1],path:setMatch[2]});return results}function detectInteractiveSession(command,shell){if(!command||typeof command!=="string")return!1;let trimmed=command.trim();if(shell==="posix"){let lower=trimmed.toLowerCase();if(/^watch(\s|$)/.test(lower))return!0;if(/^screen(\s|$)/.test(lower))return!0;if(/^tmux(\s+new-session(\s+.*)?)?$/.test(lower))return!0}else if(shell==="powershell"){if(/^Start-Process\s/i.test(trimmed))return!0}return!1}function detectPosixWrites(command){if(!command||typeof command!=="string")return{writes:[],hasWrites:!1};let ast,parseFailed=!1;try{ast=import_bash_parser.default(command,{mode:"posix"})}catch{parseFailed=!0}let allWrites=[];if(!parseFailed&&ast&&typeof ast==="object"){let leafCommands=[];collectLeafCommands(ast,leafCommands);for(let cmd of leafCommands)allWrites.push(...detectRedirects(cmd)),allWrites.push(...detectBuiltinWrites(cmd)),allWrites.push(...detectInplaceEdit(cmd)),allWrites.push(...detectInterpreterEval(cmd)),allWrites.push(...detectNetworkDownloaders(cmd)),allWrites.push(...detectArchiveExtract(cmd)),allWrites.push(...detectGitDestructive(cmd))}if(parseFailed){let procSubWrites=detectProcessSubstitutionWrites(command);allWrites.push(...procSubWrites)}let seen=new Set,writes=allWrites.filter((wt)=>{let key=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key))return!1;return seen.add(key),!0});return{writes,hasWrites:writes.length>0,parseError:parseFailed&&writes.length===0?!0:void 0}}function detectWindowsWrites(command,shell){if(!command||typeof command!=="string")return{writes:[],hasWrites:!1};try{let subCommands=splitWindowsCommands(command),allWrites=[];for(let subCmd of subCommands){let writes2=shell==="powershell"?detectPowerShellWrites(subCmd):detectCmdWrites(subCmd);allWrites.push(...writes2)}let seen=new Set,writes=allWrites.filter((wt)=>{let key=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key))return!1;return seen.add(key),!0});return{writes,hasWrites:writes.length>0}}catch{return{writes:[],hasWrites:!1,parseError:!0}}}function isDynamicPath(pathText){if(pathText===null||pathText===void 0)return!1;if(/\$[A-Za-z_][A-Za-z0-9_]*/.test(pathText))return!0;if(/\$\{[^}]+\}/.test(pathText))return!0;if(/\$\([^)]+\)/.test(pathText))return!0;if(/`[^`]+`/.test(pathText))return!0;return!1}function resolvePath(pathText,cwd){if(pathText===null)return null;if(isDynamicPath(pathText))return null;if(/^[a-zA-Z]:[\\\\/]/.test(cwd)||cwd.includes("\\"))return path54.win32.resolve(cwd,pathText);let normalizedRelativeWindowsPath=!path54.posix.isAbsolute(pathText)&&!/^[a-zA-Z]:[\\/]/.test(pathText)?pathText.replace(/\\/g,"/"):pathText;return path54.posix.resolve(cwd,normalizedRelativeWindowsPath)}function getCdTarget(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(c.type!=="SimpleCommand"&&c.type!=="Command")return null;let name=c.name;if(!name||typeof name!=="object")return null;let n=name;if(n.type!=="Word")return null;if(n.text!=="cd")return null;let suffix=c.suffix;if(!Array.isArray(suffix)||suffix.length===0)return null;let first=suffix[0];if(!first||typeof first!=="object")return null;let firstWord=first;if(firstWord.type!=="Word")return null;let target=firstWord.text;if(target==="-"||target==="~"||target==="~/")return null;return target}function collectWritesWithNodes(node,out,cwdStack){if(!node||typeof node!=="object")return;switch(node.type){case"Script":{let _globalCwd=cwdStack[0]??"/";if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack);break}case"Subshell":{let effectiveCwd=cwdStack[0]??"/",subshellRedirs=node.redirections;if(Array.isArray(subshellRedirs))for(let redirect of subshellRedirs){let writesFromRedirect=getWritesFromRedirectNode(redirect,effectiveCwd);for(let w of writesFromRedirect)out.push({write:w,context:effectiveCwd})}if(node.list){let subStack=[...cwdStack];collectWritesWithNodes(node.list,out,subStack)}break}case"CompoundList":{if(Array.isArray(node.commands)){let currentStack=cwdStack;for(let cmd of node.commands){let cdTarget=getCdTarget(cmd);if(cdTarget)currentStack[0]=path54.posix.resolve(currentStack[0]??"/",cdTarget),collectWritesWithNodes(cmd,out,currentStack);else collectWritesWithNodes(cmd,out,currentStack)}}break}case"Pipeline":case"Sequence":{if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack);break}case"LogicalExpression":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}break}case"And":case"Or":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}break}case"Command":case"SimpleCommand":{let effectiveCwd=cwdStack[0]??"/",cdTarget=getCdTarget(node);if(cdTarget){cwdStack[0]=path54.posix.resolve(cwdStack[0]??"/",cdTarget);return}let writesFromRedirs=getWritesFromCommandRedirs(node,effectiveCwd);for(let w of writesFromRedirs)out.push({write:w,context:effectiveCwd});let builtinWrites=detectBuiltinWrites(node);for(let w of builtinWrites)out.push({write:w,context:effectiveCwd});let inplaceWrites=detectInplaceEdit(node);for(let w of inplaceWrites)out.push({write:w,context:effectiveCwd});let interpreterWrites=detectInterpreterEval(node);for(let w of interpreterWrites)out.push({write:w,context:effectiveCwd});let networkWrites=detectNetworkDownloaders(node);for(let w of networkWrites)out.push({write:w,context:effectiveCwd});let archiveWrites=detectArchiveExtract(node);for(let w of archiveWrites)out.push({write:w,context:effectiveCwd});let gitWrites=detectGitDestructive(node);for(let w of gitWrites)out.push({write:w,context:effectiveCwd});break}}}function getWritesFromRedirectNode(redirect,_context){if(!redirect||typeof redirect!=="object")return[];let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")return[];let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))return[];let fileNode=r.file,path55=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType))return[{category:"redirect",operator:opLabel,path:path55}];else if(REDIRECT_HERE_TOKENS.has(opType))return[{category:"here_doc",operator:opLabel,path:path55}];return[]}function getWritesFromCommandRedirs(cmd,context){if(!cmd||typeof cmd!=="object")return[];let c=cmd,results=[];results.push(...detectHereDocMarkers(cmd));let{suffix,prefix}=c;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item)){let writes=getWritesFromRedirectNode(item,context);results.push(...writes)}}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item)){let writes=getWritesFromRedirectNode(item,context);results.push(...writes)}}return results}function resolveWriteTargets(command,writes,cwd){if(!writes||writes.length===0)return[];if(!command||typeof command!=="string")return writes.map((original)=>({original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}));let ast;try{ast=import_bash_parser.default(command,{mode:"posix"})}catch{ast=null}if(!ast||typeof ast!=="object")return writes.map((original)=>({original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}));let cwdStack=[cwd],writesWithNodes=[];collectWritesWithNodes(ast,writesWithNodes,cwdStack);let seen=new Set,deduplicated=writesWithNodes.filter((wwn)=>{let key=buildDedupeKey(wwn.write.category,wwn.write.operator,wwn.write.path);if(seen.has(key))return!1;return seen.add(key),!0}),resolvedMap=new Map;for(let{write,context}of deduplicated){let resolvedPath=resolvePath(write.path,context),resolved=write.path!==null&&!isDynamicPath(write.path),key=buildDedupeKey(write.category,write.operator,write.path);resolvedMap.set(key,{resolvedPath,resolved})}return writes.map((original)=>{let key=buildDedupeKey(original.category,original.operator,original.path),resolved=resolvedMap.get(key);if(resolved)return{original,resolvedPath:resolved.resolvedPath,resolved:resolved.resolved};return{original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}})}var import_bash_parser,REDIRECT_WRITE_TOKENS,REDIRECT_HERE_TOKENS,REDIRECT_ALL_WRITE_TOKENS,BUILTIN_WRITE_COMMANDS,INPLACE_EDIT_COMMANDS,INTERPRETER_EVAL_COMMANDS,NETWORK_DOWNLOAD_COMMANDS,ARCHIVE_EXTRACT_COMMANDS,GIT_COMMAND="git";var init_shell_write_detect=__esm(()=>{import_bash_parser=__toESM(require_src(),1);REDIRECT_WRITE_TOKENS=new Set(["GREAT","DGREAT","CLOBBER","LESSGREAT"]),REDIRECT_HERE_TOKENS=new Set(["DLESS","DLESSDASH"]),REDIRECT_ALL_WRITE_TOKENS=new Set([...REDIRECT_WRITE_TOKENS,...REDIRECT_HERE_TOKENS]),BUILTIN_WRITE_COMMANDS=new Set(["cp","mv","install","ln","truncate"]),INPLACE_EDIT_COMMANDS=new Set(["sed","perl","awk"]),INTERPRETER_EVAL_COMMANDS=new Set(["python","python3","python2","node","bun","ruby","perl","php"]),NETWORK_DOWNLOAD_COMMANDS=new Set(["curl","wget","scp"]),ARCHIVE_EXTRACT_COMMANDS=new Set(["tar","unzip","gunzip","gzip","bzip2","xz","7z","rar"])});import*as fs28 from"node:fs";import*as path55 from"node:path";function containsPathTraversal(str){if(/\.\.[/\\]/.test(str))return!0;if(/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(str))return!0;if(/%2e%2e/i.test(str))return!0;if(/%2e\./i.test(str))return!0;if(/%2e/i.test(str)&&/\.\./.test(str))return!0;if(/%252e%252e/i.test(str))return!0;if(/\uff0e/.test(str))return!0;if(/\u3002/.test(str))return!0;if(/\uff65/.test(str))return!0;if(/%2f/i.test(str))return!0;if(/%5c/i.test(str))return!0;return!1}function containsControlChars(str){for(let ch of str){let code=ch.codePointAt(0);if(code===void 0)continue;if(code<=31||code>=127&&code<=159)return!0;if(code>=8234&&code<=8238)return!0;if(code>=8294&&code<=8297)return!0}return!1}function validateDirectory(directory){if(!directory||directory.trim()==="")throw Error("Invalid directory: empty");if(containsPathTraversal(directory))throw Error("Invalid directory: path traversal detected");if(containsControlChars(directory))throw Error("Invalid directory: control characters detected");if(directory.startsWith("/")||directory.startsWith("\\"))throw Error("Invalid directory: absolute path");if(/^[A-Za-z]:[/\\]/.test(directory))throw Error("Invalid directory: Windows absolute path")}function validateSymlinkBoundary(targetPath,rootPath){let realTarget;try{realTarget=_internals30.realpathSync(targetPath)}catch{realTarget=path55.resolve(targetPath)}let realRoot;try{realRoot=_internals30.realpathSync(rootPath)}catch{realRoot=path55.resolve(rootPath)}let normalizedTarget=path55.normalize(realTarget),normalizedRoot=path55.normalize(realRoot);if(!normalizedTarget.startsWith(normalizedRoot+path55.sep)&&normalizedTarget!==normalizedRoot)throw Error(`Symlink resolution escaped boundary: ${realTarget} is not within ${realRoot}`)}function isCanonicalPathWithinRoot(targetPath,rootPath){let canonicalRoot;try{canonicalRoot=fs28.realpathSync(rootPath)}catch{canonicalRoot=path55.normalize(rootPath)}let probe2=path55.normalize(targetPath);for(let i=0;i<4096;i++)try{let canonicalProbe=fs28.realpathSync(probe2),relative15=path55.relative(canonicalRoot,canonicalProbe);return!relative15.startsWith("..")&&!path55.isAbsolute(relative15)}catch{let parent=path55.dirname(probe2);if(parent===probe2)return!1;probe2=parent}return!1}function validateTargetWithinRoot(filePath,root){if(!filePath||filePath.trim()==="")return"Empty path";if(path55.isAbsolute(filePath)||/^[A-Za-z]:[/\\]/.test(filePath))return`Absolute path rejected: ${filePath}`;if(containsPathTraversal(filePath))return`Path traversal detected: ${filePath}`;if(containsControlChars(filePath))return`Control characters detected in path: ${filePath}`;let resolved=path55.resolve(root,filePath),relative15=path55.relative(root,resolved);if(relative15.startsWith("..")||path55.isAbsolute(relative15))return`Path escapes root: ${filePath}`;if(!isCanonicalPathWithinRoot(resolved,root))return`Path escapes root via symlink/junction: ${filePath}`;return null}var _internals30;var init_path_security=__esm(()=>{_internals30={realpathSync:fs28.realpathSync,containsPathTraversal,containsControlChars,validateDirectory,validateSymlinkBoundary,isCanonicalPathWithinRoot,validateTargetWithinRoot}});import*as fs29 from"node:fs";import*as path56 from"node:path";function extractFilename(code,language,index){let lines=code.trim().split(`
|
|
692
|
+
`)return{nextReduction:reducers.start,nextState:state.setEscaping(!1).removeLastChar()};if(!state.escaping&&char==="\\")return{nextReduction:reducers.start,nextState:state.setEscaping(!0).appendChar(char)};if(!state.escaping&&char==="'")return{nextReduction:reducers.singleQuoting,nextState:state.appendChar(char)};if(!state.escaping&&char==='"')return{nextReduction:reducers.doubleQuoting,nextState:state.appendChar(char)};if(!state.escaping&&char==="$")return{nextReduction:reducers.expansionStart,nextState:state.appendChar(char).appendEmptyExpansion()};if(!state.escaping&&char==="`")return{nextReduction:reducers.expansionCommandTick,nextState:state.appendChar(char).appendEmptyExpansion()};return{nextReduction:reducers.start,nextState:state.appendChar(char).setEscaping(!1)}}module.exports={inherits:"posix",init:(posixMode)=>{let phaseCatalog=posixMode.phaseCatalog,lexerPhases=[convertToWord,phaseCatalog.parameterExpansion,phaseCatalog.arithmeticExpansion,phaseCatalog.commandExpansion,phaseCatalog.tildeExpanding,phaseCatalog.parameterExpansion.resolve,phaseCatalog.commandExpansion.resolve,phaseCatalog.arithmeticExpansion.resolve,phaseCatalog.fieldSplitting.split,phaseCatalog.pathExpansion,phaseCatalog.quoteRemoval,phaseCatalog.defaultNodeType],reducers=Object.assign({},posixMode.tokenizer.reducers,{start});return Object.assign({},posixMode,{lexerPhases,tokenizer:()=>posixMode.tokenizer({},reducers)})}}});var require_src=__commonJS((exports,module)=>{var shellLexer=require_shell_lexer(),utils=require_utils2(),modes={bash:require_bash(),posix:require_posix(),"word-expansion":require_word_expansion()};function loadPlugin(name){let modePlugin=modes[name];if(modePlugin.inherits)return modePlugin.init(loadPlugin(modePlugin.inherits),utils);return modePlugin.init(null,utils)}module.exports=function(sourceCode,options){try{options=options||{},options.mode=options.mode||"posix";let mode=loadPlugin(options.mode),Parser=mode.grammar.Parser,astBuilder=mode.astBuilder,parser=new Parser;return parser.lexer=shellLexer(mode,options),parser.yy=astBuilder(options),parser.parse(sourceCode)}catch(err){if(err instanceof SyntaxError)throw err;throw Error(err.stack||err.message)}}});import*as path54 from"node:path";function buildDedupeKey(category,operator,path55){return`${category}|${operator}|${path55??"null"}`}function detectProcessSubstitutionWrites(command){let results=[],writeProcSubPattern=/>\s*\(([^)]+)\)/g;while(!0){let match=writeProcSubPattern.exec(command);if(match===null)break;let innerCommand=match[1].trim();if(!innerCommand)continue;let stages=innerCommand.split("|").map((s)=>s.trim());for(let stage of stages){let builtinResult=detectBuiltinWritesFromString(stage);if(builtinResult)results.push(builtinResult);let appendMatch=stage.match(/^\s*(.*?)\s*>>(\s*)(\S+)\s*$/);if(appendMatch){let path55=appendMatch[3];if(path55&&!isNullDevice(path55))results.push({category:"redirect",operator:">>",path:path55})}else{let writeMatch=stage.match(/^\s*(.*?)\s*>(?!>)(\s*)(\S+)\s*$/);if(writeMatch){let path55=writeMatch[3];if(path55&&!isNullDevice(path55))results.push({category:"redirect",operator:">",path:path55})}}}}return results}function detectBuiltinWritesFromString(cmd){let tokens=cmd.trim().split(/\s+/);if(tokens.length===0)return null;let name=tokens[0].toLowerCase();if(BUILTIN_WRITE_COMMANDS.has(name)){for(let i=tokens.length-1;i>=1;i--)if(!tokens[i].startsWith("-"))return{category:"builtin_write",operator:name,path:tokens[i]}}return null}function wordText(node){if(!node||typeof node!=="object")return null;if(isBashWord(node))return node.text;return null}function isBashWord(node){return!!node&&typeof node==="object"&&node.type==="Word"&&typeof node.text==="string"}function collectLeafCommands(node,out){if(!node||typeof node!=="object")return;switch(node.type){case"Script":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"Pipeline":case"Sequence":if(Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"CompoundList":if(out.push(node),Array.isArray(node.commands))for(let cmd of node.commands)collectLeafCommands(cmd,out);break;case"LogicalExpression":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"And":case"Or":if(node.left)collectLeafCommands(node.left,out);if(node.right)collectLeafCommands(node.right,out);break;case"Subshell":if(out.push(node),node.list)collectLeafCommands(node.list,out);break;case"ProcessSubstitution":{let opNode=node.op;if(opNode&&typeof opNode==="object"){if(opNode.type?.toUpperCase()==="GREAT"){if(node.command)collectLeafCommands(node.command,out)}}}break;default:out.push(node);break}}function getCommandName(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(typeof c.name==="string")return c.name;return wordText(c.name)}function getSuffixWords(cmd){if(!cmd||typeof cmd!=="object")return[];let suffix=cmd.suffix;if(!Array.isArray(suffix))return[];return suffix.map((s)=>wordText(s)??"")}function getRedirections(cmd){if(!cmd||typeof cmd!=="object")return[];let c=cmd;if(Array.isArray(c.redirections))return c.redirections;let results=[],suffix=c.suffix,prefix=c.prefix;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item))results.push(item)}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item))results.push(item)}return results}function isRedirectNode(node){return!!(node&&typeof node==="object"&&node.type==="Redirect")}function operatorLabel(op){if(!op||typeof op!=="object")return"unknown";let opType=op.type?.toUpperCase();switch(opType){case"GREAT":return">";case"DGREAT":return">>";case"CLOBBER":return">|";case"LESS":return"<";case"DLESS":return"<<";case"DLESSDASH":return"<<-";case"LESSAND":return"<&";case"GREATAND":return">&";case"LESSGREAT":return"<>";default:return opType||"unknown"}}function extractRedirectPath(fileNode){let text=wordText(fileNode);if(!text)return null;return text}function isNullDevice(path55){return path55==="/dev/null"||path55==="/dev/zero"||path55==="/dev/urandom"}function isNumeric(s){return/^\d+$/.test(s)}function detectRedirects(cmd){let results=[];results.push(...detectHereDocMarkers(cmd));let redirections=getRedirections(cmd);for(let redirect of redirections){if(!redirect||typeof redirect!=="object")continue;let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")continue;let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))continue;let fileNode=r.file,path55=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType))results.push({category:"redirect",operator:opLabel,path:path55});else if(REDIRECT_HERE_TOKENS.has(opType))results.push({category:"here_doc",operator:opLabel,path:path55})}return results}function detectHereDocMarkers(cmd){let results=[];if(!cmd||typeof cmd!=="object")return results;let suffix=cmd.suffix;if(!Array.isArray(suffix))return results;for(let item of suffix){if(!item||typeof item!=="object")continue;if(isHereDocMarker(item))results.push({category:"here_doc",operator:item.text==="<<-"?"<<-":"<<",path:null})}return results}function isHereDocMarker(node){if(!node||typeof node!=="object")return!1;let type=node.type?.toLowerCase();return type==="dless"||type==="dlessdash"}function detectBuiltinWrites(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(lowerName==="dd"){let suffixWords2=getSuffixWords(cmd);for(let word of suffixWords2)if(word.startsWith("of=")){let path55=word.slice(3);if(path55&&!isNullDevice(path55))results.push({category:"builtin_write",operator:"dd of=",path:path55})}return results}if(lowerName==="tee"){let suffixWords2=getSuffixWords(cmd),pastDoubleDash=!1;for(let word of suffixWords2){if(word==="--"){pastDoubleDash=!0;continue}if(!pastDoubleDash&&word.startsWith("-"))continue;if(word&&!isNullDevice(word))results.push({category:"builtin_write",operator:"tee",path:word})}return results}if(!BUILTIN_WRITE_COMMANDS.has(lowerName))return results;let suffixWords=getSuffixWords(cmd);if(lowerName==="truncate"){for(let word of suffixWords)if(!word.startsWith("-")&&!isNumeric(word)){results.push({category:"builtin_write",operator:"truncate",path:word});break}}else for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"builtin_write",operator:name,path:word});break}}return results}function detectInplaceEdit(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INPLACE_EDIT_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd);if(!suffixWords.some((word)=>{if(lowerName==="sed")return word.startsWith("-i")&&word.length>1;return word==="-i"||word.startsWith("-i")}))return[];let scriptPattern=/^[ssy]\/.*\/[gim]*$/,quotedScriptPattern=/^["'].*["']$/,flagArgs=new Set(["-e","-E","-f","-i"]),combinedFlagArgs=/^-[paaneA]+[eEf]/,sedInplaceSuffix=/^-i[a-z]+/i,skipIndices=new Set;for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word.startsWith("-")){if(flagArgs.has(word)||combinedFlagArgs.test(word)||sedInplaceSuffix.test(word)){if(skipIndices.add(i),i+1<suffixWords.length)skipIndices.add(i+1)}}else if(scriptPattern.test(word)||quotedScriptPattern.test(word))skipIndices.add(i)}let candidates=suffixWords.map((word,i)=>({word,i})).filter(({i})=>!skipIndices.has(i));if(candidates.length>0){let file2=candidates[0].word;results.push({category:"inplace_edit",operator:`${name} -i`,path:file2})}return results}function detectInterpreterEval(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!INTERPRETER_EVAL_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd),relevantFlags={python:["-c"],python3:["-c"],python2:["-c"],node:["-e","-p","-pe"],bun:["-e","-p","-pe"],ruby:["-e"],perl:["-e","-E"],php:["-r","-R","-F"]}[lowerName]??[];if(!suffixWords.some((word)=>relevantFlags.some((f)=>word===f||word.startsWith(f)&&word.length>f.length)))return[];return results.push({category:"interpreter_eval",operator:`${name} [eval]`,path:null}),results}function detectNetworkDownloaders(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!NETWORK_DOWNLOAD_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="curl")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-o"&&i+1<suffixWords.length){let path55=suffixWords[i+1];if(!path55.startsWith("-"))results.push({category:"network_download",operator:"curl -o",path:path55})}else if(word.startsWith("-o")&&word.length>2)results.push({category:"network_download",operator:"curl -o",path:word.slice(2)})}else if(lowerName==="wget")for(let i=0;i<suffixWords.length;i++){let word=suffixWords[i];if(word==="-O"&&i+1<suffixWords.length){let path55=suffixWords[i+1];if(!path55.startsWith("-"))results.push({category:"network_download",operator:"wget -O",path:path55})}else if(word.startsWith("-O")&&word.length>2)results.push({category:"network_download",operator:"wget -O",path:word.slice(2)})}else if(lowerName==="scp")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")&&(word.includes(":")||word.startsWith("/")||word.startsWith("."))){results.push({category:"network_download",operator:"scp",path:word});break}}return results}function detectArchiveExtract(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;let lowerName=name.toLowerCase();if(!ARCHIVE_EXTRACT_COMMANDS.has(lowerName))return[];let suffixWords=getSuffixWords(cmd);if(lowerName==="tar"){if(suffixWords.some((word)=>{if(word==="--extract"||word==="--get")return!0;if(word.startsWith("-")&&word.includes("x"))return!0;return!1}))for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"tar -x",path:word});break}if(word.startsWith("--file=")&&word.length>7){results.push({category:"archive_extract",operator:"tar -x",path:word.slice(7)});break}}}else if(lowerName==="unzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:"unzip",path:word});break}}else if(lowerName==="gunzip"||lowerName==="gzip"||lowerName==="bzip2"||lowerName==="xz"||lowerName==="7z"||lowerName==="rar"){if(suffixWords.includes("-d")||suffixWords.includes("--decompress")||lowerName==="gunzip")for(let i=suffixWords.length-1;i>=0;i--){let word=suffixWords[i];if(!word.startsWith("-")){results.push({category:"archive_extract",operator:`${name} [decompress]`,path:word});break}}}return results}function detectGitDestructive(cmd){let results=[],name=getCommandName(cmd);if(!name)return results;if(name.toLowerCase()!==GIT_COMMAND)return[];let suffixWords=getSuffixWords(cmd);if(suffixWords.length===0)return[];let first=suffixWords[0].toLowerCase();if(first==="checkout"){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length){let path55=suffixWords[dashDashIdx+1],op=path55==="."?"git checkout -- .":"git checkout --";results.push({category:"git_destructive",operator:op,path:path55})}}else if(first==="restore"){let hasHard=suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")),hasForce=suffixWords.some((w)=>w==="--force"||w==="-f"||w.startsWith("-")&&w.includes("f"));if(hasHard||hasForce){let dashDashIdx=suffixWords.indexOf("--");if(dashDashIdx!==-1&&dashDashIdx+1<suffixWords.length)results.push({category:"git_destructive",operator:"git restore",path:suffixWords[dashDashIdx+1]});else results.push({category:"git_destructive",operator:"git restore",path:null})}}else if(first==="reset"){if(suffixWords.some((w)=>w==="--hard"||w==="-H"||w.startsWith("-")&&w.includes("H")))results.push({category:"git_destructive",operator:"git reset --hard",path:null})}else if(first==="clean"){if(suffixWords.some((w)=>w==="-n"||w==="--dry-run"||w.startsWith("-")&&w.includes("n")))return results;let hasForce=suffixWords.some((w)=>w==="-f"||w==="--force"||w.startsWith("-")&&w.includes("f")),hasDir=suffixWords.some((w)=>w==="-d"||w==="--dir"||w.startsWith("-")&&w.includes("d"));if(hasForce&&hasDir)results.push({category:"git_destructive",operator:"git clean -fd",path:null})}return results}function splitWindowsCommands(command){let commands=[],current="",inSingleQuote=!1,inDoubleQuote=!1,parenDepth=0;for(let i=0;i<command.length;i++){let ch=command[i];if(ch==="'"&&!inDoubleQuote)inSingleQuote=!inSingleQuote;else if(ch==='"'&&!inSingleQuote)inDoubleQuote=!inDoubleQuote;else if(ch==="("&&!inSingleQuote&&!inDoubleQuote)parenDepth++;else if(ch===")"&&!inSingleQuote&&!inDoubleQuote)parenDepth--;if(ch==="|"&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());current="";continue}if((ch==="&"||ch==="|")&&i+1<command.length&&command[i+1]===ch&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(current.trim())commands.push(current.trim());commands.push(ch==="&"?"&&":"||"),current="",i++;continue}if(ch==="&"&&!inSingleQuote&&!inDoubleQuote&&parenDepth===0){if(!(i+1<command.length&&command[i+1]==="&")){if(current.trim())commands.push(current.trim());current="";continue}}current+=ch}if(current.trim())commands.push(current.trim());return commands.filter((c)=>c!=="&&"&&c!=="||")}function detectPowerShellWrites(command){let results=[],trimmed=command.trim();if(!trimmed)return results;let innerCommand=trimmed,cmdMatch=trimmed.match(/^(?:powershell|pwsh)\s+(?:-Command|-C)\s+(.*)$/i);if(cmdMatch){if(innerCommand=cmdMatch[1].trim(),innerCommand.startsWith('"')&&innerCommand.endsWith('"')||innerCommand.startsWith("'")&&innerCommand.endsWith("'"))innerCommand=innerCommand.slice(1,-1)}let redirectMatch=innerCommand.match(/^(.*?)\s+((?:>){1,2})\s*(\S+)$/);if(redirectMatch){let beforeRedirect=redirectMatch[1],op=redirectMatch[2],path55=redirectMatch[3];if(!/\d>\s*$|\s\d>&$/.test(`${beforeRedirect} ${op}`))results.push({category:"redirect",operator:op,path:path55})}let leadingRedirect=innerCommand.match(/^((?:>){1,2})\s+(\S+)$/);if(leadingRedirect)results.push({category:"redirect",operator:leadingRedirect[1],path:leadingRedirect[2]});let iwrMatch=trimmed.match(/^(?:Invoke-WebRequest|curl)\s.*?(?:-OutFile\s+(\S+)|-o\s+(\S+))/i);if(iwrMatch){let path55=iwrMatch[1]||iwrMatch[2];if(path55)results.push({category:"network_download",operator:"Invoke-WebRequest -OutFile",path:path55})}function detectPsContentCmdlet(cmd){let cmdletMatch=cmd.match(/^(Out-File|Set-Content|Add-Content|Clear-Content)\b/i);if(!cmdletMatch)return null;let cmdletName=cmdletMatch[1],rest=cmd.slice(cmdletMatch[0].length).trim(),pathFlagMatch=rest.match(/(?:-Path|-FilePath|-LiteralPath)\s+("([^"]+)"|'([^']+)'|(\S+))/i);if(pathFlagMatch){let path55=pathFlagMatch[2]??pathFlagMatch[3]??pathFlagMatch[4]??"";return{category:"redirect",operator:cmdletName,path:path55}}let tokens=rest.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[];for(let token of tokens){if(token.startsWith("-"))continue;let path55=token.replace(/^["']|["']$/g,"");return{category:"redirect",operator:cmdletName,path:path55}}return null}let contentResult=detectPsContentCmdlet(innerCommand);if(contentResult)results.push(contentResult);let pipeContentMatch=innerCommand.match(/\|\s*(Out-File|Set-Content|Add-Content|Clear-Content)\b\s*(.*)$/i);if(pipeContentMatch){let cmdletName=pipeContentMatch[1],tokens=pipeContentMatch[2].trim().match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[];for(let token of tokens){if(token.startsWith("-"))continue;let path55=token.replace(/^["']|["']$/g,"");if(path55){results.push({category:"redirect",operator:cmdletName,path:path55});break}}}function detectPsFileOp(cmd){let opMatch=cmd.match(/^(Copy-Item|Move-Item|Remove-Item)\b/i);if(!opMatch)return null;let cmdletName=opMatch[1],rest=cmd.slice(opMatch[0].length).trim(),destFlagMatch=rest.match(/-Destination\s+(\S+|"[^"]+"|'[^']+')/i);if(destFlagMatch){let path55=destFlagMatch[1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path55}}let tokens=[],flagTakingValue=new Set(["-Path","-LiteralPath","-Exclude","-Include","-Filter"]),switchFlags=new Set(["-Recurse","-Force","-Confirm","-WhatIf","-PassThru","-Verbose","-Debug"]),parts=rest.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[],i=0;while(i<parts.length){let part=parts[i];if(flagTakingValue.has(part)&&i+1<parts.length){let value=parts[i+1];if(!value.startsWith("-"))tokens.push(value);i+=2}else if(switchFlags.has(part))i++;else if(part.startsWith("-"))i++;else tokens.push(part),i++}if(tokens.length>=2){let path55=tokens[tokens.length-1].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path55}}else if(tokens.length===1){let path55=tokens[0].replace(/^["']|["']$/g,"");return{category:"builtin_write",operator:cmdletName,path:path55}}return null}let fileOp=detectPsFileOp(innerCommand);if(fileOp)results.push(fileOp);let pipeFileOpMatch=innerCommand.match(/\|\s*(Copy-Item|Move-Item)\b\s*(.*)$/i);if(pipeFileOpMatch){let cmdletName=pipeFileOpMatch[1],afterCmdlet=pipeFileOpMatch[2].trim(),destFlagMatch=afterCmdlet.match(/-Destination\s+(\S+|"[^"]+"|'[^']+')/i);if(destFlagMatch){let path55=destFlagMatch[1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path55})}else{let nonFlagTokens=(afterCmdlet.match(/(?:[^\s"-]+|"[^"]*"|'[^']*'|-[^\s]+)/g)??[]).filter((t)=>!t.startsWith("-")&&t.length>0);if(nonFlagTokens.length>0){let path55=nonFlagTokens[nonFlagTokens.length-1].replace(/^["']|["']$/g,"");results.push({category:"builtin_write",operator:cmdletName,path:path55})}}}let aliasRedirectMatch=trimmed.match(/^(echo|write)\s+(\S+.*?)\s*(?:>|\s{2,})/i);if(aliasRedirectMatch){let _aliasPart=aliasRedirectMatch[0],_afterAlias=trimmed.slice(aliasRedirectMatch[0].length),fullRedirectMatch=trimmed.match(/((?:>){1,2})\s*(\S+)$/);if(fullRedirectMatch)results.push({category:"redirect",operator:fullRedirectMatch[1],path:fullRedirectMatch[2]})}let bareAliasMatch=trimmed.match(/^(echo|write)\s+.*?\s+((?:>){1,2})\s*(\S+)$/i);if(bareAliasMatch)results.push({category:"redirect",operator:bareAliasMatch[2],path:bareAliasMatch[3]});return results}function detectCmdWrites(command){let results=[],trimmed=command.trim();if(!trimmed)return results;let innerCommand=trimmed,cmdWrapperMatch=trimmed.match(/^cmd(?:\.exe)?\s+\/[ck]\s+(.*)$/i);if(cmdWrapperMatch){if(innerCommand=cmdWrapperMatch[1].trim(),innerCommand.startsWith('"')&&innerCommand.endsWith('"')||innerCommand.startsWith("'")&&innerCommand.endsWith("'"))innerCommand=innerCommand.slice(1,-1)}let redirectMatch=innerCommand.match(/^(.*?)\s+((?:>){1,2})\s*(\S+)$/);if(redirectMatch){let beforeRedirect=redirectMatch[1],op=redirectMatch[2],path55=redirectMatch[3];if(!/\d>&?$/.test(beforeRedirect))results.push({category:"redirect",operator:op,path:path55})}let leadingRedirect=innerCommand.match(/^((?:>){1,2})\s+(\S+)$/);if(leadingRedirect)results.push({category:"redirect",operator:leadingRedirect[1],path:leadingRedirect[2]});function detectCmdCopy(cmd){let directMatch=cmd.match(/^copy\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(directMatch)return{category:"builtin_write",operator:"copy",path:directMatch[2].replace(/^["']|["']$/g,"")};let ifExistMatch=cmd.match(/if\s+exist\s+\S+.*?copy\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(ifExistMatch)return{category:"builtin_write",operator:"copy",path:ifExistMatch[2].replace(/^["']|["']$/g,"")};return null}function detectCmdMove(cmd){let directMatch=cmd.match(/^move\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(directMatch)return{category:"builtin_write",operator:"move",path:directMatch[2].replace(/^["']|["']$/g,"")};let ifExistMatch=cmd.match(/if\s+exist\s+\S+.*?move\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(ifExistMatch)return{category:"builtin_write",operator:"move",path:ifExistMatch[2].replace(/^["']|["']$/g,"")};return null}let copyResult=detectCmdCopy(innerCommand);if(copyResult)results.push(copyResult);let moveResult=detectCmdMove(innerCommand);if(moveResult)results.push(moveResult);let renMatch=innerCommand.match(/^ren\s+(\S+|"[^"]+"|'[^']+')\s+(\S+|"[^"]+"|'[^']+')/i);if(renMatch){let dest=(renMatch[2]||"").replace(/^["']|["']$/g,"");if(dest)results.push({category:"builtin_write",operator:"ren",path:dest})}function detectCmdDel(cmd){let delMatch=cmd.match(/^del\s+/i);if(!delMatch)return null;let tokens=(cmd.slice(delMatch[0].length).trim().match(/(\/?[^\s]+|"[^"]*"|'[^']*')/g)??[]).filter((t)=>!t.startsWith("/"));if(tokens.length>0)return{category:"builtin_write",operator:"del",path:tokens[0].replace(/^["']|["']$/g,"")};return null}let delResult=detectCmdDel(innerCommand);if(delResult)results.push(delResult);let rdMatch=innerCommand.match(/^rd\s+(?:\/s\s+|\/q\s+)*(\S+)/i);if(rdMatch){let path55=rdMatch[1].replace(/^["']|["']$/g,"");if(!path55.startsWith("/"))results.push({category:"builtin_write",operator:"rd",path:path55})}let mdMatch=trimmed.match(/^md\s+(\S+)/i);if(mdMatch){let path55=mdMatch[1].replace(/^["']|["']$/g,"");if(!path55.startsWith("/"))results.push({category:"builtin_write",operator:"md",path:path55})}let echoMatch=trimmed.match(/^echo\s+(\S+.*?)\s+((?:>){1,2})\s*(\S+)$/i);if(echoMatch)results.push({category:"redirect",operator:echoMatch[2],path:echoMatch[3]});let echoDotMatch=trimmed.match(/^echo\.\s+((?:>){1,2})\s*(\S+)$/i);if(echoDotMatch)results.push({category:"redirect",operator:echoDotMatch[1],path:echoDotMatch[2]});let setMatch=trimmed.match(/^set\s+\S+\s*=\s*\S*\s*((?:>){1,2})\s*(\S+)$/i);if(setMatch)results.push({category:"redirect",operator:setMatch[1],path:setMatch[2]});return results}function detectInteractiveSession(command,shell){if(!command||typeof command!=="string")return!1;let trimmed=command.trim();if(shell==="posix"){let lower=trimmed.toLowerCase();if(/^watch(\s|$)/.test(lower))return!0;if(/^screen(\s|$)/.test(lower))return!0;if(/^tmux(\s+new-session(\s+.*)?)?$/.test(lower))return!0}else if(shell==="powershell"){if(/^Start-Process\s/i.test(trimmed))return!0}return!1}function detectPosixWrites(command){if(!command||typeof command!=="string")return{writes:[],hasWrites:!1};let ast,parseFailed=!1;try{ast=import_bash_parser.default(command,{mode:"posix"})}catch{parseFailed=!0}let allWrites=[];if(!parseFailed&&ast&&typeof ast==="object"){let leafCommands=[];collectLeafCommands(ast,leafCommands);for(let cmd of leafCommands)allWrites.push(...detectRedirects(cmd)),allWrites.push(...detectBuiltinWrites(cmd)),allWrites.push(...detectInplaceEdit(cmd)),allWrites.push(...detectInterpreterEval(cmd)),allWrites.push(...detectNetworkDownloaders(cmd)),allWrites.push(...detectArchiveExtract(cmd)),allWrites.push(...detectGitDestructive(cmd))}if(parseFailed){let procSubWrites=detectProcessSubstitutionWrites(command);allWrites.push(...procSubWrites)}let seen=new Set,writes=allWrites.filter((wt)=>{let key=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key))return!1;return seen.add(key),!0});return{writes,hasWrites:writes.length>0,parseError:parseFailed&&writes.length===0?!0:void 0}}function detectWindowsWrites(command,shell){if(!command||typeof command!=="string")return{writes:[],hasWrites:!1};try{let subCommands=splitWindowsCommands(command),allWrites=[];for(let subCmd of subCommands){let writes2=shell==="powershell"?detectPowerShellWrites(subCmd):detectCmdWrites(subCmd);allWrites.push(...writes2)}let seen=new Set,writes=allWrites.filter((wt)=>{let key=buildDedupeKey(wt.category,wt.operator,wt.path);if(seen.has(key))return!1;return seen.add(key),!0});return{writes,hasWrites:writes.length>0}}catch{return{writes:[],hasWrites:!1,parseError:!0}}}function isDynamicPath(pathText){if(pathText===null||pathText===void 0)return!1;if(/\$[A-Za-z_][A-Za-z0-9_]*/.test(pathText))return!0;if(/\$\{[^}]+\}/.test(pathText))return!0;if(/\$\([^)]+\)/.test(pathText))return!0;if(/`[^`]+`/.test(pathText))return!0;return!1}function resolvePath(pathText,cwd){if(pathText===null)return null;if(isDynamicPath(pathText))return null;if(/^[a-zA-Z]:[\\\\/]/.test(cwd)||cwd.includes("\\"))return path54.win32.resolve(cwd,pathText);let normalizedRelativeWindowsPath=!path54.posix.isAbsolute(pathText)&&!/^[a-zA-Z]:[\\/]/.test(pathText)?pathText.replace(/\\/g,"/"):pathText;return path54.posix.resolve(cwd,normalizedRelativeWindowsPath)}function getCdTarget(cmd){if(!cmd||typeof cmd!=="object")return null;let c=cmd;if(c.type!=="SimpleCommand"&&c.type!=="Command")return null;let name=c.name;if(!name||typeof name!=="object")return null;let n=name;if(n.type!=="Word")return null;if(n.text!=="cd")return null;let suffix=c.suffix;if(!Array.isArray(suffix)||suffix.length===0)return null;let first=suffix[0];if(!first||typeof first!=="object")return null;let firstWord=first;if(firstWord.type!=="Word")return null;let target=firstWord.text;if(target==="-"||target==="~"||target==="~/")return null;return target}function collectWritesWithNodes(node,out,cwdStack){if(!node||typeof node!=="object")return;switch(node.type){case"Script":{let _globalCwd=cwdStack[0]??"/";if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack);break}case"Subshell":{let effectiveCwd=cwdStack[0]??"/",subshellRedirs=node.redirections;if(Array.isArray(subshellRedirs))for(let redirect of subshellRedirs){let writesFromRedirect=getWritesFromRedirectNode(redirect,effectiveCwd);for(let w of writesFromRedirect)out.push({write:w,context:effectiveCwd})}if(node.list){let subStack=[...cwdStack];collectWritesWithNodes(node.list,out,subStack)}break}case"CompoundList":{if(Array.isArray(node.commands)){let currentStack=cwdStack;for(let cmd of node.commands){let cdTarget=getCdTarget(cmd);if(cdTarget)currentStack[0]=path54.posix.resolve(currentStack[0]??"/",cdTarget),collectWritesWithNodes(cmd,out,currentStack);else collectWritesWithNodes(cmd,out,currentStack)}}break}case"Pipeline":case"Sequence":{if(Array.isArray(node.commands))for(let cmd of node.commands)collectWritesWithNodes(cmd,out,cwdStack);break}case"LogicalExpression":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}break}case"And":case"Or":{if(node.left){collectWritesWithNodes(node.left,out,cwdStack);let leftContext=cwdStack[0]??"/";if(node.right){let rightStack=[leftContext];collectWritesWithNodes(node.right,out,rightStack)}}break}case"Command":case"SimpleCommand":{let effectiveCwd=cwdStack[0]??"/",cdTarget=getCdTarget(node);if(cdTarget){cwdStack[0]=path54.posix.resolve(cwdStack[0]??"/",cdTarget);return}let writesFromRedirs=getWritesFromCommandRedirs(node,effectiveCwd);for(let w of writesFromRedirs)out.push({write:w,context:effectiveCwd});let builtinWrites=detectBuiltinWrites(node);for(let w of builtinWrites)out.push({write:w,context:effectiveCwd});let inplaceWrites=detectInplaceEdit(node);for(let w of inplaceWrites)out.push({write:w,context:effectiveCwd});let interpreterWrites=detectInterpreterEval(node);for(let w of interpreterWrites)out.push({write:w,context:effectiveCwd});let networkWrites=detectNetworkDownloaders(node);for(let w of networkWrites)out.push({write:w,context:effectiveCwd});let archiveWrites=detectArchiveExtract(node);for(let w of archiveWrites)out.push({write:w,context:effectiveCwd});let gitWrites=detectGitDestructive(node);for(let w of gitWrites)out.push({write:w,context:effectiveCwd});break}}}function getWritesFromRedirectNode(redirect,_context){if(!redirect||typeof redirect!=="object")return[];let r=redirect,opNode=r.op;if(!opNode||typeof opNode!=="object")return[];let opType=opNode.type?.toUpperCase();if(!opType||!REDIRECT_ALL_WRITE_TOKENS.has(opType))return[];let fileNode=r.file,path55=extractRedirectPath(fileNode),opLabel=operatorLabel(opNode);if(REDIRECT_WRITE_TOKENS.has(opType))return[{category:"redirect",operator:opLabel,path:path55}];else if(REDIRECT_HERE_TOKENS.has(opType))return[{category:"here_doc",operator:opLabel,path:path55}];return[]}function getWritesFromCommandRedirs(cmd,context){if(!cmd||typeof cmd!=="object")return[];let c=cmd,results=[];results.push(...detectHereDocMarkers(cmd));let{suffix,prefix}=c;if(Array.isArray(suffix)){for(let item of suffix)if(isRedirectNode(item)){let writes=getWritesFromRedirectNode(item,context);results.push(...writes)}}if(Array.isArray(prefix)){for(let item of prefix)if(isRedirectNode(item)){let writes=getWritesFromRedirectNode(item,context);results.push(...writes)}}return results}function resolveWriteTargets(command,writes,cwd){if(!writes||writes.length===0)return[];if(!command||typeof command!=="string")return writes.map((original)=>({original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}));let ast;try{ast=import_bash_parser.default(command,{mode:"posix"})}catch{ast=null}if(!ast||typeof ast!=="object")return writes.map((original)=>({original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}));let cwdStack=[cwd],writesWithNodes=[];collectWritesWithNodes(ast,writesWithNodes,cwdStack);let seen=new Set,deduplicated=writesWithNodes.filter((wwn)=>{let key=buildDedupeKey(wwn.write.category,wwn.write.operator,wwn.write.path);if(seen.has(key))return!1;return seen.add(key),!0}),resolvedMap=new Map;for(let{write,context}of deduplicated){let resolvedPath=resolvePath(write.path,context),resolved=write.path!==null&&!isDynamicPath(write.path),key=buildDedupeKey(write.category,write.operator,write.path);resolvedMap.set(key,{resolvedPath,resolved})}return writes.map((original)=>{let key=buildDedupeKey(original.category,original.operator,original.path),resolved=resolvedMap.get(key);if(resolved)return{original,resolvedPath:resolved.resolvedPath,resolved:resolved.resolved};return{original,resolvedPath:resolvePath(original.path,cwd),resolved:original.path!==null&&!isDynamicPath(original.path)}})}var import_bash_parser,REDIRECT_WRITE_TOKENS,REDIRECT_HERE_TOKENS,REDIRECT_ALL_WRITE_TOKENS,BUILTIN_WRITE_COMMANDS,INPLACE_EDIT_COMMANDS,INTERPRETER_EVAL_COMMANDS,NETWORK_DOWNLOAD_COMMANDS,ARCHIVE_EXTRACT_COMMANDS,GIT_COMMAND="git";var init_shell_write_detect=__esm(()=>{import_bash_parser=__toESM(require_src(),1);REDIRECT_WRITE_TOKENS=new Set(["GREAT","DGREAT","CLOBBER","LESSGREAT"]),REDIRECT_HERE_TOKENS=new Set(["DLESS","DLESSDASH"]),REDIRECT_ALL_WRITE_TOKENS=new Set([...REDIRECT_WRITE_TOKENS,...REDIRECT_HERE_TOKENS]),BUILTIN_WRITE_COMMANDS=new Set(["cp","mv","install","ln","truncate"]),INPLACE_EDIT_COMMANDS=new Set(["sed","perl","awk"]),INTERPRETER_EVAL_COMMANDS=new Set(["python","python3","python2","node","bun","ruby","perl","php"]),NETWORK_DOWNLOAD_COMMANDS=new Set(["curl","wget","scp"]),ARCHIVE_EXTRACT_COMMANDS=new Set(["tar","unzip","gunzip","gzip","bzip2","xz","7z","rar"])});import*as fs28 from"node:fs";import*as path55 from"node:path";function containsPathTraversal(str){if(/\.\.[/\\]/.test(str))return!0;if(/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(str))return!0;if(/%2e%2e/i.test(str))return!0;if(/%2e\./i.test(str))return!0;if(/%2e/i.test(str)&&/\.\./.test(str))return!0;if(/%252e%252e/i.test(str))return!0;if(/\uff0e/.test(str))return!0;if(/\u3002/.test(str))return!0;if(/\uff65/.test(str))return!0;if(/%2f/i.test(str))return!0;if(/%5c/i.test(str))return!0;return!1}function containsControlChars(str){for(let ch of str){let code=ch.codePointAt(0);if(code===void 0)continue;if(code<=31||code>=127&&code<=159)return!0;if(code>=8234&&code<=8238)return!0;if(code>=8294&&code<=8297)return!0}return!1}function validateDirectory(directory){if(!directory||directory.trim()==="")throw Error("Invalid directory: empty");if(containsPathTraversal(directory))throw Error("Invalid directory: path traversal detected");if(containsControlChars(directory))throw Error("Invalid directory: control characters detected");if(directory.startsWith("/")||directory.startsWith("\\"))throw Error("Invalid directory: absolute path");if(/^[A-Za-z]:[/\\]/.test(directory))throw Error("Invalid directory: Windows absolute path")}function validateSymlinkBoundary(targetPath,rootPath){let realTarget;try{realTarget=_internals30.realpathSync(targetPath)}catch{realTarget=path55.resolve(targetPath)}let realRoot;try{realRoot=_internals30.realpathSync(rootPath)}catch{realRoot=path55.resolve(rootPath)}let normalizedTarget=path55.normalize(realTarget),normalizedRoot=path55.normalize(realRoot);if(!normalizedTarget.startsWith(normalizedRoot+path55.sep)&&normalizedTarget!==normalizedRoot)throw Error(`Symlink resolution escaped boundary: ${realTarget} is not within ${realRoot}`)}function isCanonicalPathWithinRoot(targetPath,rootPath){let canonicalRoot;try{canonicalRoot=fs28.realpathSync(rootPath)}catch{canonicalRoot=path55.normalize(rootPath)}let probe2=path55.normalize(targetPath);for(let i=0;i<4096;i++)try{let canonicalProbe=fs28.realpathSync(probe2),relative15=path55.relative(canonicalRoot,canonicalProbe);return!relative15.startsWith("..")&&!path55.isAbsolute(relative15)}catch{let parent=path55.dirname(probe2);if(parent===probe2)return!1;probe2=parent}return!1}function validateTargetWithinRoot(filePath,root){if(!filePath||filePath.trim()==="")return"Empty path";if(path55.isAbsolute(filePath)||/^[A-Za-z]:[/\\]/.test(filePath))return`Absolute path rejected: ${filePath}`;if(containsPathTraversal(filePath))return`Path traversal detected: ${filePath}`;if(containsControlChars(filePath))return`Control characters detected in path: ${filePath}`;let resolved=path55.resolve(root,filePath),relative15=path55.relative(root,resolved);if(relative15.startsWith("..")||path55.isAbsolute(relative15))return`Path escapes root: ${filePath}`;if(!isCanonicalPathWithinRoot(resolved,root))return`Path escapes root via symlink/junction: ${filePath}`;return null}var _internals30;var init_path_security=__esm(()=>{_internals30={realpathSync:fs28.realpathSync,containsPathTraversal,containsControlChars,validateDirectory,validateSymlinkBoundary,isCanonicalPathWithinRoot,validateTargetWithinRoot}});import*as fs29 from"node:fs";import*as path56 from"node:path";function extractFilename(code,language,index){let lines=code.trim().split(`
|
|
693
693
|
`),ext=EXT_MAP[language.toLowerCase()]??".txt",firstLine=lines[0]?.trim()??"",filenameMatch=firstLine.match(/^[#/]+\s*filename[:\s]+(\S+\.\w+)/i);if(filenameMatch?.[1])return filenameMatch[1];let bareMatch=firstLine.match(/^[#/]+\s*(\w+\.\w+)\s*$/);if(bareMatch?.[1])return bareMatch[1];for(let line of lines.slice(0,5)){let defMatch=line.match(/^(?:def\s+|class\s+)(\w+)/);if(defMatch?.[1]&&!defMatch[1].startsWith("_"))return`${defMatch[1]}${ext}`;let psMatch=line.match(/^function\s+([\w-]+)/i);if(psMatch?.[1])return`${psMatch[1]}${ext}`}return`output_${index+1}${ext}`}function lstatIfPresent(filePath){try{return fs29.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}function reservationKey(filename){return path56.normalize(filename).toLowerCase()}function planExtractCodeBlocks(args2,directory){let{content,output_dir:outputDir,prefix}=args2;if(!content)return{status:"noop",reason:"content-required"};let matches=[...content.matchAll(/```(\w*)\n([\s\S]*?)```/g)];if(matches.length===0)return{status:"noop",reason:"no-code-blocks"};if(matches.length>MAX_EXTRACTED_FILES)return{status:"invalid",reason:`Too many code blocks (${matches.length}; maximum ${MAX_EXTRACTED_FILES})`};let targetDir=directory;if(outputDir!==void 0&&outputDir.trim()!==""){let reason=validateTargetWithinRoot(outputDir,directory);if(reason)return{status:"invalid",reason:`output_dir rejected — ${reason}`};targetDir=path56.resolve(directory,outputDir)}let reserved=new Set,files=[];for(let index=0;index<matches.length;index++){let language=matches[index]?.[1]??"",code=matches[index]?.[2]??"",filename=extractFilename(code,language,index);if(prefix)filename=`${prefix}_${filename}`;if(filename.includes("/")||filename.includes("\\"))return{status:"invalid",reason:`Rejected unsafe filename (must be a bare name): ${filename}`};let requestedPath=path56.join(targetDir,filename);if(lstatIfPresent(requestedPath)?.isSymbolicLink())return{status:"invalid",reason:`Rejected write through symlink: ${requestedPath}`};let base=path56.basename(filename,path56.extname(filename)),ext=path56.extname(filename),candidate=filename,counter=1;while(reserved.has(reservationKey(candidate))||lstatIfPresent(path56.join(targetDir,candidate))!==null){if(counter>MAX_COLLISION_ATTEMPTS)return{status:"invalid",reason:`Too many filename collisions for ${filename}`};candidate=`${base}_${counter}${ext}`,counter++}let absolutePath=path56.join(targetDir,candidate),relativePath=path56.relative(directory,absolutePath)||candidate,reason=validateTargetWithinRoot(relativePath,directory);if(reason)return{status:"invalid",reason:`Rejected write outside workspace: ${absolutePath} — ${reason}`};reserved.add(reservationKey(candidate)),files.push({filename:candidate,absolutePath,relativePath,code:code.trim()})}return{status:"ready",targetDir,files}}function getOrPlanExtractCodeBlocks(args2,directory){if(typeof args2==="object"&&args2!==null){let cached2=cachedPlans.get(args2);if(cached2?.directory===directory)return cached2.plan;let plan=planExtractCodeBlocks(args2,directory);return cachedPlans.set(args2,{directory,plan}),plan}return planExtractCodeBlocks(args2,directory)}function consumeExtractCodeBlocksPlan(args2,directory){let plan=getOrPlanExtractCodeBlocks(args2,directory);if(typeof args2==="object"&&args2!==null)cachedPlans.delete(args2);return plan}var EXT_MAP,MAX_EXTRACTED_FILES=256,MAX_COLLISION_ATTEMPTS=1e4,cachedPlans;var init_file_extractor_planner=__esm(()=>{init_path_security();EXT_MAP={python:".py",py:".py",powershell:".ps1",ps1:".ps1",pwsh:".ps1",javascript:".js",js:".js",typescript:".ts",ts:".ts",bash:".sh",sh:".sh",json:".json",yaml:".yaml",yml:".yaml",xml:".xml",html:".html",css:".css",sql:".sql",pester:".Tests.ps1",test:".Tests.ps1","":".txt"},cachedPlans=new WeakMap});import{Buffer as Buffer3}from"node:buffer";function unverifiable(reason){return{status:"unverifiable",reason}}function dedupe(paths){return[...new Set(paths)]}function genericResolver(args2){let paths=[],observedTargetField=!1;for(let key of SCALAR_PATH_KEYS){if(!(key in args2))continue;observedTargetField=!0;let value=args2[key];if(typeof value!=="string"||value.trim()===""||containsControlCharacter(value))return unverifiable(`Malformed ${key} target`);paths.push(value)}for(let key of ARRAY_PATH_KEYS){if(!(key in args2))continue;observedTargetField=!0;let value=args2[key];if(!Array.isArray(value)||value.some((item)=>typeof item!=="string"||item.trim()===""||containsControlCharacter(item)))return unverifiable(`Malformed ${key} targets`);paths.push(...value)}if(!observedTargetField||paths.length===0)return unverifiable("No write target was provided");return{status:"resolved",paths:dedupe(paths)}}function normalizeComparisonPath(filePath){return filePath.replace(/\\/g,"/").replace(/^\.\//,"")}function containsControlCharacter(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function parseTarget(raw,stripGitPrefix){let value=raw.replace(/\r$/,"").split("\t",1)[0]?.trim()??"";if(!value)return{error:"Empty patch target"};if(value==="/dev/null")return{};if(value.startsWith('"')||value.startsWith("'")||value.endsWith('"')||value.endsWith("'"))return{error:`Quoted patch path is unsupported: ${value}`};if(stripGitPrefix&&/\s/.test(value))return{error:`Ambiguous whitespace in diff path: ${value}`};if(stripGitPrefix&&(value.startsWith("a/")||value.startsWith("b/")))value=value.slice(2);if(!value||containsControlCharacter(value))return{error:"Malformed patch target"};return{path:value}}function parsePatchPayload(payload){let paths=[],operations=new Map,add=(raw,operation,stripGitPrefix=!1)=>{let parsed=parseTarget(raw,stripGitPrefix);if(parsed.error)return parsed.error;if(!parsed.path)return null;paths.push(parsed.path);let key=normalizeComparisonPath(parsed.path),existing=operations.get(key)??new Set;return existing.add(operation),operations.set(key,existing),null},lines=payload.split(`
|
|
694
694
|
`),beginIndices=[],endIndices=[],nativeOperationIndices=[];for(let index=0;index<lines.length;index++){let line=lines[index]??"",trimmed=line.trim();if(trimmed==="*** Begin Patch")beginIndices.push(index);if(trimmed==="*** End Patch")endIndices.push(index);if(/^\*\*\* (?:Update|Add|Delete) File:/i.test(line)||/^\*\*\* Move (?:to|from):/i.test(line))nativeOperationIndices.push(index)}if(beginIndices.length>0||endIndices.length>0||nativeOperationIndices.length>0){if(beginIndices.length===0)return"Native patch is missing *** Begin Patch";if(endIndices.length===0)return"Native patch is missing *** End Patch";if(beginIndices.length!==1||endIndices.length!==1)return"Native patch framing must contain exactly one begin and end marker";let beginIndex=beginIndices[0]??-1,endIndex=endIndices[0]??-1;if(beginIndex>=endIndex)return"Native patch has invalid begin/end marker ordering";if(nativeOperationIndices.some((index)=>index<=beginIndex||index>=endIndex))return"Native patch contains an operation outside begin/end markers";for(let index=beginIndex+1;index<endIndex;index++){let line=lines[index]??"",match=line.match(/^\*\*\* (Update|Add|Delete) File:\s*(.*)$/);if(match){let error49=add(match[2]??"",(match[1]??"").toLowerCase());if(error49)return error49;continue}let move=line.match(/^\*\*\* Move (?:to|from):\s*(.*)$/i);if(move){let error49=add(move[1]??"","move");if(error49)return error49}}}else for(let line of lines){let git=line.match(/^diff --git\s+(.+)$/);if(git){let remainder=git[1]?.trim()??"";if(remainder.startsWith('"')||remainder.startsWith("'"))return"Quoted diff --git paths are unsupported";let parts=remainder.split(/\s+/);if(parts.length!==2)return"Malformed diff --git header";for(let part of parts){let error49=add(part,"diff",!0);if(error49)return error49}continue}let unified=line.match(/^(---|\+\+\+)\s+(.+)$/);if(unified){let error49=add(unified[2]??"","diff",!0);if(error49)return error49;continue}let rename7=line.match(/^rename (from|to)\s+(.+)$/);if(rename7){let error49=add(rename7[2]??"","rename");if(error49)return error49}}if(paths.length===0)return"Patch contains no recognizable write targets";for(let[filePath,fileOperations]of operations)if(fileOperations.has("add")&&fileOperations.has("delete"))return`Contradictory add/delete operations for ${filePath}`;return{paths:dedupe(paths),operations}}function patchResolver(args2,_context,toolName){let payloadGroups=[],aggregateBytes=0;for(let field of PATCH_PAYLOAD_KEYS){if(!(field in args2))continue;let value=args2[field];if(typeof value!=="string")return unverifiable(`Malformed ${field} payload`);payloadGroups.push({field,payloads:[value]})}if("cmd"in args2){let cmd=args2.cmd;if(typeof cmd==="string")payloadGroups.push({field:"cmd",payloads:[cmd]});else if(Array.isArray(cmd)&&cmd.every((item)=>typeof item==="string")){let payloads=cmd.filter((item,index)=>{if(index===0&&/(?:^|[/\\])(?:apply_patch|patch)(?:\.exe)?$/i.test(item))return!1;return!(item.startsWith("-")&&!item.includes(`
|
|
695
695
|
`)&&!item.includes("*** Begin Patch"))});payloadGroups.push({field:"cmd",payloads})}else return unverifiable("Malformed cmd payload")}if(payloadGroups.length===0)return unverifiable("No patch payload was provided");let resolvedGroups=[];for(let group of payloadGroups){if(group.payloads.length===0)return unverifiable(`Empty ${group.field} payload`);let groupPaths=[];for(let payload of group.payloads){let bytes=Buffer3.byteLength(payload,"utf8");if(bytes>MAX_PATCH_FIELD_BYTES)return unverifiable(`Patch payload exceeds 1 MB (${group.field} field)`);if(aggregateBytes+=bytes,aggregateBytes>MAX_PATCH_AGGREGATE_BYTES)return unverifiable("Aggregate patch payload exceeds size limit");let parsed=parsePatchPayload(payload);if(typeof parsed==="string")return unverifiable(`${group.field}: ${parsed}`);groupPaths.push(...parsed.paths)}resolvedGroups.push({field:group.field,paths:dedupe(groupPaths)})}let canonical=(paths2)=>paths2.map(normalizeComparisonPath).sort().join(`
|