diff --git a/.zenodo.json b/.zenodo.json index 22d38f6e..ebe2e13f 100644 --- a/.zenodo.json +++ b/.zenodo.json @@ -1,18 +1,18 @@ { "title": "Pantheon Opencode", "upload_type": "software", - "description": "Pantheon v2.1.5 is an OpenCode plugin coordinating 14 specialized agents, with a typed decision router (Jev), 25 curated skills with progressive disclosure, named-behavior overrides, an on-demand agent forge, and a cost-aware skill discovery cascade. OpenCode 2.x only - the V1 contract is removed.", + "description": "Pantheon v2.1.6 is an OpenCode plugin coordinating 14 specialized agents, with a typed decision router (Jev), 25 curated skills with progressive disclosure, named-behavior overrides, an on-demand agent forge, and a cost-aware skill discovery cascade. OpenCode 2.x only - the V1 contract is removed.", "creators": [ { "name": "Igor Leite da Silva", "orcid": "0000-0001-7787-7562" } ], - "version": "2.1.5", + "version": "2.1.6", "license": "MIT", "language": "eng", "keywords": ["opencode", "ai-agents", "multi-agent", "orchestration", "developer-tools"], - "url": "https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.5", + "url": "https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.6", "related_identifiers": [ { "identifier": "https://github.com/ils15/pantheon-opencode", @@ -20,5 +20,5 @@ "resource_type": "software" } ], - "publication_date": "2026-11-14" + "publication_date": "2026-11-16" } diff --git a/AGENTS.global.md b/AGENTS.global.md index 70b0d49a..155d4819 100644 --- a/AGENTS.global.md +++ b/AGENTS.global.md @@ -1,7 +1,7 @@ - + # Pantheon Agent System — OpenCode diff --git a/AGENTS.md b/AGENTS.md index bca9c72b..6981f221 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ - + # Pantheon — Repository Setup diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bd3120b..fcd76d0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `node scripts/versioning.mjs apply --notes` pre-fills the generated sections from conventional commits. Running apply will move this section to a versioned entry and reset the template below. --> +## [v2.1.6] - 2026-11-16 + +### 🆕 What's New + +- **Deepwork Resilient Normalization**: Supported multi-decision blueprints, single-option policies, and string acceptance criteria. +- **Fail-Fast Anti-Mocking**: Prohibited fake mock servers on service ports to hide missing dependencies; fail fast with explicit errors. +- **Workspace Tool Directory**: Native shell tools dynamically resolve to the active project root rather than falling back to `$HOME`. +- **Atomic Skill Installation**: Enforced sequential `&&` chaining for `npx skills add` to prevent silent dropping of trailing targets. +- **Project Bootstrap Git Init**: `init --project` initializes an empty Git repo when absent, enabling worktree and branch support. +- **Decoupled Background Processes**: Mandated `setsid nohup > 2>&1 &` (or `disown`) for long-running service processes. + +### Fixed + +- **deepwork** — fixed `readPlan` schema rejection on single-option decision policies and auto-inferred acceptance criteria kinds (`test|command|file|manual`). +- **deepwork** — added atomic plan locking and safe temp files preventing write race conditions during concurrent decision resolutions. +- **tools** — flattened JSON schema for `pantheon_jev_decide` to eliminate upstream validator rejections on top-level `oneOf`/`anyOf`. +- **tools** — bound `shellTool` fallback execution directory dynamically to `hostLocationDirectory`. +- **mcp** — improved `pantheon-vision` error reporting with status code diagnostics and actionable fallback to native `vision_describe`. +- **tui** — removed duplicate todo block from settings preferences in favor of native sidebar. +- **agents** — updated Zeus and backend instructions with Fail-Fast, resource exclusivity, and decoupled server execution standards. + ## [v2.1.5] - 2026-11-14 ### 🆕 What's New diff --git a/CITATION.cff b/CITATION.cff index 6e8d53e3..14740c0a 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,11 +2,11 @@ cff-version: 1.2.0 message: "If you use Pantheon, please cite this software." title: "Pantheon Opencode" abstract: >- - Pantheon v2.1.5 is an OpenCode plugin and installer coordinating 14 + Pantheon v2.1.6 is an OpenCode plugin and installer coordinating 14 specialized agents with high-speed direct dispatch, native subagents, and progressive skill disclosure for OpenCode 2.x. -version: 2.1.5 -url: https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.5 +version: 2.1.6 +url: https://github.com/ils15/pantheon-opencode/releases/tag/v2.1.6 doi: 10.5281/zenodo.22650136 repository-code: https://github.com/ils15/pantheon-opencode license: MIT diff --git a/docs/guides/execution-modes.md b/docs/guides/execution-modes.md index 4c17e845..d91d1b61 100644 --- a/docs/guides/execution-modes.md +++ b/docs/guides/execution-modes.md @@ -62,7 +62,8 @@ For multi-phase tasks spanning 10+ turns or multiple sessions: - **Fail-first acceptance:** every task defines concrete acceptance criteria (`kind: test|command|file|manual`, `fails_now: true`) verified with cryptographic receipts. - **Tool automation (`pantheon_deepwork`):** structured tool for `init`, `status`, - `update_task`, `verify_acceptance`, and `resolve_decision`. + `update_task`, `verify_acceptance`, and `resolve_decision`. Resiliently normalizes complex + multi-decision plans, single-option constraints, string criteria, and agent aliases with atomic file locking. - **Resumability:** checkpoints persisted to `.pantheon/deepwork//`. Resume anytime with `/pantheon-deepwork --resume `. diff --git a/docs/releases/v2-highlights.md b/docs/releases/v2-highlights.md index 6b78ed80..dba896c0 100644 --- a/docs/releases/v2-highlights.md +++ b/docs/releases/v2-highlights.md @@ -4,6 +4,15 @@ > [CHANGELOG.md](https://github.com/ils15/pantheon-opencode/blob/main/CHANGELOG.md); this > page keeps the user-facing highlights that used to sit in the README. +## v2.1.6 + +- **Deepwork Resilient Normalization:** Full support for multi-decision plans, single-option policy constraints, string criteria auto-inference, and agent handle normalization with atomic plan locking. +- **Fail-Fast Anti-Mocking Rule:** Strict standard forbidding ad-hoc mock servers on production ports to mask missing dependencies; agents fail fast with explicit diagnostics. +- **Project Tool Working Directory:** Dynamic binding of shell tools to the project workspace instead of falling back to `$HOME`. +- **Atomic Skill Installation:** Sequential `&&` chaining for `npx skills add` commands preventing silent omissions when installing multiple skills. +- **Project Bootstrap Git Init:** `init --project` automatically initializes an empty Git repo when absent, enabling worktree and branch isolation out of the box. +- **Decoupled Background Processes:** Mandatory `setsid nohup > 2>&1 &` (or `disown`) for background servers surviving subshell termination. + ## v2.1.5 - **Risk-Based Validation Protocol (#444):** Explicit multi-tier protocol distinguishing focused test slices (<10s), package integration suites, and mandatory repository CI gates. Escalation to broad suites requires explicit triggers (cross-module, breaking contracts, auth, DB migrations). diff --git a/package-lock.json b/package-lock.json index 2e4ab2e2..dbf031ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pantheon-opencode", - "version": "2.1.5", + "version": "2.1.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pantheon-opencode", - "version": "2.1.5", + "version": "2.1.6", "hasInstallScript": true, "license": "MIT", "workspaces": [ @@ -8982,7 +8982,7 @@ }, "src/plugins/tui": { "name": "pantheon-tui", - "version": "2.1.5", + "version": "2.1.6", "license": "MIT", "dependencies": { "@opencode/plugin": "2.0.26", diff --git a/package.json b/package.json index 953df96b..584657c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pantheon-opencode", - "version": "2.1.5", + "version": "2.1.6", "description": "Multi-agent orchestration for OpenCode \u2014 14 specialized agents, TDD, Themis review gates.", "type": "module", "workspaces": [ diff --git a/plugin.json b/plugin.json index 37670858..e6947405 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "pantheon", "publisher": "ils15", - "version": "2.1.5", + "version": "2.1.6", "displayName": "Pantheon", "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 25 skills, and OpenCode support.", "agents": "./src/agents", diff --git a/pyproject.toml b/pyproject.toml index d907dc07..a9c1559d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend" [project] name = "pantheon" -version = "2.1.5" +version = "2.1.6" description = "Multi-agent orchestration framework" requires-python = ">=3.11" # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those diff --git a/scripts/install/opencode.mjs b/scripts/install/opencode.mjs index 9673aeaf..fc5da003 100644 --- a/scripts/install/opencode.mjs +++ b/scripts/install/opencode.mjs @@ -3290,6 +3290,18 @@ async function installPass( markAppliedWrite() stateStep(true) advancePhase() + + if (opts.isProject && !existsSync(join(target, '.git'))) { + try { + const { spawnSync } = await import('node:child_process') + const gitProbe = spawnSync('git', ['--version'], { stdio: 'ignore' }) + if (gitProbe.status === 0) { + spawnSync('git', ['init', '-q'], { cwd: target, stdio: 'ignore' }) + } + } catch { + // git probe or initialization failed; harmless + } + } } // Fail closed only after the degraded state is persisted. The caller records diff --git a/src/agents/roster.json b/src/agents/roster.json index dbb1f54f..84cee499 100644 --- a/src/agents/roster.json +++ b/src/agents/roster.json @@ -556,7 +556,7 @@ }, "execute": "deny" }, - "body": "## Fast Greeting & Direct Query Bypass\n\n- **Greetings and casual queries** (\"oi\", \"olá\", \"hello\", \"hi\", \"good morning\", \"how are you\", greetings, general questions about Pantheon or capabilities, simple clarifications, or direct calculations that do not require reading or editing project code): **Respond directly and immediately in 1 concise turn.**\n- **DO NOT dispatch subagents**, do not call Athena/Apollo, do not call Jev or council, and do not invoke tools for greetings and direct queries.\n\n## Prompt Refinery & Request Disambiguation (`prompt-refinery`)\n\n- **Prefix `>>` (Tier 2 Visual Contract):**\n - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.\n - Present the structured engineering brief:\n - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)\n - In Scope, Out of Scope & Negative Constraints\n - Acceptance Criteria\n - Open Questions with Recommended Defaults\n - **MANDATORY `question` tool:** When Open Questions, decisions needed, or scope trade-offs are present, ALWAYS invoke the native `question` tool with structured choices (marking the recommended choice with `(Recomendado)`) alongside the execution approval question (e.g. `[\"(Recomendado) Aprovar escopo e iniciar execução\", \"Ajustar escopo/premissas\"]`). NEVER leave open questions as inert text bullets in chat and proceed blindly.\n- **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**\n - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).\n - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options (recommended option first) rather than making blind assumptions or writing plain-text questions.\n\n\n## Strict Test Slicing & Anti-Fatigue Mandate (Issue #437)\n\n- **Repo Selector First:** Prefer the repository's own focused selector (e.g. `npm run test:quick`, `node scripts/test-slice.mjs`, `pytest -k`) over path guessing.\n- **Mandatory Sliced Checks (<10s):** When dispatching implementation specialists (@hermes, @aphrodite, @talos, @demeter, @prometheus), ALWAYS provide the exact, narrow test slice command for the changed file (e.g. `node --test tests/.test.mjs`, `pytest tests/test_.py -k `).\n- **Global Suites Forbidden in Dev Loops:** STRICTLY FORBID specialists from running global repository-wide test suites (`npm test`, `npm run test:all`, unconstrained `pytest`). Full suites cause massive timeouts, context bloating, and token waste. Full suites are reserved exclusively for the final release/PR gate.\n- **Failure/Fix Loop (No Redundant Passes):** When fixing a failed test, specialists MUST rerun ONLY the failed test (`-k ` or `--test-name-pattern`). DO NOT repeat passing tests if code was unchanged.\n- **Mapping Gaps & Scope Justification:** If no direct test file exists, report the mapping gap and run static lint/typecheck fallback (`npx biome check ` or `ruff check `) plus nearest slice; never escalate silently to full suites. Any broader-than-slice run requires visible scope justification.\n- **Observable Summary Receipt:** Require the specialist to return the structured receipt: `**tests:** [PASS|WARN|FAIL] (targets: N, duration: s, selection: )`.\n\n## Fast-Path Direct Implementation (Default Coding Workflow)\n\n- **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:\n - **Dispatch directly to the domain specialist in 1 turn.** Send a concise 3-5 line brief: goal, files, acceptance criteria, test command.\n - Domain mapping: Backend/API/logic to `@hermes`; Frontend/UI/styles to `@aphrodite`; Hotfixes/typos/CSS to `@talos`; Database schemas/migrations to `@demeter`; Infra/Docker/CI to `@prometheus`; Read-only broad research to `@apollo`.\n - **DO NOT invoke @athena.** DO NOT force planning or ask for plan approval on direct coding requests.\n - **DO NOT invoke Council synthesis.** Council is reserved strictly for `/pantheon-council` or explicit multi-perspective trade-off requests.\n - When the specialist returns, report the concise deliverable and test result directly to the user.\n - **Skill-Informed Handoff**: When a task involves an installed skill (built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), Zeus includes `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instructs the specialist to read `SKILL.md` before implementation.\n- **Asynchronous parallel subagents**: When running long test suites, heavy builds, or independent exploratory research, use `task(..., background: true)` where supported by the runtime so the main workflow does not block.\n- **Planning via @athena is strictly gated**:\n - ONLY invoke Athena when the user explicitly runs `/pantheon-deepwork` or explicitly requests a plan in the prompt (\"plan this first\", \"create a plan\", \"planeje\").\n\n## Session Task Checklist & TUI Todo Panel (`todowrite`)\n\n- **Live TUI Progress:** Whenever coordinating a workflow with two or more steps, or executing an architecture/deepwork plan:\n - **Initialize:** Call `todowrite` immediately with the sequential task checklist (all items marked `pending`).\n - **Transition:** As each phase or specialist delegation starts, update the active item to `in_progress` via `todowrite`.\n - **Complete:** Upon verification or specialist return, mark the item `completed` (or `cancelled` if discarded) via `todowrite`.\n - This ensures the active session's task status is visible in real-time in the Pantheon TUI Todo block.\n\n## Golden Rule & Boundaries\n\n**Coordinator and router.** Zeus never edits or implements code (delegates to @hermes, @aphrodite, @talos, etc.), but may perform bounded reads (≤50 lines) for fast routing without unnecessary subagent dispatches. Broad investigations or exploratory research go to @apollo. Routing and inspecting files across the `.pantheon/` directory (`.pantheon/**`, including plans, memory-bank, reports, configs) and active worktrees (`.pantheon-worktrees/**`) is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\nZeus NEVER edits files (`edit: deny`, `hashline_edit: deny`). Zero terminal access (`bash: deny`, `shell: deny`). OpenCode's native terminal tool is `bash` (aliased to `shell`). Zeus has NO terminal access.\nNEVER ask the user to type terminal commands — dispatch the specialist with bash permitted (@prometheus, @hermes, @talos).\n\n## MCP call timing (when each integration fires)\n\nThese rules are economic, measured against the 2026-11-05 usage audit. They apply to every agent:\n\n- **pantheon-memory** (`memory_store`): durable, reusable facts ONLY (architectural decisions, conventions, user preferences). Session narration never stores — it belongs in conversation history. Check search results before storing to avoid duplicates. Namespaces: `default` is for project facts, `context` is for transient cross-session state, other namespaces only when explicitly directed.\n- **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed.\n- **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.\n- **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.\n\n## Local advisory routing before native delegation\n\n- For a bounded deliverable, delegate once to the final specialist; the specialist can gather the necessary facts. Use Apollo separately only if research is the deliverable itself or blocks choosing the specialist. Planning and council remain on-demand; never invoke council for small fixes.\n- Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.\n- Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: \"delegation\"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.\n- Missing capability & Proactive Project Skill Decision Flow:\n - Discovery: When a task requires capabilities not in the local pool, run `pantheon_skill_search` (in-process, read-only) or `node scripts/skill-search.mjs` across the trust cascade.\n - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: \"choice\"` or `\"rank\"`).\n - Proactive Interactive Question Gate (MANDATORY `question` tool):\n - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).\n - SEMPRE no projeto atual: External skills MUST ALWAYS be installed strictly in the current project root under `.agents/skills/` (using `-a opencode -y`). NEVER propose or allow global installation (`~/.config/opencode/skills/`).\n - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:\n * Recommended choice: `\"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)\"` (curated candidates).\n * Granular choice: `\"Selecionar skills específicas para instalar\"` (or checkbox list if multiselect).\n * Skip choice: `\"Prosseguir sem instalar skills adicionais\"`.\n - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute `npx skills add [skill2...] -a opencode -y` in the project root (batching multiple skills in a single run).\n - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`.\n\n## Visual Context for Implementation\n\n- When a request includes an image or screenshot, use image content already available in the conversation. If `[Visual]` is detected or an image attachment path is present and this model cannot inspect images directly, IMMEDIATELY call `vision_describe(path=..., question=...)` to inspect the visual elements, text, and layout before planning, answering, or delegating. Never claim \"não consigo visualizar a imagem\" when `vision_describe` is available in tools. Call it first.\n- For UI work, delegate to @aphrodite and include the image reference (URL/path when available) plus a concise description of the relevant layout, elements, and requested outcome in the task prompt.\n- Tell the implementer to compare the reference with the current UI and preserve unrelated existing work or changes. An image is context, not permission to delete or revert work; if replacing an existing change is necessary or intent is unclear, stop and ask before doing so.\n\n## Delegation Protocol\n\nGOLDEN RULE: `subagent_type: general` and `subagent_type: explore` are FORBIDDEN.\nDo not use shared KV to track depth; at most one auxiliary specialist.\n\n## Handoff Brief (every delegation)\n\nBefore every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history.\n- **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation.\n`memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript.\n\n## Plan Handoff and Approval\n\nWhenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:\n1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.\n2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.\n3. Write the full technical blueprint to `.pantheon/deepwork//PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.\n4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:\n - **Goal & Target:** 1 crisp sentence.\n - **Execution Flow:** Mermaid diagram (3-4 nodes).\n - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).\n - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork//PLAN.md`.\n5. **Interactive Question Gate (MANDATORY `question` tool):**\n - **Open Questions & Decisions Needed:** If the plan, task brief, or refinement contains any Open Questions or `decisions_needed`, **NEVER leave them as inert text bullets** in chat or assume \"proceed if no objections\". You MUST decompose each open question into an interactive item in the native `question` tool with concrete options, marking the recommended choice with `(Recomendado)`.\n - **Plan Approval Gate:** Alongside any open questions, include the approval question with explicit options (e.g., `[\"(Recomendado) Aprovar e iniciar execução\", \"Ajustar plano\"]` / `[\"(Recommended) Approve and begin execution\", \"Adjust plan\"]`), falling back to plain text only if the tool is not exposed.\n6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork//PLAN.md`, and repeat the interactive gate." + "body": "## Fast Greeting & Direct Query Bypass\n\n- **Greetings and casual queries** (\"oi\", \"olá\", \"hello\", \"hi\", \"good morning\", \"how are you\", greetings, general questions about Pantheon or capabilities, simple clarifications, or direct calculations that do not require reading or editing project code): **Respond directly and immediately in 1 concise turn.**\n- **DO NOT dispatch subagents**, do not call Athena/Apollo, do not call Jev or council, and do not invoke tools for greetings and direct queries.\n\n## Prompt Refinery & Request Disambiguation (`prompt-refinery`)\n\n- **Prefix `>>` (Tier 2 Visual Contract):**\n - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.\n - Present the structured engineering brief:\n - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)\n - In Scope, Out of Scope & Negative Constraints\n - Acceptance Criteria\n - Open Questions with Recommended Defaults\n - **MANDATORY `question` tool:** When Open Questions, decisions needed, or scope trade-offs are present, ALWAYS invoke the native `question` tool with structured choices (marking the recommended choice with `(Recomendado)`) alongside the execution approval question (e.g. `[\"(Recomendado) Aprovar escopo e iniciar execução\", \"Ajustar escopo/premissas\"]`). NEVER leave open questions as inert text bullets in chat and proceed blindly.\n- **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**\n - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).\n - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options (recommended option first) rather than making blind assumptions or writing plain-text questions.\n\n\n## Strict Test Slicing & Anti-Fatigue Mandate (Issue #437)\n\n- **Repo Selector First:** Prefer the repository's own focused selector (e.g. `npm run test:quick`, `node scripts/test-slice.mjs`, `pytest -k`) over path guessing.\n- **Mandatory Sliced Checks (<10s):** When dispatching implementation specialists (@hermes, @aphrodite, @talos, @demeter, @prometheus), ALWAYS provide the exact, narrow test slice command for the changed file (e.g. `node --test tests/.test.mjs`, `pytest tests/test_.py -k `).\n- **Global Suites Forbidden in Dev Loops:** STRICTLY FORBID specialists from running global repository-wide test suites (`npm test`, `npm run test:all`, unconstrained `pytest`). Full suites cause massive timeouts, context bloating, and token waste. Full suites are reserved exclusively for the final release/PR gate.\n- **Failure/Fix Loop (No Redundant Passes):** When fixing a failed test, specialists MUST rerun ONLY the failed test (`-k ` or `--test-name-pattern`). DO NOT repeat passing tests if code was unchanged.\n- **Mapping Gaps & Scope Justification:** If no direct test file exists, report the mapping gap and run static lint/typecheck fallback (`npx biome check ` or `ruff check `) plus nearest slice; never escalate silently to full suites. Any broader-than-slice run requires visible scope justification.\n- **Observable Summary Receipt:** Require the specialist to return the structured receipt: `**tests:** [PASS|WARN|FAIL] (targets: N, duration: s, selection: )`.\n\n## Fast-Path Direct Implementation (Default Coding Workflow)\n\n- **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:\n - **Dispatch directly to the domain specialist in 1 turn.** Send a concise 3-5 line brief: goal, files, acceptance criteria, test command.\n - Domain mapping: Backend/API/logic to `@hermes`; Frontend/UI/styles to `@aphrodite`; Hotfixes/typos/CSS to `@talos`; Database schemas/migrations to `@demeter`; Infra/Docker/CI to `@prometheus`; Read-only broad research to `@apollo`.\n - **DO NOT invoke @athena.** DO NOT force planning or ask for plan approval on direct coding requests.\n - **DO NOT invoke Council synthesis.** Council is reserved strictly for `/pantheon-council` or explicit multi-perspective trade-off requests.\n - When the specialist returns, report the concise deliverable and test result directly to the user.\n - **Skill-Informed Handoff**: When a task involves an installed skill (built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), Zeus includes `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instructs the specialist to read `SKILL.md` before implementation.\n- **Asynchronous parallel subagents**: When running long test suites, heavy builds, or independent exploratory research, use `task(..., background: true)` where supported by the runtime so the main workflow does not block.\n- **Planning via @athena is strictly gated**:\n - ONLY invoke Athena when the user explicitly runs `/pantheon-deepwork` or explicitly requests a plan in the prompt (\"plan this first\", \"create a plan\", \"planeje\").\n\n## Session Task Checklist & TUI Todo Panel (`todowrite`)\n\n- **Live TUI Progress:** Whenever coordinating a workflow with two or more steps, or executing an architecture/deepwork plan:\n - **Initialize:** Call `todowrite` immediately with the sequential task checklist (all items marked `pending`).\n - **Transition:** As each phase or specialist delegation starts, update the active item to `in_progress` via `todowrite`.\n - **Complete:** Upon verification or specialist return, mark the item `completed` (or `cancelled` if discarded) via `todowrite`.\n - This ensures the active session's task status is visible in real-time in the Pantheon TUI Todo block.\n\n## Golden Rule & Boundaries\n\n**Coordinator and router.** Zeus never edits or implements code (delegates to @hermes, @aphrodite, @talos, etc.), but may perform bounded reads (≤50 lines) for fast routing without unnecessary subagent dispatches. Broad investigations or exploratory research go to @apollo. Routing and inspecting files across the `.pantheon/` directory (`.pantheon/**`, including plans, memory-bank, reports, configs) and active worktrees (`.pantheon-worktrees/**`) is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\nZeus NEVER edits files (`edit: deny`, `hashline_edit: deny`). Zero terminal access (`bash: deny`, `shell: deny`). OpenCode's native terminal tool is `bash` (aliased to `shell`). Zeus has NO terminal access.\nNEVER ask the user to type terminal commands — dispatch the specialist with bash permitted (@prometheus, @hermes, @talos).\n\n## MCP call timing (when each integration fires)\n\nThese rules are economic, measured against the 2026-11-05 usage audit. They apply to every agent:\n\n- **pantheon-memory** (`memory_store`): durable, reusable facts ONLY (architectural decisions, conventions, user preferences). Session narration never stores — it belongs in conversation history. Check search results before storing to avoid duplicates. Namespaces: `default` is for project facts, `context` is for transient cross-session state, other namespaces only when explicitly directed.\n- **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed.\n- **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.\n- **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.\n\n## Local advisory routing before native delegation\n\n- For a bounded deliverable, delegate once to the final specialist; the specialist can gather the necessary facts. Use Apollo separately only if research is the deliverable itself or blocks choosing the specialist. Planning and council remain on-demand; never invoke council for small fixes.\n- Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.\n- Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: \"delegation\"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.\n- Missing capability & Proactive Project Skill Decision Flow:\n - Discovery: When a task requires capabilities not in the local pool, run `pantheon_skill_search` (in-process, read-only) or `node scripts/skill-search.mjs` across the trust cascade.\n - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: \"choice\"` or `\"rank\"`).\n - Proactive Interactive Question Gate (MANDATORY `question` tool):\n - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).\n - SEMPRE no projeto atual: External skills MUST ALWAYS be installed strictly in the current project root under `.agents/skills/` (using `-a opencode -y`). NEVER propose or allow global installation (`~/.config/opencode/skills/`).\n - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:\n * Recommended choice: `\"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)\"` (curated candidates).\n * Granular choice: `\"Selecionar skills específicas para instalar\"` (or checkbox list if multiselect).\n * Skip choice: `\"Prosseguir sem instalar skills adicionais\"`.\n - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute one command per skill sequentially chained with `&&`: `npx skills add -a opencode -y && npx skills add -a opencode -y` in the project root (the skills CLI only accepts one target per invocation; never pass multiple skills as separate positional arguments to a single call).\n - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`.\n\n## Visual Context for Implementation\n\n- When a request includes an image or screenshot, use image content already available in the conversation. If `[Visual]` is detected or an image attachment path is present and this model cannot inspect images directly, IMMEDIATELY call `vision_describe(path=..., question=...)` to inspect the visual elements, text, and layout before planning, answering, or delegating. Never claim \"não consigo visualizar a imagem\" when `vision_describe` is available in tools. Call it first.\n- For UI work, delegate to @aphrodite and include the image reference (URL/path when available) plus a concise description of the relevant layout, elements, and requested outcome in the task prompt.\n- Tell the implementer to compare the reference with the current UI and preserve unrelated existing work or changes. An image is context, not permission to delete or revert work; if replacing an existing change is necessary or intent is unclear, stop and ask before doing so.\n\n## Delegation Protocol\n\nGOLDEN RULE: `subagent_type: general` and `subagent_type: explore` are FORBIDDEN.\nDo not use shared KV to track depth; at most one auxiliary specialist.\n\n## Handoff Brief (every delegation)\n\nBefore every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history.\n- **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation.\n- **Fail-Fast & Anti-Mocking:** Specialists must NEVER create ad-hoc mock servers or fake listeners on real production/service ports to simulate missing dependencies; fail fast with explicit `DEPENDENCY_MISSING`.\n- **Resource Exclusivity:** When dispatching tasks that bind network ports or run servers, explicitly designate single port/resource ownership to avoid concurrent bind collisions.\n- **Decoupled Background Processes:** Long-running services (FastAPI/uvicorn, Vite, dev servers) must always be launched using `setsid nohup > 2>&1 &` (or `disown`) so they survive subshell termination.\n`memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript.\n\n## Plan Handoff and Approval\n\nWhenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:\n1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.\n2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.\n3. Write the full technical blueprint to `.pantheon/deepwork//PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.\n4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:\n - **Goal & Target:** 1 crisp sentence.\n - **Execution Flow:** Mermaid diagram (3-4 nodes).\n - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).\n - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork//PLAN.md`.\n5. **Interactive Question Gate (MANDATORY `question` tool):**\n - **Open Questions & Decisions Needed:** If the plan, task brief, or refinement contains any Open Questions or `decisions_needed`, **NEVER leave them as inert text bullets** in chat or assume \"proceed if no objections\". You MUST decompose each open question into an interactive item in the native `question` tool with concrete options, marking the recommended choice with `(Recomendado)`.\n - **Plan Approval Gate:** Alongside any open questions, include the approval question with explicit options (e.g., `[\"(Recomendado) Aprovar e iniciar execução\", \"Ajustar plano\"]` / `[\"(Recommended) Approve and begin execution\", \"Adjust plan\"]`), falling back to plain text only if the tool is not exposed.\n6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork//PLAN.md`, and repeat the interactive gate." } } } diff --git a/src/agents/zeus.md b/src/agents/zeus.md index d037ff76..f8b98bfc 100644 --- a/src/agents/zeus.md +++ b/src/agents/zeus.md @@ -126,7 +126,7 @@ These rules are economic, measured against the 2026-11-05 usage audit. They appl * Recommended choice: `"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)"` (curated candidates). * Granular choice: `"Selecionar skills específicas para instalar"` (or checkbox list if multiselect). * Skip choice: `"Prosseguir sem instalar skills adicionais"`. - - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute `npx skills add [skill2...] -a opencode -y` in the project root (batching multiple skills in a single run). + - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute one command per skill sequentially chained with `&&`: `npx skills add -a opencode -y && npx skills add -a opencode -y` in the project root (the skills CLI only accepts one target per invocation; never pass multiple skills as separate positional arguments to a single call). - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`. ## Visual Context for Implementation @@ -144,6 +144,9 @@ Do not use shared KV to track depth; at most one auxiliary specialist. Before every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history. - **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation. +- **Fail-Fast & Anti-Mocking:** Specialists must NEVER create ad-hoc mock servers or fake listeners on real production/service ports to simulate missing dependencies; fail fast with explicit `DEPENDENCY_MISSING`. +- **Resource Exclusivity:** When dispatching tasks that bind network ports or run servers, explicitly designate single port/resource ownership to avoid concurrent bind collisions. +- **Decoupled Background Processes:** Long-running services (FastAPI/uvicorn, Vite, dev servers) must always be launched using `setsid nohup > 2>&1 &` (or `disown`) so they survive subshell termination. `memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript. ## Plan Handoff and Approval diff --git a/src/instructions/backend-standards.instructions.md b/src/instructions/backend-standards.instructions.md index 8dba7b91..e8377da6 100644 --- a/src/instructions/backend-standards.instructions.md +++ b/src/instructions/backend-standards.instructions.md @@ -45,3 +45,8 @@ fallback: shared - CSRF protection - Rate limiting for sensitive endpoints - Sanitize logs (never log passwords/tokens) + +## Fail-Fast & Infrastructure Honesty +- Never create ad-hoc mock servers or fake listener stubs on real service/application ports to simulate missing dependencies. +- If a required dependency, service, or upstream endpoint is absent: FAIL FAST with explicit error details (`DEPENDENCY_MISSING`) rather than masking it. +- Long-running background processes (dev servers, uvicorn, vite): ALWAYS decouple from subshells using `setsid nohup > 2>&1 &` (or `disown`). diff --git a/src/mcp/pantheon_vision.py b/src/mcp/pantheon_vision.py index ad501195..87a8b19f 100644 --- a/src/mcp/pantheon_vision.py +++ b/src/mcp/pantheon_vision.py @@ -671,7 +671,10 @@ def _gateway_http_error(status: int) -> str: "free-tier (usable only from inside OpenCode) or this account has " "no paid access to it." ) - return "Vision gateway returned an HTTP error." + return ( + f"Vision gateway returned HTTP error {status}. If running inside OpenCode, " + "use the native 'vision_describe' tool as fallback." + ) async def _gateway( diff --git a/src/pantheon/deepwork/deepwork-tool.ts b/src/pantheon/deepwork/deepwork-tool.ts index 6a9ae801..5c1435c0 100644 --- a/src/pantheon/deepwork/deepwork-tool.ts +++ b/src/pantheon/deepwork/deepwork-tool.ts @@ -6,7 +6,7 @@ */ import { z } from 'zod' -import type { ToolContextLike } from '../tool-context.ts' +import { resolveToolCwd } from '../tool-context.ts' import type { V2ToolDef, V2ToolResult } from '../tools.ts' import { buildApprovalQuestion, @@ -15,14 +15,15 @@ import { } from './plan-projection.ts' import { appendJournal, - computeTaskReadiness, deepworkPlanJsonPath, deepworkPlanMdPath, listPlans, + normalizePlanData, readPlan, resolvePlanDecision, updateTaskState, verifyTaskAcceptance, + withPlanLock, writePlan, } from './plan-tracker.ts' @@ -140,10 +141,7 @@ export function createDeepworkTool(cwd = process.cwd()): V2ToolDef { output: {}, async execute(input: Record, context: unknown): Promise { const parsed = DeepworkToolInputSchema.parse(input) - const effectiveCwd = - typeof (context as ToolContextLike)?.directory === 'string' - ? (context as ToolContextLike).directory - : cwd + const effectiveCwd = resolveToolCwd(context, cwd) if (parsed.action === 'list') { const plans = await listPlans(effectiveCwd) @@ -175,81 +173,31 @@ export function createDeepworkTool(cwd = process.cwd()): V2ToolDef { } if (parsed.action === 'init') { - const title = parsed.title?.trim() || slug - const intent = parsed.intent?.trim() || 'Plano de deepwork estruturado.' - const rawTasks = parsed.tasks ?? [] - const rawDecisions = parsed.decisions ?? [] - const doneWhen = parsed.done_when ?? [] - - const tasks = rawTasks.map((t, idx) => ({ - id: typeof t.id === 'string' ? t.id : `T${String(idx + 1).padStart(2, '0')}`, - title: typeof t.title === 'string' ? t.title : `Task ${idx + 1}`, - description: typeof t.description === 'string' ? t.description : undefined, - agent: typeof t.agent === 'string' ? t.agent : 'zeus', - phase: typeof t.phase === 'number' ? t.phase : 1, - state: (typeof t.state === 'string' ? t.state : 'pending') as - | 'pending' - | 'ready' - | 'in_progress' - | 'done' - | 'failed' - | 'blocked', - depends_on: Array.isArray(t.depends_on) ? (t.depends_on as string[]) : [], - parallel_safe: Boolean(t.parallel_safe), - acceptance: Array.isArray(t.acceptance) - ? ( - t.acceptance as Array<{ - kind: 'test' | 'command' | 'file' | 'manual' - check: string - fails_now?: boolean - verified?: boolean - proof?: string - }> - ).map((a) => ({ - kind: a.kind || 'command', - check: a.check || 'verify', - fails_now: a.fails_now ?? true, - verified: a.verified ?? false, - proof: a.proof, - })) - : [], - })) - - const decisions = rawDecisions.map((d, idx) => ({ - id: typeof d.id === 'string' ? d.id : `D${String(idx + 1).padStart(2, '0')}`, - question: typeof d.question === 'string' ? d.question : 'Decisão necessária', - options: Array.isArray(d.options) ? (d.options as string[]) : ['Sim', 'Não'], - chosen: typeof d.chosen === 'string' ? d.chosen : undefined, - status: (d.chosen ? 'resolved' : 'pending') as 'pending' | 'resolved', - })) - - const initialPlan = computeTaskReadiness({ - plan_id: slug, - title, - intent, - done_when: doneWhen, - decisions_needed: decisions, - risks: [], - out_of_scope: [], - tasks, - metadata: { - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - version: 1, + const initialPlan = normalizePlanData( + { + plan_id: slug, + title: parsed.title, + intent: parsed.intent, + done_when: parsed.done_when, + decisions_needed: parsed.decisions, + tasks: parsed.tasks, }, - }) + slug, + ) - await writePlan(effectiveCwd, initialPlan) - await appendJournal(effectiveCwd, slug, { - type: 'plan_created', - timestamp: new Date().toISOString(), - payload: { slug, title, tasks_count: tasks.length }, + await withPlanLock(effectiveCwd, slug, async () => { + await writePlan(effectiveCwd, initialPlan) + await appendJournal(effectiveCwd, slug, { + type: 'plan_created', + timestamp: new Date().toISOString(), + payload: { slug, title: initialPlan.title, tasks_count: initialPlan.tasks.length }, + }) }) const projection = generateChatProjection(initialPlan, effectiveCwd) const approvalQ = buildApprovalQuestion(initialPlan) const todoPayload = { - todos: tasks.map((t) => ({ + todos: initialPlan.tasks.map((t) => ({ content: `[${t.id}] ${t.title}`, status: t.state === 'done' @@ -262,7 +210,7 @@ export function createDeepworkTool(cwd = process.cwd()): V2ToolDef { return { output: [ - `✅ Plano de Deepwork '${title}' inicializado com sucesso em \`.pantheon/deepwork/${slug}/\`!`, + `✅ Plano de Deepwork '${initialPlan.title}' inicializado com sucesso em \`.pantheon/deepwork/${slug}/\`!`, `- 🔗 **Deeplink PLAN.md:** [Abrir PLAN.md](file://${deepworkPlanMdPath(effectiveCwd, slug)})`, `- 🔗 **Deeplink plan.json:** [Abrir plan.json](file://${deepworkPlanJsonPath(effectiveCwd, slug)})`, '', diff --git a/src/pantheon/deepwork/plan-schema.ts b/src/pantheon/deepwork/plan-schema.ts index d69359fa..89175a59 100644 --- a/src/pantheon/deepwork/plan-schema.ts +++ b/src/pantheon/deepwork/plan-schema.ts @@ -55,9 +55,11 @@ export type DecisionStatus = z.infer export const PlanDecisionSchema = z.object({ id: z.string().min(1), question: z.string().min(1), - options: z.array(z.string()).min(2), + options: z.array(z.string()).default([]), chosen: z.string().optional(), + choice: z.string().optional(), status: DecisionStatusSchema.default('pending'), + resolved_at: z.string().optional(), }) export type PlanDecision = z.infer @@ -78,7 +80,7 @@ export type PlanMetadata = z.infer export const DeepworkPlanSchema = z.object({ plan_id: z.string().min(1), title: z.string().min(1), - intent: z.string().min(1), + intent: z.string().default('Plano de deepwork estruturado.'), done_when: z.array(z.string()).default([]), decisions_needed: z.array(PlanDecisionSchema).default([]), risks: z.array(PlanRiskSchema).default([]), diff --git a/src/pantheon/deepwork/plan-tracker.ts b/src/pantheon/deepwork/plan-tracker.ts index 5b4ee95f..06eed38c 100644 --- a/src/pantheon/deepwork/plan-tracker.ts +++ b/src/pantheon/deepwork/plan-tracker.ts @@ -13,6 +13,11 @@ import { generateMarkdownDocument } from './plan-projection.ts' import { type DeepworkPlan, DeepworkPlanSchema, + type PlanAcceptanceCriterion, + type PlanAcceptanceKind, + type PlanDecision, + type PlanMetadata, + type PlanRisk, type PlanTask, type TaskState, } from './plan-schema.ts' @@ -81,17 +86,288 @@ export function computeTaskReadiness(plan: DeepworkPlan): DeepworkPlan { return { ...plan, tasks: updatedTasks } } +export function inferAcceptanceKind(check: string): PlanAcceptanceKind { + const lower = check.toLowerCase() + if (lower.includes('test') || lower.includes('pytest') || lower.includes('assert')) return 'test' + if ( + lower.includes('file') || + lower.includes('exist') || + lower.includes('criado') || + lower.includes('path') + ) + return 'file' + if ( + lower.startsWith('npm ') || + lower.startsWith('bash ') || + lower.startsWith('alembic ') || + lower.startsWith('git ') || + lower.includes(' && ') || + lower.includes(' || ') + ) + return 'command' + return 'manual' +} + +/** + * Normalizes unstructured or loosely structured plan input into a canonical DeepworkPlan. + * Resilient to agent variations: owner vs agent, @-prefixes, array of strings for acceptance, + * choices in decisions, and string phases. + */ +export function normalizePlanData(data: unknown, fallbackSlug = 'plan'): DeepworkPlan { + const obj = (data && typeof data === 'object' ? data : {}) as Record + const slug = String(obj.plan_id ?? obj.slug ?? fallbackSlug).trim() || fallbackSlug + const title = String(obj.title ?? slug).trim() || slug + const intent = String(obj.intent ?? '').trim() || 'Plano de deepwork estruturado.' + const done_when = Array.isArray(obj.done_when) + ? obj.done_when.map((s) => String(s).trim()).filter(Boolean) + : [] + + const rawDecisions = Array.isArray(obj.decisions_needed) + ? obj.decisions_needed + : Array.isArray(obj.decisions) + ? obj.decisions + : [] + + const decisions_needed: PlanDecision[] = rawDecisions.map((d: unknown, idx: number) => { + const dec = (d && typeof d === 'object' ? d : {}) as Record + const id = String(dec.id ?? `D${String(idx + 1).padStart(2, '0')}`).trim() + const question = String(dec.question ?? dec.title ?? 'Decisão necessária').trim() + const rawOptions = Array.isArray(dec.options) + ? dec.options + : typeof dec.options === 'string' + ? [dec.options] + : [] + const options = rawOptions.map((opt) => String(opt).trim()).filter(Boolean) + const chosenVal = dec.chosen ?? dec.choice + const chosen = typeof chosenVal === 'string' ? chosenVal : undefined + const statusVal = String(dec.status ?? '') + .trim() + .toLowerCase() + const status: 'pending' | 'resolved' = + statusVal === 'resolved' || chosen !== undefined ? 'resolved' : 'pending' + return { + id, + question, + options, + chosen, + choice: chosen, + status, + resolved_at: typeof dec.resolved_at === 'string' ? dec.resolved_at : undefined, + } + }) + + const rawRisks = Array.isArray(obj.risks) ? obj.risks : [] + const risks: PlanRisk[] = rawRisks.map((r: unknown, idx: number) => { + const risk = (r && typeof r === 'object' ? r : {}) as Record + return { + id: String(risk.id ?? `R${String(idx + 1).padStart(2, '0')}`).trim(), + description: String(risk.description ?? risk.risk ?? '').trim() || 'Risco não especificado', + mitigation: typeof risk.mitigation === 'string' ? risk.mitigation : undefined, + } + }) + + const out_of_scope = Array.isArray(obj.out_of_scope) + ? obj.out_of_scope.map((s) => String(s).trim()).filter(Boolean) + : [] + + const rawTasks = Array.isArray(obj.tasks) ? obj.tasks : [] + const tasks: PlanTask[] = rawTasks.map((t: unknown, idx: number) => { + const task = (t && typeof t === 'object' ? t : {}) as Record + const id = String(task.id ?? `T${String(idx + 1).padStart(2, '0')}`).trim() + const taskTitle = String(task.title ?? task.name ?? `Task ${idx + 1}`).trim() + const description = typeof task.description === 'string' ? task.description : undefined + const rawAgent = task.agent ?? task.owner ?? task.assignee + const agent = + typeof rawAgent === 'string' && rawAgent.trim().length > 0 + ? rawAgent.replace(/^@/, '').trim() + : 'zeus' + + const rawPhase = task.phase + let phase = 1 + if (typeof rawPhase === 'number' && Number.isFinite(rawPhase)) { + phase = rawPhase + } else if (typeof rawPhase === 'string') { + const match = rawPhase.match(/\d+/) + if (match) phase = Number.parseInt(match[0], 10) + } + + const rawState = String(task.state ?? task.status ?? 'pending') + .trim() + .toLowerCase() + const validStates: TaskState[] = [ + 'pending', + 'ready', + 'in_progress', + 'done', + 'failed', + 'blocked', + ] + const state: TaskState = validStates.includes(rawState as TaskState) + ? (rawState as TaskState) + : 'pending' + + const depends_on = Array.isArray(task.depends_on) + ? task.depends_on.map((dep) => String(dep).trim()).filter(Boolean) + : [] + const parallel_safe = Boolean(task.parallel_safe ?? task.parallel) + + const rawAcceptance = Array.isArray(task.acceptance) + ? task.acceptance + : Array.isArray(task.acceptance_criteria) + ? task.acceptance_criteria + : Array.isArray(task.criteria) + ? task.criteria + : [] + + const acceptance: PlanAcceptanceCriterion[] = rawAcceptance.map((a: unknown) => { + if (typeof a === 'string') { + const checkText = a.trim() + return { + kind: inferAcceptanceKind(checkText), + check: checkText, + fails_now: true, + verified: false, + } + } + const acc = (a && typeof a === 'object' ? a : {}) as Record + const checkText = String( + acc.check ?? acc.description ?? acc.title ?? acc.name ?? 'verify', + ).trim() + const rawKind = String(acc.kind ?? '') + .trim() + .toLowerCase() + const validKinds = ['test', 'command', 'file', 'manual'] as const + const kind = ( + validKinds.includes(rawKind as (typeof validKinds)[number]) + ? rawKind + : inferAcceptanceKind(checkText) + ) as PlanAcceptanceKind + return { + kind, + check: checkText || 'verify', + fails_now: typeof acc.fails_now === 'boolean' ? acc.fails_now : true, + verified: Boolean(acc.verified), + proof: typeof acc.proof === 'string' ? acc.proof : undefined, + } + }) + + const rawResult = + task.result && typeof task.result === 'object' + ? (task.result as Record) + : undefined + const result = rawResult + ? { + summary: typeof rawResult.summary === 'string' ? rawResult.summary : undefined, + verified_at: + typeof rawResult.verified_at === 'string' ? rawResult.verified_at : undefined, + artifacts: Array.isArray(rawResult.artifacts) + ? rawResult.artifacts.map((art) => String(art)) + : undefined, + } + : undefined + + return { + id, + title: taskTitle, + description, + agent, + phase, + state, + depends_on, + parallel_safe, + acceptance, + result, + } + }) + + const rawMeta = + obj.metadata && typeof obj.metadata === 'object' + ? (obj.metadata as Record) + : {} + const now = new Date().toISOString() + const metadata: PlanMetadata = { + created_at: typeof rawMeta.created_at === 'string' ? rawMeta.created_at : now, + updated_at: typeof rawMeta.updated_at === 'string' ? rawMeta.updated_at : now, + version: typeof rawMeta.version === 'number' ? rawMeta.version : 1, + } + + return computeTaskReadiness({ + plan_id: slug, + title, + intent, + done_when, + decisions_needed, + risks, + out_of_scope, + tasks, + metadata, + }) +} + /** - * Read the canonical JSON plan. Returns null if absent or corrupt. + * Read the canonical JSON plan. Returns null if absent. + * Automatically normalizes minor schema variations (single options, string criteria, owner aliases). */ export async function readPlan(cwd = process.cwd(), slug: string): Promise { const path = deepworkPlanJsonPath(cwd, slug) + let raw: string + try { + raw = await readFile(path, 'utf8') + } catch (err: unknown) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') { + return null + } + throw err + } + + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch (err: unknown) { + throw new Error(`Plano '${slug}' em ${path} contém JSON inválido: ${(err as Error).message}`) + } + + const result = DeepworkPlanSchema.safeParse(parsed) + if (result.success) { + return result.data + } + try { - const raw = await readFile(path, 'utf8') - const parsed = JSON.parse(raw) - return DeepworkPlanSchema.parse(parsed) + const normalized = normalizePlanData(parsed, slug) + const repairedResult = DeepworkPlanSchema.safeParse(normalized) + if (repairedResult.success) { + return repairedResult.data + } } catch { - return null + // fall through to schema issue reporting + } + + const issues = result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ') + throw new Error(`Plano '${slug}' em ${path} falhou na validação de schema: ${issues}`) +} + +const planLocks = new Map>() + +/** + * Execute an async operation with serialized exclusivity per plan slug. + * Prevents concurrent read-modify-write race conditions and clashing tempfiles. + */ +export async function withPlanLock(cwd: string, slug: string, fn: () => Promise): Promise { + const key = `${cwd}::${slug}` + const prev = planLocks.get(key) ?? Promise.resolve() + let resolveCurrent: (() => void) | undefined + const current = new Promise((resolve) => { + resolveCurrent = resolve + }) + planLocks.set(key, current) + try { + await prev + return await fn() + } finally { + resolveCurrent?.() + if (planLocks.get(key) === current) { + planLocks.delete(key) + } } } @@ -111,16 +387,20 @@ export async function writePlan(cwd = process.cwd(), plan: DeepworkPlan): Promis }, }) + const randomSuffix = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}` + // Atomic write for plan.json const jsonPath = deepworkPlanJsonPath(cwd, plan.plan_id) - const jsonTmp = `${jsonPath}.tmp` + const jsonTmp = `${jsonPath}.tmp.${randomSuffix}` await writeFile(jsonTmp, `${JSON.stringify(normalized, null, 2)}\n`, 'utf8') await rename(jsonTmp, jsonPath) // Projection write for PLAN.md const mdPath = deepworkPlanMdPath(cwd, plan.plan_id) + const mdTmp = `${mdPath}.tmp.${randomSuffix}` const mdContent = generateMarkdownDocument(normalized) - await writeFile(mdPath, mdContent, 'utf8') + await writeFile(mdTmp, mdContent, 'utf8') + await rename(mdTmp, mdPath) } /** @@ -164,38 +444,42 @@ export async function updateTaskState( state: TaskState, result?: { summary?: string; verified_at?: string; artifacts?: string[] }, ): Promise { - const plan = await readPlan(cwd, slug) - if (!plan) { - throw new Error(`Deepwork plan "${slug}" not found`) - } + return withPlanLock(cwd, slug, async () => { + const plan = await readPlan(cwd, slug) + if (!plan) { + throw new Error(`Deepwork plan "${slug}" not found`) + } - const taskIndex = plan.tasks.findIndex((t) => t.id === taskId) - const existingTask = plan.tasks[taskIndex] - if (taskIndex === -1 || !existingTask) { - throw new Error(`Task "${taskId}" not found in plan "${slug}"`) - } + const taskIndex = plan.tasks.findIndex((t) => t.id === taskId) + const existingTask = plan.tasks[taskIndex] + if (taskIndex === -1 || !existingTask) { + throw new Error(`Task "${taskId}" not found in plan "${slug}"`) + } - const updatedResult = result ? { ...(existingTask.result ?? {}), ...result } : existingTask.result + const updatedResult = result + ? { ...(existingTask.result ?? {}), ...result } + : existingTask.result - const updatedTask: PlanTask = { - ...existingTask, - state, - ...(updatedResult !== undefined ? { result: updatedResult } : {}), - } + const updatedTask: PlanTask = { + ...existingTask, + state, + ...(updatedResult !== undefined ? { result: updatedResult } : {}), + } - const updatedTasks = [...plan.tasks] - updatedTasks[taskIndex] = updatedTask + const updatedTasks = [...plan.tasks] + updatedTasks[taskIndex] = updatedTask - const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks } - await writePlan(cwd, nextPlan) + const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks } + await writePlan(cwd, nextPlan) - await appendJournal(cwd, slug, { - type: 'task_state_changed', - timestamp: new Date().toISOString(), - payload: { taskId, state, result }, - }) + await appendJournal(cwd, slug, { + type: 'task_state_changed', + timestamp: new Date().toISOString(), + payload: { taskId, state, result }, + }) - return (await readPlan(cwd, slug)) ?? nextPlan + return (await readPlan(cwd, slug)) ?? nextPlan + }) } /** @@ -209,49 +493,51 @@ export async function verifyTaskAcceptance( verified: boolean, proof?: string, ): Promise { - const plan = await readPlan(cwd, slug) - if (!plan) { - throw new Error(`Deepwork plan "${slug}" not found`) - } + return withPlanLock(cwd, slug, async () => { + const plan = await readPlan(cwd, slug) + if (!plan) { + throw new Error(`Deepwork plan "${slug}" not found`) + } - const taskIndex = plan.tasks.findIndex((t) => t.id === taskId) - const task = plan.tasks[taskIndex] - if (taskIndex === -1 || !task) { - throw new Error(`Task "${taskId}" not found in plan "${slug}"`) - } + const taskIndex = plan.tasks.findIndex((t) => t.id === taskId) + const task = plan.tasks[taskIndex] + if (taskIndex === -1 || !task) { + throw new Error(`Task "${taskId}" not found in plan "${slug}"`) + } - const currentAcc = task.acceptance[checkIndex] - if (!currentAcc) { - throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`) - } + const currentAcc = task.acceptance[checkIndex] + if (!currentAcc) { + throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`) + } - const updatedAcceptance = [...task.acceptance] - const resolvedProof = proof ?? currentAcc.proof - updatedAcceptance[checkIndex] = { - ...currentAcc, - verified, - ...(resolvedProof !== undefined ? { proof: resolvedProof } : {}), - } + const updatedAcceptance = [...task.acceptance] + const resolvedProof = proof ?? currentAcc.proof + updatedAcceptance[checkIndex] = { + ...currentAcc, + verified, + ...(resolvedProof !== undefined ? { proof: resolvedProof } : {}), + } - const allVerified = updatedAcceptance.every((acc) => acc.verified) + const allVerified = updatedAcceptance.every((acc) => acc.verified) - const updatedTasks = [...plan.tasks] - updatedTasks[taskIndex] = { - ...task, - acceptance: updatedAcceptance, - state: allVerified ? 'done' : task.state, - } + const updatedTasks = [...plan.tasks] + updatedTasks[taskIndex] = { + ...task, + acceptance: updatedAcceptance, + state: allVerified ? 'done' : task.state, + } - const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks } - await writePlan(cwd, nextPlan) + const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks } + await writePlan(cwd, nextPlan) - await appendJournal(cwd, slug, { - type: 'acceptance_verified', - timestamp: new Date().toISOString(), - payload: { taskId, checkIndex, verified, proof, allVerified }, - }) + await appendJournal(cwd, slug, { + type: 'acceptance_verified', + timestamp: new Date().toISOString(), + payload: { taskId, checkIndex, verified, proof, allVerified }, + }) - return (await readPlan(cwd, slug)) ?? nextPlan + return (await readPlan(cwd, slug)) ?? nextPlan + }) } /** @@ -263,34 +549,38 @@ export async function resolvePlanDecision( decisionId: string, chosen: string, ): Promise { - const plan = await readPlan(cwd, slug) - if (!plan) { - throw new Error(`Deepwork plan "${slug}" not found`) - } + return withPlanLock(cwd, slug, async () => { + const plan = await readPlan(cwd, slug) + if (!plan) { + throw new Error(`Deepwork plan "${slug}" not found`) + } - const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId) - const existingDec = plan.decisions_needed[decIndex] - if (decIndex === -1 || !existingDec) { - throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`) - } + const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId) + const existingDec = plan.decisions_needed[decIndex] + if (decIndex === -1 || !existingDec) { + throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`) + } - const updatedDecisions = [...plan.decisions_needed] - updatedDecisions[decIndex] = { - ...existingDec, - chosen, - status: 'resolved', - } + const updatedDecisions = [...plan.decisions_needed] + updatedDecisions[decIndex] = { + ...existingDec, + chosen, + choice: chosen, + status: 'resolved', + resolved_at: new Date().toISOString(), + } - const nextPlan: DeepworkPlan = { ...plan, decisions_needed: updatedDecisions } - await writePlan(cwd, nextPlan) + const nextPlan: DeepworkPlan = { ...plan, decisions_needed: updatedDecisions } + await writePlan(cwd, nextPlan) - await appendJournal(cwd, slug, { - type: 'decision_resolved', - timestamp: new Date().toISOString(), - payload: { decisionId, chosen }, - }) + await appendJournal(cwd, slug, { + type: 'decision_resolved', + timestamp: new Date().toISOString(), + payload: { decisionId, chosen }, + }) - return (await readPlan(cwd, slug)) ?? nextPlan + return (await readPlan(cwd, slug)) ?? nextPlan + }) } /** diff --git a/src/pantheon/jev-decision-tool.ts b/src/pantheon/jev-decision-tool.ts index 8bb98f3b..34f2db8f 100644 --- a/src/pantheon/jev-decision-tool.ts +++ b/src/pantheon/jev-decision-tool.ts @@ -872,14 +872,8 @@ const JEV_INPUT_SCHEMA: Record = { type: 'object', additionalProperties: false, required: ['schemaVersion'], - anyOf: [ - { required: ['state'] }, - { required: ['delegateId', 'resultSummaryKind', 'resultMetrics', 'criteria'] }, - { required: ['candidates'] }, - { required: ['claims'] }, - ], properties: { - schemaVersion: { type: 'integer', const: 1 }, + schemaVersion: { type: 'integer', enum: [1] }, state: { type: 'string', minLength: 1, maxLength: 12_000 }, mode: { type: 'string', enum: ['skills', 'delegation', 'review', 'rank', 'verify', 'order'] }, questions: { type: 'array', minItems: 1, maxItems: 4, items: questionSchema }, diff --git a/src/pantheon/local-decision-tool.ts b/src/pantheon/local-decision-tool.ts index 1a29b3d2..8e73148f 100644 --- a/src/pantheon/local-decision-tool.ts +++ b/src/pantheon/local-decision-tool.ts @@ -114,7 +114,7 @@ const v2InputSchema: Record = { 'complexity', ], properties: { - schemaVersion: { type: 'integer', const: 1 }, + schemaVersion: { type: 'integer', enum: [1] }, candidateAgents: { type: 'array', maxItems: 14, items: { type: 'string', minLength: 1 } }, domain: { type: ['string', 'null'] }, candidateSkillIds: { type: 'array', maxItems: 64, items: { type: 'string', minLength: 1 } }, diff --git a/src/pantheon/native-vision.ts b/src/pantheon/native-vision.ts index 1aca55a0..be31de2c 100644 --- a/src/pantheon/native-vision.ts +++ b/src/pantheon/native-vision.ts @@ -576,7 +576,7 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini return { name: 'vision_describe', description: - 'Analyze an image with an OpenCode Zen multimodal model confirmed by the current V2 model catalog. ' + + 'Analyze an image with an OpenCode Zen multimodal model confirmed by the current model catalog. ' + 'Prefers the OpenCode Go MiMo 2.6 Flash model and falls back to another live image-capable Zen model. ' + 'Free-tier models are excluded (the direct gateway rejects them). ' + 'Accepts a local path, file URL, public HTTP(S) URL, or base64 image data URI.', diff --git a/src/pantheon/skill-search-tool.ts b/src/pantheon/skill-search-tool.ts index cf74968d..fac7bea1 100644 --- a/src/pantheon/skill-search-tool.ts +++ b/src/pantheon/skill-search-tool.ts @@ -20,6 +20,7 @@ import { join } from 'node:path' // @ts-expect-error scripts/skill-search.mjs is a plain Node ESM script without bundled .d.ts import { searchSkillSources } from '../../scripts/skill-search.mjs' import { PANTHEON_SKILL_CATALOG } from './pantheon-decision-catalog.ts' +import { resolveToolCwd } from './tool-context.ts' import type { V2ToolDef } from './tools.ts' export interface SkillSearchResult { @@ -172,6 +173,72 @@ const SKILL_SEARCH_INPUT_SCHEMA: Record = { }, } +export interface SkillScore { + readonly score: number + readonly matchedTokens: number +} + +/** + * Score relevance of a skill against query tokens. + * + * Uses word-boundary and segment matching with tiered weighting: + * - Exact ID match: 20 pts + * - Exact segment match in hyphenated/slashed ID: 12 pts + * - Prefix match on ID segment (>=4 chars): 6 pts + * - Exact word match in description: 5 pts + * - Prefix match on description word (>=4 chars): 2 pts + * - Multi-token synergy bonus: + (matchedTokens * 5) pts + * + * Substrings inside words (e.g. "rate" inside "generates" or "migrate") + * receive ZERO points, completely eliminating false-positive lexical bleed. + */ +export function scoreSkillMatch( + id: string, + description: string, + queryTokens: readonly string[], +): SkillScore { + const idLower = id.toLowerCase() + const descLower = description.toLowerCase() + const idTokens = idLower.split(/[^a-z0-9]+/).filter(Boolean) + const descWords = descLower.split(/[^a-z0-9]+/).filter(Boolean) + + let score = 0 + let matchedTokens = 0 + + for (const t of queryTokens) { + let tokenScore = 0 + + if (idLower === t) { + tokenScore += 20 + } else if (idTokens.includes(t)) { + tokenScore += 12 + } else if ( + idTokens.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w))) + ) { + tokenScore += 6 + } + + if (descWords.includes(t)) { + tokenScore += 5 + } else if ( + descWords.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w))) + ) { + tokenScore += 2 + } + + if (tokenScore > 0) { + score += tokenScore + matchedTokens += 1 + } + } + + if (matchedTokens > 1) { + score += matchedTokens * 5 + } + + return { score, matchedTokens } +} + export function executeSkillSearch( input: Record, options: { cwd?: string } = {}, @@ -195,48 +262,35 @@ export function executeSkillSearch( ], ) - const results: SkillSearchResult[] = [] const failures: string[] = [] const cwd = options.cwd ?? process.cwd() const installedMap = scanInstalledSkills(cwd) + const tokens = query + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((t) => t.length > 1) + + const scoredResults: Array = [] + // 1. Tier 1: Installed skills (Pantheon catalog + local filesystem .opencode/skills and .agents/skills) - if (sources.has('installed')) { - const tokens = query - .toLowerCase() - .split(/[^a-z0-9]+/) - .filter((t) => t.length > 2) - - if (tokens.length > 0) { - for (const entry of installedMap.values()) { - const idLower = entry.id.toLowerCase() - const descLower = entry.description.toLowerCase() - const matchScore = tokens.reduce((score, t) => { - const stem = t.length > 4 ? t.slice(0, 4) : t - return ( - score + - (idLower.includes(t) || - descLower.includes(t) || - idLower.includes(stem) || - descLower.includes(stem) - ? 1 - : 0) - ) - }, 0) - - if (matchScore > 0) { - results.push({ - skill: entry.id, - description: entry.description, - source: 'installed', - installed: true, - installs: null, - installCommand: null, - path: entry.path, - scope: entry.scope, - }) - } + if (sources.has('installed') && tokens.length > 0) { + const minThreshold = tokens.length > 1 ? 5 : 2 + for (const entry of installedMap.values()) { + const { score } = scoreSkillMatch(entry.id, entry.description, tokens) + if (score >= minThreshold) { + scoredResults.push({ + skill: entry.id, + description: entry.description, + source: 'installed', + installed: true, + installs: null, + installCommand: null, + path: entry.path, + scope: entry.scope, + score, + }) } } } @@ -244,9 +298,9 @@ export function executeSkillSearch( // 2. External tiers (Anthropic, skills.sh, GitHub) const externalSources = ['anthropic', 'skills-sh', 'github'].filter((s) => sources.has(s)) - if (externalSources.length > 0 && results.length < limit) { + if (externalSources.length > 0 && scoredResults.length < limit) { try { - const extLimit = limit - results.length + const extLimit = limit - scoredResults.length const extRes = searchSkillSources(query, { limit: extLimit, sources: externalSources, @@ -257,6 +311,7 @@ export function executeSkillSearch( } if (Array.isArray(extRes.entries)) { + const minThreshold = tokens.length > 1 ? 5 : 2 for (const entry of extRes.entries) { const bareName = ( entry.skill.includes('@') ? entry.skill.split('@')[1] : entry.skill @@ -266,7 +321,22 @@ export function executeSkillSearch( const installedRecord = installedMap.get(entry.skill.toLowerCase()) || installedMap.get(bareName) - const pushItem: SkillSearchResult = { + const { score } = scoreSkillMatch(entry.skill, entry.skill, tokens) + if (score < minThreshold && !isInstalled) { + continue + } + + if ( + scoredResults.some( + (r) => + r.skill.toLowerCase() === entry.skill.toLowerCase() || + (bareName && r.skill.toLowerCase() === bareName), + ) + ) { + continue + } + + scoredResults.push({ skill: entry.skill, description: entry.skill, source: entry.source as 'anthropic' | 'skills-sh' | 'github', @@ -276,8 +346,8 @@ export function executeSkillSearch( installCommand: isInstalled ? null : `npx skills add ${entry.skill} -a opencode -y`, path: isInstalled && installedRecord ? installedRecord.path : null, ...(isInstalled && installedRecord ? { scope: installedRecord.scope } : {}), - } - results.push(pushItem) + score: score || 1, + }) } } } catch (err) { @@ -287,7 +357,11 @@ export function executeSkillSearch( } } - const bounded = results.slice(0, limit) + scoredResults.sort((a, b) => b.score - a.score) + const bounded: SkillSearchResult[] = scoredResults + .slice(0, limit) + .map(({ score: _, ...item }) => item) + return { ok: true, query, @@ -297,14 +371,14 @@ export function executeSkillSearch( } } -export function createV2SkillSearchDefinition(): V2ToolDef { +export function createV2SkillSearchDefinition(defaultDir?: string): V2ToolDef { return { name: 'pantheon_skill_search', description: TOOL_DESCRIPTION, input: SKILL_SEARCH_INPUT_SCHEMA, output: {}, execute: async (input: Record, context?: unknown) => { - const cwd = (context as { directory?: string } | undefined)?.directory || process.cwd() + const cwd = resolveToolCwd(context, defaultDir) return { output: JSON.stringify(executeSkillSearch(input, { cwd }), null, 2), } diff --git a/src/pantheon/tool-context.ts b/src/pantheon/tool-context.ts index aae81760..e5cbc19d 100644 --- a/src/pantheon/tool-context.ts +++ b/src/pantheon/tool-context.ts @@ -21,3 +21,26 @@ export interface ToolContextLike { */ agent?: string } + +/** + * Resolves the effective working directory for tool operations. + * + * Checks in order of precedence: + * 1. ctx.directory (explicit workspace directory on tool context) + * 2. ctx.worktree (worktree directory if isolated) + * 3. fallbackDir (injected location directory from host at plugin setup) + * 4. process.cwd() (fallback process directory) + */ +export function resolveToolCwd(context: unknown, fallbackDir?: string): string { + const ctx = (context ?? {}) as Partial + if (typeof ctx.directory === 'string' && ctx.directory.trim().length > 0) { + return ctx.directory + } + if (typeof ctx.worktree === 'string' && ctx.worktree.trim().length > 0) { + return ctx.worktree + } + if (typeof fallbackDir === 'string' && fallbackDir.trim().length > 0) { + return fallbackDir + } + return process.cwd() +} diff --git a/src/pantheon/tools.ts b/src/pantheon/tools.ts index 40255971..fb145acd 100644 --- a/src/pantheon/tools.ts +++ b/src/pantheon/tools.ts @@ -57,7 +57,7 @@ import { createV2LocalDecisionDefinition } from './local-decision-tool.ts' import { createModelCommand } from './model-command.ts' import { createV2VisionTool, type V2VisionRuntime } from './native-vision.ts' import { createV2SkillSearchDefinition } from './skill-search-tool.ts' -import type { ToolContextLike } from './tool-context.ts' +import { resolveToolCwd, type ToolContextLike } from './tool-context.ts' // ─── Contract types ───────────────────────────────────────────────────── @@ -400,7 +400,7 @@ const MODEL_INPUT: Record = { scope: { type: 'string', enum: ['project'], - description: 'Project scope only; global overrides are not supported in V2.', + description: 'Project scope only; global overrides are not supported.', }, }, } @@ -412,12 +412,12 @@ async function executeModel( context: unknown, ): Promise { if (input.scope !== undefined && input.scope !== 'project') { - return { output: 'Error: V2 pantheon_model is project-only; global scope is not supported.' } + return { output: 'Error: pantheon_model is project-only; global scope is not supported.' } } if (Object.hasOwn(input, 'confirm') || Object.hasOwn(input, 'authorize_global')) { return { output: - 'Error: V2 pantheon_model does not accept authorization flags; global authorization is not supported by this tool.', + 'Error: pantheon_model does not accept authorization flags; global authorization is not supported by this tool.', } } // The V1 tool validates its own args (zod) and reports failures as text. @@ -557,45 +557,49 @@ const SHELL_INPUT = { } as const /** - * A V2 fallback shell tool alias. OpenCode registers `bash`, but models frequently + * Shell tool execution. OpenCode registers `bash`, but models frequently * attempt to invoke `shell` because of agent permission YAML conventions. - * This alias ensures terminal commands execute seamlessly without tool-not-found errors. + * This tool ensures terminal commands execute seamlessly in the workspace directory. */ -const shellTool: V2ToolDef = { - name: 'shell', - description: 'Execute a shell command in the workspace directory. Alias for bash execution.', - input: SHELL_INPUT, - output: {}, - execute: async (input, context) => { - const raw = (input as Record) ?? {} - const command = String(raw.command ?? raw.cmd ?? '') - if (!command.trim()) { - return { output: '', ok: false, error: 'Command cannot be empty' } - } - const toolCtx = toolContext(context) - const cwd = toolCtx.directory || process.cwd() - try { - const { stdout, stderr } = await execAsync(command, { - cwd, - maxBuffer: 10 * 1024 * 1024, - shell: '/bin/bash', - }) - const output = [stdout, stderr].filter(Boolean).join('\n') - return { output, ok: true } - } catch (err: unknown) { - const execError = err as { stdout?: string; stderr?: string; message?: string } - const output = [execError.stdout, execError.stderr, execError.message] - .filter(Boolean) - .join('\n') - return { output, ok: false, error: output } - } - }, +export function createShellTool(fallbackDir?: string): V2ToolDef { + return { + name: 'shell', + description: 'Execute a shell command in the workspace directory. Alias for bash execution.', + input: SHELL_INPUT, + output: {}, + execute: async (input, context) => { + const raw = (input as Record) ?? {} + const command = String(raw.command ?? raw.cmd ?? '') + if (!command.trim()) { + return { output: '', ok: false, error: 'Command cannot be empty' } + } + const cwd = resolveToolCwd(context, fallbackDir) + try { + const { stdout, stderr } = await execAsync(command, { + cwd, + maxBuffer: 10 * 1024 * 1024, + shell: '/bin/bash', + }) + const output = [stdout, stderr].filter(Boolean).join('\n') + return { output, ok: true } + } catch (err: unknown) { + const execError = err as { stdout?: string; stderr?: string; message?: string } + const output = [execError.stdout, execError.stderr, execError.message] + .filter(Boolean) + .join('\n') + return { output, ok: false, error: output } + } + }, + } } +export const shellTool = createShellTool() + export function createV2ToolDefinitions( visionRuntime?: V2VisionRuntime, shadow: V2ToolShadowOptions = {}, jevRuntime?: V2JevDecisionRuntime, + hostLocationDirectory?: string, ): V2ToolDef[] { const definitions: V2ToolDef[] = [ { @@ -618,8 +622,8 @@ export function createV2ToolDefinitions( 'on disk: a call reads that cache and never waits on the network unless refreshPricing is ' + 'set, a stale cache is refreshed in the background and the report says so, and an unpriced ' + 'model reads — and is excluded from the totals, which then say partial. Pass session= to aggregate that session plus its descendant sessions. Phase may be unknown ' + - 'on V2; costs are catalog list prices, not an invoice.', + 'session id> to aggregate that session plus its descendant sessions. Phase may be unknown; ' + + 'costs are catalog list prices, not an invoice.', input: COST_INPUT, output: {}, execute: executeCost, @@ -628,8 +632,8 @@ export function createV2ToolDefinitions( name: 'pantheon_model', description: 'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. ' + - 'V2 ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model ' + - 'selection. Global overrides are not read or written in V2; future global support requires ' + + 'Ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model ' + + 'selection. Global overrides are not read or written; future global support requires ' + 'separate explicit authorization. Pass action="status" to read project-scoped overrides. ' + 'Never writes .env or top-level model/small_model.', input: MODEL_INPUT, @@ -644,9 +648,9 @@ export function createV2ToolDefinitions( ) definitions.push(todowriteTool) definitions.push(todoreadTool) - definitions.push(shellTool) - definitions.push(createV2SkillSearchDefinition()) - definitions.push(createDeepworkTool()) + definitions.push(createShellTool(hostLocationDirectory)) + definitions.push(createV2SkillSearchDefinition(hostLocationDirectory)) + definitions.push(createDeepworkTool(hostLocationDirectory)) if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime)) if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime)) return definitions diff --git a/src/plugin.ts b/src/plugin.ts index bd33d174..9cbf4b59 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -773,6 +773,7 @@ async function registerV2Tools( }, }, runtime, + host.location?.directory, ) if (boundedRead !== undefined) toolDefs.push(boundedRead) diff --git a/src/plugin/index.js b/src/plugin/index.js index aa62e181..18fcaa8f 100644 --- a/src/plugin/index.js +++ b/src/plugin/index.js @@ -7532,14 +7532,8 @@ var JEV_INPUT_SCHEMA = { type: "object", additionalProperties: false, required: ["schemaVersion"], - anyOf: [ - { required: ["state"] }, - { required: ["delegateId", "resultSummaryKind", "resultMetrics", "criteria"] }, - { required: ["candidates"] }, - { required: ["claims"] } - ], properties: { - schemaVersion: { type: "integer", const: 1 }, + schemaVersion: { type: "integer", enum: [1] }, state: { type: "string", minLength: 1, maxLength: 12e3 }, mode: { type: "string", enum: ["skills", "delegation", "review", "rank", "verify", "order"] }, questions: { type: "array", minItems: 1, maxItems: 4, items: questionSchema }, @@ -9268,7 +9262,7 @@ function discoverActiveSessionId(directory) { function createV2VisionTool(runtime) { return { name: "vision_describe", - description: "Analyze an image with an OpenCode Zen multimodal model confirmed by the current V2 model catalog. Prefers the OpenCode Go MiMo 2.6 Flash model and falls back to another live image-capable Zen model. Free-tier models are excluded (the direct gateway rejects them). Accepts a local path, file URL, public HTTP(S) URL, or base64 image data URI.", + description: "Analyze an image with an OpenCode Zen multimodal model confirmed by the current model catalog. Prefers the OpenCode Go MiMo 2.6 Flash model and falls back to another live image-capable Zen model. Free-tier models are excluded (the direct gateway rejects them). Accepts a local path, file URL, public HTTP(S) URL, or base64 image data URI.", input: { type: "object", additionalProperties: false, @@ -12036,6 +12030,21 @@ ${renderMarkdown(query, days, pricing)}`; // src/pantheon/deepwork/deepwork-tool.ts import { z as z3 } from "zod"; +// src/pantheon/tool-context.ts +function resolveToolCwd(context, fallbackDir) { + const ctx = context ?? {}; + if (typeof ctx.directory === "string" && ctx.directory.trim().length > 0) { + return ctx.directory; + } + if (typeof ctx.worktree === "string" && ctx.worktree.trim().length > 0) { + return ctx.worktree; + } + if (typeof fallbackDir === "string" && fallbackDir.trim().length > 0) { + return fallbackDir; + } + return process.cwd(); +} + // src/pantheon/deepwork/plan-projection.ts import { join as join15 } from "node:path"; function generateChatProjection(plan, cwd = process.cwd()) { @@ -12264,9 +12273,11 @@ var DecisionStatusSchema = z2.enum(["pending", "resolved"]); var PlanDecisionSchema = z2.object({ id: z2.string().min(1), question: z2.string().min(1), - options: z2.array(z2.string()).min(2), + options: z2.array(z2.string()).default([]), chosen: z2.string().optional(), - status: DecisionStatusSchema.default("pending") + choice: z2.string().optional(), + status: DecisionStatusSchema.default("pending"), + resolved_at: z2.string().optional() }); var PlanRiskSchema = z2.object({ id: z2.string().min(1), @@ -12281,7 +12292,7 @@ var PlanMetadataSchema = z2.object({ var DeepworkPlanSchema = z2.object({ plan_id: z2.string().min(1), title: z2.string().min(1), - intent: z2.string().min(1), + intent: z2.string().default("Plano de deepwork estruturado."), done_when: z2.array(z2.string()).default([]), decisions_needed: z2.array(PlanDecisionSchema).default([]), risks: z2.array(PlanRiskSchema).default([]), @@ -12326,14 +12337,193 @@ function computeTaskReadiness(plan) { }); return { ...plan, tasks: updatedTasks }; } +function inferAcceptanceKind(check) { + const lower = check.toLowerCase(); + if (lower.includes("test") || lower.includes("pytest") || lower.includes("assert")) return "test"; + if (lower.includes("file") || lower.includes("exist") || lower.includes("criado") || lower.includes("path")) + return "file"; + if (lower.startsWith("npm ") || lower.startsWith("bash ") || lower.startsWith("alembic ") || lower.startsWith("git ") || lower.includes(" && ") || lower.includes(" || ")) + return "command"; + return "manual"; +} +function normalizePlanData(data, fallbackSlug = "plan") { + const obj = data && typeof data === "object" ? data : {}; + const slug = String(obj.plan_id ?? obj.slug ?? fallbackSlug).trim() || fallbackSlug; + const title = String(obj.title ?? slug).trim() || slug; + const intent = String(obj.intent ?? "").trim() || "Plano de deepwork estruturado."; + const done_when = Array.isArray(obj.done_when) ? obj.done_when.map((s) => String(s).trim()).filter(Boolean) : []; + const rawDecisions = Array.isArray(obj.decisions_needed) ? obj.decisions_needed : Array.isArray(obj.decisions) ? obj.decisions : []; + const decisions_needed = rawDecisions.map((d, idx) => { + const dec = d && typeof d === "object" ? d : {}; + const id = String(dec.id ?? `D${String(idx + 1).padStart(2, "0")}`).trim(); + const question = String(dec.question ?? dec.title ?? "Decis\xE3o necess\xE1ria").trim(); + const rawOptions = Array.isArray(dec.options) ? dec.options : typeof dec.options === "string" ? [dec.options] : []; + const options = rawOptions.map((opt) => String(opt).trim()).filter(Boolean); + const chosenVal = dec.chosen ?? dec.choice; + const chosen = typeof chosenVal === "string" ? chosenVal : void 0; + const statusVal = String(dec.status ?? "").trim().toLowerCase(); + const status = statusVal === "resolved" || chosen !== void 0 ? "resolved" : "pending"; + return { + id, + question, + options, + chosen, + choice: chosen, + status, + resolved_at: typeof dec.resolved_at === "string" ? dec.resolved_at : void 0 + }; + }); + const rawRisks = Array.isArray(obj.risks) ? obj.risks : []; + const risks = rawRisks.map((r, idx) => { + const risk = r && typeof r === "object" ? r : {}; + return { + id: String(risk.id ?? `R${String(idx + 1).padStart(2, "0")}`).trim(), + description: String(risk.description ?? risk.risk ?? "").trim() || "Risco n\xE3o especificado", + mitigation: typeof risk.mitigation === "string" ? risk.mitigation : void 0 + }; + }); + const out_of_scope = Array.isArray(obj.out_of_scope) ? obj.out_of_scope.map((s) => String(s).trim()).filter(Boolean) : []; + const rawTasks = Array.isArray(obj.tasks) ? obj.tasks : []; + const tasks = rawTasks.map((t, idx) => { + const task = t && typeof t === "object" ? t : {}; + const id = String(task.id ?? `T${String(idx + 1).padStart(2, "0")}`).trim(); + const taskTitle = String(task.title ?? task.name ?? `Task ${idx + 1}`).trim(); + const description = typeof task.description === "string" ? task.description : void 0; + const rawAgent = task.agent ?? task.owner ?? task.assignee; + const agent = typeof rawAgent === "string" && rawAgent.trim().length > 0 ? rawAgent.replace(/^@/, "").trim() : "zeus"; + const rawPhase = task.phase; + let phase = 1; + if (typeof rawPhase === "number" && Number.isFinite(rawPhase)) { + phase = rawPhase; + } else if (typeof rawPhase === "string") { + const match = rawPhase.match(/\d+/); + if (match) phase = Number.parseInt(match[0], 10); + } + const rawState = String(task.state ?? task.status ?? "pending").trim().toLowerCase(); + const validStates = [ + "pending", + "ready", + "in_progress", + "done", + "failed", + "blocked" + ]; + const state = validStates.includes(rawState) ? rawState : "pending"; + const depends_on = Array.isArray(task.depends_on) ? task.depends_on.map((dep) => String(dep).trim()).filter(Boolean) : []; + const parallel_safe = Boolean(task.parallel_safe ?? task.parallel); + const rawAcceptance = Array.isArray(task.acceptance) ? task.acceptance : Array.isArray(task.acceptance_criteria) ? task.acceptance_criteria : Array.isArray(task.criteria) ? task.criteria : []; + const acceptance = rawAcceptance.map((a) => { + if (typeof a === "string") { + const checkText2 = a.trim(); + return { + kind: inferAcceptanceKind(checkText2), + check: checkText2, + fails_now: true, + verified: false + }; + } + const acc = a && typeof a === "object" ? a : {}; + const checkText = String( + acc.check ?? acc.description ?? acc.title ?? acc.name ?? "verify" + ).trim(); + const rawKind = String(acc.kind ?? "").trim().toLowerCase(); + const validKinds = ["test", "command", "file", "manual"]; + const kind = validKinds.includes(rawKind) ? rawKind : inferAcceptanceKind(checkText); + return { + kind, + check: checkText || "verify", + fails_now: typeof acc.fails_now === "boolean" ? acc.fails_now : true, + verified: Boolean(acc.verified), + proof: typeof acc.proof === "string" ? acc.proof : void 0 + }; + }); + const rawResult = task.result && typeof task.result === "object" ? task.result : void 0; + const result = rawResult ? { + summary: typeof rawResult.summary === "string" ? rawResult.summary : void 0, + verified_at: typeof rawResult.verified_at === "string" ? rawResult.verified_at : void 0, + artifacts: Array.isArray(rawResult.artifacts) ? rawResult.artifacts.map((art) => String(art)) : void 0 + } : void 0; + return { + id, + title: taskTitle, + description, + agent, + phase, + state, + depends_on, + parallel_safe, + acceptance, + result + }; + }); + const rawMeta = obj.metadata && typeof obj.metadata === "object" ? obj.metadata : {}; + const now = (/* @__PURE__ */ new Date()).toISOString(); + const metadata = { + created_at: typeof rawMeta.created_at === "string" ? rawMeta.created_at : now, + updated_at: typeof rawMeta.updated_at === "string" ? rawMeta.updated_at : now, + version: typeof rawMeta.version === "number" ? rawMeta.version : 1 + }; + return computeTaskReadiness({ + plan_id: slug, + title, + intent, + done_when, + decisions_needed, + risks, + out_of_scope, + tasks, + metadata + }); +} async function readPlan(cwd = process.cwd(), slug) { const path5 = deepworkPlanJsonPath(cwd, slug); + let raw; + try { + raw = await readFile6(path5, "utf8"); + } catch (err) { + if (err.code === "ENOENT") { + return null; + } + throw err; + } + let parsed; try { - const raw = await readFile6(path5, "utf8"); - const parsed = JSON.parse(raw); - return DeepworkPlanSchema.parse(parsed); + parsed = JSON.parse(raw); + } catch (err) { + throw new Error(`Plano '${slug}' em ${path5} cont\xE9m JSON inv\xE1lido: ${err.message}`); + } + const result = DeepworkPlanSchema.safeParse(parsed); + if (result.success) { + return result.data; + } + try { + const normalized = normalizePlanData(parsed, slug); + const repairedResult = DeepworkPlanSchema.safeParse(normalized); + if (repairedResult.success) { + return repairedResult.data; + } } catch { - return null; + } + const issues = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", "); + throw new Error(`Plano '${slug}' em ${path5} falhou na valida\xE7\xE3o de schema: ${issues}`); +} +var planLocks = /* @__PURE__ */ new Map(); +async function withPlanLock(cwd, slug, fn) { + const key = `${cwd}::${slug}`; + const prev = planLocks.get(key) ?? Promise.resolve(); + let resolveCurrent; + const current = new Promise((resolve8) => { + resolveCurrent = resolve8; + }); + planLocks.set(key, current); + try { + await prev; + return await fn(); + } finally { + resolveCurrent?.(); + if (planLocks.get(key) === current) { + planLocks.delete(key); + } } } async function writePlan(cwd = process.cwd(), plan) { @@ -12347,14 +12537,17 @@ async function writePlan(cwd = process.cwd(), plan) { version: (plan.metadata.version || 1) + 1 } }); + const randomSuffix = `${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`; const jsonPath = deepworkPlanJsonPath(cwd, plan.plan_id); - const jsonTmp = `${jsonPath}.tmp`; + const jsonTmp = `${jsonPath}.tmp.${randomSuffix}`; await writeFile3(jsonTmp, `${JSON.stringify(normalized, null, 2)} `, "utf8"); await rename5(jsonTmp, jsonPath); const mdPath = deepworkPlanMdPath(cwd, plan.plan_id); + const mdTmp = `${mdPath}.tmp.${randomSuffix}`; const mdContent = generateMarkdownDocument(normalized); - await writeFile3(mdPath, mdContent, "utf8"); + await writeFile3(mdTmp, mdContent, "utf8"); + await rename5(mdTmp, mdPath); } async function appendJournal(cwd = process.cwd(), slug, event) { const dir = deepworkPlanDir(cwd, slug); @@ -12365,93 +12558,101 @@ async function appendJournal(cwd = process.cwd(), slug, event) { await appendFile3(journalPath, line, "utf8"); } async function updateTaskState(cwd = process.cwd(), slug, taskId, state, result) { - const plan = await readPlan(cwd, slug); - if (!plan) { - throw new Error(`Deepwork plan "${slug}" not found`); - } - const taskIndex = plan.tasks.findIndex((t) => t.id === taskId); - const existingTask = plan.tasks[taskIndex]; - if (taskIndex === -1 || !existingTask) { - throw new Error(`Task "${taskId}" not found in plan "${slug}"`); - } - const updatedResult = result ? { ...existingTask.result ?? {}, ...result } : existingTask.result; - const updatedTask = { - ...existingTask, - state, - ...updatedResult !== void 0 ? { result: updatedResult } : {} - }; - const updatedTasks = [...plan.tasks]; - updatedTasks[taskIndex] = updatedTask; - const nextPlan = { ...plan, tasks: updatedTasks }; - await writePlan(cwd, nextPlan); - await appendJournal(cwd, slug, { - type: "task_state_changed", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - payload: { taskId, state, result } + return withPlanLock(cwd, slug, async () => { + const plan = await readPlan(cwd, slug); + if (!plan) { + throw new Error(`Deepwork plan "${slug}" not found`); + } + const taskIndex = plan.tasks.findIndex((t) => t.id === taskId); + const existingTask = plan.tasks[taskIndex]; + if (taskIndex === -1 || !existingTask) { + throw new Error(`Task "${taskId}" not found in plan "${slug}"`); + } + const updatedResult = result ? { ...existingTask.result ?? {}, ...result } : existingTask.result; + const updatedTask = { + ...existingTask, + state, + ...updatedResult !== void 0 ? { result: updatedResult } : {} + }; + const updatedTasks = [...plan.tasks]; + updatedTasks[taskIndex] = updatedTask; + const nextPlan = { ...plan, tasks: updatedTasks }; + await writePlan(cwd, nextPlan); + await appendJournal(cwd, slug, { + type: "task_state_changed", + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + payload: { taskId, state, result } + }); + return await readPlan(cwd, slug) ?? nextPlan; }); - return await readPlan(cwd, slug) ?? nextPlan; } async function verifyTaskAcceptance(cwd = process.cwd(), slug, taskId, checkIndex, verified, proof) { - const plan = await readPlan(cwd, slug); - if (!plan) { - throw new Error(`Deepwork plan "${slug}" not found`); - } - const taskIndex = plan.tasks.findIndex((t) => t.id === taskId); - const task = plan.tasks[taskIndex]; - if (taskIndex === -1 || !task) { - throw new Error(`Task "${taskId}" not found in plan "${slug}"`); - } - const currentAcc = task.acceptance[checkIndex]; - if (!currentAcc) { - throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`); - } - const updatedAcceptance = [...task.acceptance]; - const resolvedProof = proof ?? currentAcc.proof; - updatedAcceptance[checkIndex] = { - ...currentAcc, - verified, - ...resolvedProof !== void 0 ? { proof: resolvedProof } : {} - }; - const allVerified = updatedAcceptance.every((acc) => acc.verified); - const updatedTasks = [...plan.tasks]; - updatedTasks[taskIndex] = { - ...task, - acceptance: updatedAcceptance, - state: allVerified ? "done" : task.state - }; - const nextPlan = { ...plan, tasks: updatedTasks }; - await writePlan(cwd, nextPlan); - await appendJournal(cwd, slug, { - type: "acceptance_verified", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - payload: { taskId, checkIndex, verified, proof, allVerified } + return withPlanLock(cwd, slug, async () => { + const plan = await readPlan(cwd, slug); + if (!plan) { + throw new Error(`Deepwork plan "${slug}" not found`); + } + const taskIndex = plan.tasks.findIndex((t) => t.id === taskId); + const task = plan.tasks[taskIndex]; + if (taskIndex === -1 || !task) { + throw new Error(`Task "${taskId}" not found in plan "${slug}"`); + } + const currentAcc = task.acceptance[checkIndex]; + if (!currentAcc) { + throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`); + } + const updatedAcceptance = [...task.acceptance]; + const resolvedProof = proof ?? currentAcc.proof; + updatedAcceptance[checkIndex] = { + ...currentAcc, + verified, + ...resolvedProof !== void 0 ? { proof: resolvedProof } : {} + }; + const allVerified = updatedAcceptance.every((acc) => acc.verified); + const updatedTasks = [...plan.tasks]; + updatedTasks[taskIndex] = { + ...task, + acceptance: updatedAcceptance, + state: allVerified ? "done" : task.state + }; + const nextPlan = { ...plan, tasks: updatedTasks }; + await writePlan(cwd, nextPlan); + await appendJournal(cwd, slug, { + type: "acceptance_verified", + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + payload: { taskId, checkIndex, verified, proof, allVerified } + }); + return await readPlan(cwd, slug) ?? nextPlan; }); - return await readPlan(cwd, slug) ?? nextPlan; } async function resolvePlanDecision(cwd = process.cwd(), slug, decisionId, chosen) { - const plan = await readPlan(cwd, slug); - if (!plan) { - throw new Error(`Deepwork plan "${slug}" not found`); - } - const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId); - const existingDec = plan.decisions_needed[decIndex]; - if (decIndex === -1 || !existingDec) { - throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`); - } - const updatedDecisions = [...plan.decisions_needed]; - updatedDecisions[decIndex] = { - ...existingDec, - chosen, - status: "resolved" - }; - const nextPlan = { ...plan, decisions_needed: updatedDecisions }; - await writePlan(cwd, nextPlan); - await appendJournal(cwd, slug, { - type: "decision_resolved", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - payload: { decisionId, chosen } + return withPlanLock(cwd, slug, async () => { + const plan = await readPlan(cwd, slug); + if (!plan) { + throw new Error(`Deepwork plan "${slug}" not found`); + } + const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId); + const existingDec = plan.decisions_needed[decIndex]; + if (decIndex === -1 || !existingDec) { + throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`); + } + const updatedDecisions = [...plan.decisions_needed]; + updatedDecisions[decIndex] = { + ...existingDec, + chosen, + choice: chosen, + status: "resolved", + resolved_at: (/* @__PURE__ */ new Date()).toISOString() + }; + const nextPlan = { ...plan, decisions_needed: updatedDecisions }; + await writePlan(cwd, nextPlan); + await appendJournal(cwd, slug, { + type: "decision_resolved", + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + payload: { decisionId, chosen } + }); + return await readPlan(cwd, slug) ?? nextPlan; }); - return await readPlan(cwd, slug) ?? nextPlan; } async function listPlans(cwd = process.cwd()) { const root = deepworkRootDir(cwd); @@ -12584,7 +12785,7 @@ function createDeepworkTool(cwd = process.cwd()) { output: {}, async execute(input, context) { const parsed = DeepworkToolInputSchema.parse(input); - const effectiveCwd = typeof context?.directory === "string" ? context.directory : cwd; + const effectiveCwd = resolveToolCwd(context, cwd); if (parsed.action === "list") { const plans = await listPlans(effectiveCwd); if (plans.length === 0) { @@ -12613,67 +12814,36 @@ function createDeepworkTool(cwd = process.cwd()) { throw new Error(`O par\xE2metro 'slug' \xE9 obrigat\xF3rio para a a\xE7\xE3o '${parsed.action}'.`); } if (parsed.action === "init") { - const title = parsed.title?.trim() || slug; - const intent = parsed.intent?.trim() || "Plano de deepwork estruturado."; - const rawTasks = parsed.tasks ?? []; - const rawDecisions = parsed.decisions ?? []; - const doneWhen = parsed.done_when ?? []; - const tasks = rawTasks.map((t, idx) => ({ - id: typeof t.id === "string" ? t.id : `T${String(idx + 1).padStart(2, "0")}`, - title: typeof t.title === "string" ? t.title : `Task ${idx + 1}`, - description: typeof t.description === "string" ? t.description : void 0, - agent: typeof t.agent === "string" ? t.agent : "zeus", - phase: typeof t.phase === "number" ? t.phase : 1, - state: typeof t.state === "string" ? t.state : "pending", - depends_on: Array.isArray(t.depends_on) ? t.depends_on : [], - parallel_safe: Boolean(t.parallel_safe), - acceptance: Array.isArray(t.acceptance) ? t.acceptance.map((a) => ({ - kind: a.kind || "command", - check: a.check || "verify", - fails_now: a.fails_now ?? true, - verified: a.verified ?? false, - proof: a.proof - })) : [] - })); - const decisions = rawDecisions.map((d, idx) => ({ - id: typeof d.id === "string" ? d.id : `D${String(idx + 1).padStart(2, "0")}`, - question: typeof d.question === "string" ? d.question : "Decis\xE3o necess\xE1ria", - options: Array.isArray(d.options) ? d.options : ["Sim", "N\xE3o"], - chosen: typeof d.chosen === "string" ? d.chosen : void 0, - status: d.chosen ? "resolved" : "pending" - })); - const initialPlan = computeTaskReadiness({ - plan_id: slug, - title, - intent, - done_when: doneWhen, - decisions_needed: decisions, - risks: [], - out_of_scope: [], - tasks, - metadata: { - created_at: (/* @__PURE__ */ new Date()).toISOString(), - updated_at: (/* @__PURE__ */ new Date()).toISOString(), - version: 1 - } - }); - await writePlan(effectiveCwd, initialPlan); - await appendJournal(effectiveCwd, slug, { - type: "plan_created", - timestamp: (/* @__PURE__ */ new Date()).toISOString(), - payload: { slug, title, tasks_count: tasks.length } + const initialPlan = normalizePlanData( + { + plan_id: slug, + title: parsed.title, + intent: parsed.intent, + done_when: parsed.done_when, + decisions_needed: parsed.decisions, + tasks: parsed.tasks + }, + slug + ); + await withPlanLock(effectiveCwd, slug, async () => { + await writePlan(effectiveCwd, initialPlan); + await appendJournal(effectiveCwd, slug, { + type: "plan_created", + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + payload: { slug, title: initialPlan.title, tasks_count: initialPlan.tasks.length } + }); }); const projection = generateChatProjection(initialPlan, effectiveCwd); const approvalQ = buildApprovalQuestion(initialPlan); const todoPayload = { - todos: tasks.map((t) => ({ + todos: initialPlan.tasks.map((t) => ({ content: `[${t.id}] ${t.title}`, status: t.state === "done" ? "completed" : t.state === "in_progress" ? "in_progress" : "pending" })) }; return { output: [ - `\u2705 Plano de Deepwork '${title}' inicializado com sucesso em \`.pantheon/deepwork/${slug}/\`!`, + `\u2705 Plano de Deepwork '${initialPlan.title}' inicializado com sucesso em \`.pantheon/deepwork/${slug}/\`!`, `- \u{1F517} **Deeplink PLAN.md:** [Abrir PLAN.md](file://${deepworkPlanMdPath(effectiveCwd, slug)})`, `- \u{1F517} **Deeplink plan.json:** [Abrir plan.json](file://${deepworkPlanJsonPath(effectiveCwd, slug)})`, "", @@ -13013,7 +13183,7 @@ var v2InputSchema = { "complexity" ], properties: { - schemaVersion: { type: "integer", const: 1 }, + schemaVersion: { type: "integer", enum: [1] }, candidateAgents: { type: "array", maxItems: 14, items: { type: "string", minLength: 1 } }, domain: { type: ["string", "null"] }, candidateSkillIds: { type: "array", maxItems: 64, items: { type: "string", minLength: 1 } }, @@ -14122,6 +14292,37 @@ var SKILL_SEARCH_INPUT_SCHEMA = { } } }; +function scoreSkillMatch(id, description, queryTokens) { + const idLower = id.toLowerCase(); + const descLower = description.toLowerCase(); + const idTokens = idLower.split(/[^a-z0-9]+/).filter(Boolean); + const descWords = descLower.split(/[^a-z0-9]+/).filter(Boolean); + let score = 0; + let matchedTokens = 0; + for (const t of queryTokens) { + let tokenScore = 0; + if (idLower === t) { + tokenScore += 20; + } else if (idTokens.includes(t)) { + tokenScore += 12; + } else if (idTokens.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w)))) { + tokenScore += 6; + } + if (descWords.includes(t)) { + tokenScore += 5; + } else if (descWords.some((w) => w.length >= 4 && t.length >= 4 && (w.startsWith(t) || t.startsWith(w)))) { + tokenScore += 2; + } + if (tokenScore > 0) { + score += tokenScore; + matchedTokens += 1; + } + } + if (matchedTokens > 1) { + score += matchedTokens * 5; + } + return { score, matchedTokens }; +} function executeSkillSearch(input, options = {}) { const query = typeof input.query === "string" ? input.query.trim() : ""; if (query.length === 0) { @@ -14136,39 +14337,34 @@ function executeSkillSearch(input, options = {}) { "skills-sh" ] ); - const results = []; const failures = []; const cwd = options.cwd ?? process.cwd(); const installedMap = scanInstalledSkills(cwd); - if (sources.has("installed")) { - const tokens = query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2); - if (tokens.length > 0) { - for (const entry of installedMap.values()) { - const idLower = entry.id.toLowerCase(); - const descLower = entry.description.toLowerCase(); - const matchScore = tokens.reduce((score, t) => { - const stem = t.length > 4 ? t.slice(0, 4) : t; - return score + (idLower.includes(t) || descLower.includes(t) || idLower.includes(stem) || descLower.includes(stem) ? 1 : 0); - }, 0); - if (matchScore > 0) { - results.push({ - skill: entry.id, - description: entry.description, - source: "installed", - installed: true, - installs: null, - installCommand: null, - path: entry.path, - scope: entry.scope - }); - } + const tokens = query.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1); + const scoredResults = []; + if (sources.has("installed") && tokens.length > 0) { + const minThreshold = tokens.length > 1 ? 5 : 2; + for (const entry of installedMap.values()) { + const { score } = scoreSkillMatch(entry.id, entry.description, tokens); + if (score >= minThreshold) { + scoredResults.push({ + skill: entry.id, + description: entry.description, + source: "installed", + installed: true, + installs: null, + installCommand: null, + path: entry.path, + scope: entry.scope, + score + }); } } } const externalSources = ["anthropic", "skills-sh", "github"].filter((s) => sources.has(s)); - if (externalSources.length > 0 && results.length < limit) { + if (externalSources.length > 0 && scoredResults.length < limit) { try { - const extLimit = limit - results.length; + const extLimit = limit - scoredResults.length; const extRes = searchSkillSources(query, { limit: extLimit, sources: externalSources @@ -14177,11 +14373,21 @@ function executeSkillSearch(input, options = {}) { failures.push(...extRes.failures); } if (Array.isArray(extRes.entries)) { + const minThreshold = tokens.length > 1 ? 5 : 2; for (const entry of extRes.entries) { const bareName = (entry.skill.includes("@") ? entry.skill.split("@")[1] : entry.skill).toLowerCase(); const isInstalled = installedMap.has(entry.skill.toLowerCase()) || installedMap.has(bareName); const installedRecord = installedMap.get(entry.skill.toLowerCase()) || installedMap.get(bareName); - const pushItem = { + const { score } = scoreSkillMatch(entry.skill, entry.skill, tokens); + if (score < minThreshold && !isInstalled) { + continue; + } + if (scoredResults.some( + (r) => r.skill.toLowerCase() === entry.skill.toLowerCase() || bareName && r.skill.toLowerCase() === bareName + )) { + continue; + } + scoredResults.push({ skill: entry.skill, description: entry.skill, source: entry.source, @@ -14190,9 +14396,9 @@ function executeSkillSearch(input, options = {}) { ...entry.url ? { url: entry.url } : {}, installCommand: isInstalled ? null : `npx skills add ${entry.skill} -a opencode -y`, path: isInstalled && installedRecord ? installedRecord.path : null, - ...isInstalled && installedRecord ? { scope: installedRecord.scope } : {} - }; - results.push(pushItem); + ...isInstalled && installedRecord ? { scope: installedRecord.scope } : {}, + score: score || 1 + }); } } } catch (err) { @@ -14201,7 +14407,8 @@ function executeSkillSearch(input, options = {}) { ); } } - const bounded = results.slice(0, limit); + scoredResults.sort((a, b) => b.score - a.score); + const bounded = scoredResults.slice(0, limit).map(({ score: _, ...item }) => item); return { ok: true, query, @@ -14210,14 +14417,14 @@ function executeSkillSearch(input, options = {}) { failures }; } -function createV2SkillSearchDefinition() { +function createV2SkillSearchDefinition(defaultDir) { return { name: "pantheon_skill_search", description: TOOL_DESCRIPTION3, input: SKILL_SEARCH_INPUT_SCHEMA, output: {}, execute: async (input, context) => { - const cwd = context?.directory || process.cwd(); + const cwd = resolveToolCwd(context, defaultDir); return { output: JSON.stringify(executeSkillSearch(input, { cwd }), null, 2) }; @@ -14439,18 +14646,18 @@ var MODEL_INPUT = { scope: { type: "string", enum: ["project"], - description: "Project scope only; global overrides are not supported in V2." + description: "Project scope only; global overrides are not supported." } } }; var modelCommand = createModelCommand({ v2Mode: true }); async function executeModel(input, context) { if (input.scope !== void 0 && input.scope !== "project") { - return { output: "Error: V2 pantheon_model is project-only; global scope is not supported." }; + return { output: "Error: pantheon_model is project-only; global scope is not supported." }; } if (Object.hasOwn(input, "confirm") || Object.hasOwn(input, "authorize_global")) { return { - output: "Error: V2 pantheon_model does not accept authorization flags; global authorization is not supported by this tool." + output: "Error: pantheon_model does not accept authorization flags; global authorization is not supported by this tool." }; } const output = await modelCommand.pantheon_model.execute( @@ -14534,35 +14741,37 @@ var SHELL_INPUT = { } } }; -var shellTool = { - name: "shell", - description: "Execute a shell command in the workspace directory. Alias for bash execution.", - input: SHELL_INPUT, - output: {}, - execute: async (input, context) => { - const raw = input ?? {}; - const command = String(raw.command ?? raw.cmd ?? ""); - if (!command.trim()) { - return { output: "", ok: false, error: "Command cannot be empty" }; - } - const toolCtx = toolContext(context); - const cwd = toolCtx.directory || process.cwd(); - try { - const { stdout, stderr } = await execAsync(command, { - cwd, - maxBuffer: 10 * 1024 * 1024, - shell: "/bin/bash" - }); - const output = [stdout, stderr].filter(Boolean).join("\n"); - return { output, ok: true }; - } catch (err) { - const execError = err; - const output = [execError.stdout, execError.stderr, execError.message].filter(Boolean).join("\n"); - return { output, ok: false, error: output }; +function createShellTool(fallbackDir) { + return { + name: "shell", + description: "Execute a shell command in the workspace directory. Alias for bash execution.", + input: SHELL_INPUT, + output: {}, + execute: async (input, context) => { + const raw = input ?? {}; + const command = String(raw.command ?? raw.cmd ?? ""); + if (!command.trim()) { + return { output: "", ok: false, error: "Command cannot be empty" }; + } + const cwd = resolveToolCwd(context, fallbackDir); + try { + const { stdout, stderr } = await execAsync(command, { + cwd, + maxBuffer: 10 * 1024 * 1024, + shell: "/bin/bash" + }); + const output = [stdout, stderr].filter(Boolean).join("\n"); + return { output, ok: true }; + } catch (err) { + const execError = err; + const output = [execError.stdout, execError.stderr, execError.message].filter(Boolean).join("\n"); + return { output, ok: false, error: output }; + } } - } -}; -function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) { + }; +} +var shellTool = createShellTool(); +function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime, hostLocationDirectory) { const definitions = [ { name: "hashline_edit", @@ -14573,14 +14782,14 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) { }, { name: "pantheon_cost", - description: "Report token usage and USD cost by agent and phase, by model, and by session, over the last N days from opencode.db (read-only). Costs come from the models.dev catalog cached on disk: a call reads that cache and never waits on the network unless refreshPricing is set, a stale cache is refreshed in the background and the report says so, and an unpriced model reads \u2014 and is excluded from the totals, which then say partial. Pass session= to aggregate that session plus its descendant sessions. Phase may be unknown on V2; costs are catalog list prices, not an invoice.", + description: "Report token usage and USD cost by agent and phase, by model, and by session, over the last N days from opencode.db (read-only). Costs come from the models.dev catalog cached on disk: a call reads that cache and never waits on the network unless refreshPricing is set, a stale cache is refreshed in the background and the report says so, and an unpriced model reads \u2014 and is excluded from the totals, which then say partial. Pass session= to aggregate that session plus its descendant sessions. Phase may be unknown; costs are catalog list prices, not an invoice.", input: COST_INPUT, output: {}, execute: executeCost }, { name: "pantheon_model", - description: 'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. V2 ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model selection. Global overrides are not read or written in V2; future global support requires separate explicit authorization. Pass action="status" to read project-scoped overrides. Never writes .env or top-level model/small_model.', + description: 'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. Ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model selection. Global overrides are not read or written; future global support requires separate explicit authorization. Pass action="status" to read project-scoped overrides. Never writes .env or top-level model/small_model.', input: MODEL_INPUT, output: {}, execute: executeModel @@ -14593,9 +14802,9 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime) { ); definitions.push(todowriteTool); definitions.push(todoreadTool); - definitions.push(shellTool); - definitions.push(createV2SkillSearchDefinition()); - definitions.push(createDeepworkTool()); + definitions.push(createShellTool(hostLocationDirectory)); + definitions.push(createV2SkillSearchDefinition(hostLocationDirectory)); + definitions.push(createDeepworkTool(hostLocationDirectory)); if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime)); if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime)); return definitions; @@ -14923,7 +15132,8 @@ async function registerV2Tools(context, boundedRead, jevRuntime) { p3Sink.emit({ ...record2, mode: "shadow" }); } }, - runtime + runtime, + host.location?.directory ); if (boundedRead !== void 0) toolDefs.push(boundedRead); const p11Sink = createTelemetrySink(); diff --git a/src/plugins/tui/dist/tui.d.ts b/src/plugins/tui/dist/tui.d.ts index 69158b21..7c2958ab 100644 --- a/src/plugins/tui/dist/tui.d.ts +++ b/src/plugins/tui/dist/tui.d.ts @@ -608,8 +608,10 @@ export declare function toDispatchEntry(child: any, status: string | undefined, * cost. */ export declare function collectDispatch(context: any, sessionID: string | undefined, options?: CollectDispatchOptions): DispatchEntry[]; /** Sidebar blocks in render order. Spacing is derived from this list instead of - * from the view, so a hidden block can never leave an empty gap behind. */ -export type SidebarBlockKey = 'context' | 'git' | 'todo' | 'dispatch'; + * from the view, so a hidden block can never leave an empty gap behind. + * Note: The custom Todo block was removed from the sidebar composition because + * OpenCode 2.x natively renders the Todo panel when `todowrite` is used. */ +export type SidebarBlockKey = 'context' | 'git' | 'dispatch'; /** One rendered block: its key, and whether a blank line precedes it. */ export type SidebarBlock = { key: SidebarBlockKey; @@ -618,10 +620,9 @@ export type SidebarBlock = { /** Header glyph per block — one codepoint each, rendered muted before the bold * label. The fixed header (version/preset/session) takes none. * Measured as one terminal cell by the host (`@opentui/core` counts - * `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), ▾ U+25BE (N), - * ◈ U+25C8 (A). `☑` U+2611 was rejected for the Todo header because it matches - * `emoji-regex` and would occupy two cells; `⌁` U+2301 (the old Dispatch glyph) - * was replaced by the host's own Notice glyph. */ + * `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), + * ◈ U+25C8 (A). `⌁` U+2301 (the old Dispatch glyph) was replaced by the host's + * own Notice glyph. */ export declare const BLOCK_ICONS: Record; /** Tag every block that has content with its spacer: never before the first * (the view puts a single blank line after the fixed header instead), one diff --git a/src/plugins/tui/dist/tui.d.ts.map b/src/plugins/tui/dist/tui.d.ts.map index d30dd7ee..d81932f7 100644 --- a/src/plugins/tui/dist/tui.d.ts.map +++ b/src/plugins/tui/dist/tui.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"tui.d.ts","names":[],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/sidebar-width.ts","../src/index.tsx"],"mappings":";;;;KAEY;qBAEC;qBACA;qBACA;KAED;UAiBK;EACf;EACA,QAAQ;EACR;;wBAOc,iBAAiB,kBAAkB;wBAOnC,iBAAiB;wBAMjB,oBAAoB;wBAQpB,iBAAiB,iBAAiB;wBAOlC,WACd,oCACA,mBAAkB;EACf;EAAgB;;wBA+CL,YAAY;;;;qBChHf;qBACA;qBACA;;;;;;;;wBCyHG,UAAU;;;;qBCtDb;;;;qBAMA;;;qBAGA;qBACA;;YAED,mBAAmB,WAAW;;;;;;;;;;qBAU7B;YAmBD;EAAe;EAAqB;;;YAGpC;EAAuB;EAAgB;;;YAEvC;EAAoB,QAAQ,eAAe;;;YAE3C;EAAuB,MAAM;EAAY,WAAW;;;;wBAQhD,qBAAqB,iBAAiB;;wBAqDtC,cAAc,KAAK,qCAAqC;;;wBAUlD,0BACpB,KAAK,oCACL,cACC,QAAQ;;;wBAeK,iBAAiB,cAAc;;;wBAgB/B,WAAW;;;wBAWX,aAAa,cAAc;;;wBAU3B,kBAAkB;;;wBAQlB,qBAAqB,iBAAiB;;;;wBAmBtC,oBAAoB,wBAAwB;YAwChD;EAAyB;EAAgB;EAAiB;;;wBAuItD,4BACd,8BACA,mBACA,4BACA,kCACC;;wBAUa,sBACd,uBACA,oCACA;;wBAgBc,mBAAmB;YAYvB;EAAiB;EAAgB;EAAiB;;;;;;;wBAO9C,iBACd,0BACA;EACG;EAAe;;;;;;wBAsBJ,oBACd,0BACA,yCACA,kCACC;;;;;wBAqBa,qBAAqB,OAAO,qBAAqB;;;;;wBAQjD,uBACd,aAAa;;;;;wBAeC,gBAAgB;;;;;;;wBAehB,wBACd,6CACA;;;;;;;;;;;;;wBAwBc,oBACd,6CACA;;;YAmDU;EAAuB;EAAyB;;;;;YAKhD;EACV;EACA;EACA;EACA;EACA,MAAM;;;YAII;EACV,QAAQ;EACR,SAAS;EACT,OAAO;;;;;;;;;wBAUO,iBACd,OAAO,qBACP,iCACA,iDACA;EAAwB;EAAa;EAAgB;IACpD;;qBAuDU;qBACA;qBACA;;;qBAGA;;YAGD;EAAe;EAAe;EAAgB;;;;;;wBAM1C,kBAAkB,2BAA2B;;YA0BjD;EACV,SAAS;EACT;EACA;EACA;;;;wBAKc,kBACd,eAAe,cACf,sBACC;;wBAaa,kBAAkB;;;;wBASlB,gBAAgB;;YAapB;EAAkB;EAAe;EAAgB;;;;wBAI7C,eAAe,eAAe,eAAe;;wBAS7C,kBAAkB,KAAK;;wBAmCvB,iBAAiB;;wBAKjB,kBAAkB,eAAe;;wBAQjC,kBAAkB;;wBAQlB,mBAAmB,KAAK;;;wBAYxB,qBAAqB,gBAAgB;;qBAaxC;;;wBAIG,SAAS;YAiBb;;;YAIA;EAAa;EAAiB,QAAQ;;;qBAGrC;;qBAEA;;wBAmBG,aAAa,iBAAiB,SAAS;;;;wBASvC,eAAe,iBAAiB;;;;;;wBAmBhC,gBAAgB,8CAA8C;;;wBAmB9D,eAAe,gBAAgB,aAAa;;;YAQhD;;wBAGI,SAAS,QAAQ,aAAa;;wBAO9B,YAAY,MAAM;;YAKtB;EAAgB,SAAS;EAAY;;;wBAGjC,iBACd,gBAAgB,YAChB,sBACC;;wBAOa,eAAe;YAgBnB;EAAoB;EAAe;EAAkB;;;;wBASjD,gBAAgB,2CAA2C;;;wBAY3D,iBAAiB;;;qBAoBpB;;;qBAGA;;;;qBAIA;;;;;qBAKA;;;YAID,WACV,cACA,yBACA;EAAW;EAAa;EAAiB;EAAsB;MAC5D;EAAU;;;;qBAIF,gBAAgB;;;;;;;YAwBjB;EACV;EACA;EACA;EACA;;;;wBAKc,wBAAwB,oCAAoC;;;;;wBAwB5D,oBACd;EACG;EAAe;;;;YAYR;EACV,SAAS;EACT;EACA;;;;;;wBAOoB,gBACpB,mBACA,OAAM,UACL,QAAQ;;;wBA8BK,kBAAkB,UAAU;;;wBAe5B,gBACd;EAAS;EAAa;EAA0B;GAChD;;qBAiBW;qBACA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;YAGD;EAAgB;EAAsB;;;;;KAK7C;;wBAQW;;wBAMA,qBAAqB;;;wBAMrB,gBAAgB;;;wBAQhB,aAAa;EAC3B;IAAS;IAAc;;EACvB;IAAc;IAAc;;;;;;wBAWd,eAAe;;;wBAaf,UAAU;;;;;;wBAUV,kBACd,gBACA;EAAQ;EAAc;GACtB;;;;;wBAiBc,iBAAiB,QAAQ;;;;;;;wBAkBzB,cAAc,eAAe;;;;wBAoB7B,QAAQ,eAAe;;qBAQ1B;;;;wBAKG,iBAAiB,oBAAoB;YAsBzC;YACA;;YAGA;EAAsB,MAAM;EAAqB,QAAQ;;;;wBAsBrD,uBAAuB,uBAAuB;;wBAY9C,sBAAsB,iBAAiB;;;;wBAQvC,qBACd;EAAQ;EAAuB;uBAC9B;;YAQS;;EAEV;EACA;EACA;EACA;;;;;;;;wBAsCc,qBACd,8CACC,YAAY;YA6BH;YACA;;;;;;;;;;qBAWC;;YAGD;;EAEV;;EAEA;EACA,OAAO;;EAEP;;EAEA;;EAEA;;EAEA;;EAEA;;;EAGA,MAAM;;EAEN,YAAY;;EAEZ;;;;;;;;;wBAUc,0BACd,4BACA;EAAS;EAAkB;GAC3B,cACA,mBACC;;;;;wBAoBa,2BAA2B,mBAAmB;;;;;;;;wBAoB9C,iBACd,YACA,4BACA,cACA,OAAO,sBACN;;;wBA4Ba,aAAa;;YA0BjB;EACV;EACA;EACA;EACA;EACA;;;;;YAMU;EACV,MAAM;EACN;EACA;EACA;EACA,QAAQ;;;;;YAME;EACV;EACA,QAAQ,YAAY;;;wBAeN,eAAe,kBAAkB;;;;wBA2BjC,gBACd,YACA,4BACA,cACA,OAAO,sBACN;;;;;;;;;wBAuBa,gBACd,cACA,+BACA,UAAS,yBACR;;;YAsCS;;YAGA;EAAiB,KAAK;EAAiB;;;;;;;;;qBAStC,aAAa,OAAO;;;;;;wBAYjB,iBAAiB,eAAe,oBAAoB;;qBAmBvD;;qBAEA;;;qBAGA;;qBAEA;;qBAEA;;;qBAGA;;;qBAGA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;;;;;qBAMA;;;;wBAUG,mBACd,MAAM,iCACN;;;;wBAUc,sBACd,oCACA;;;;wBAac,uBAAuB;;;;wBAiBvB,gBAAgB,MAAM,gBAAgB;;;wBAStC,kBACd,MAAM,KAAK,2CACX;;wBAUc,kBAAkB,MAAM,KAAK;;;;wBAQ7B,mBAAmB;;;wBAMnB,kBAAkB,gBAAgB;;;;;;;;wBAgBlC,oBACd,MAAM,gBACN,cACA,gBACA;;;;;YAuCU;EACV;EACA;EACA;EACA,MAAM;EACN;;;;;;;wBAQc,uBAAuB,gBAAgB,mBAAmB;;;;;wBA4C1D,kBAAkB,KAAK,iBAAiB;;;wBAwBxC,sBAAsB,gBAAgB;;;;;wBAWtC,qBACd,sCACA,iCACA;;;wBAiBc,iBAAiB;;YAQrB;EAAwB;EAAY;;;YAGpC;EACV;EACA;EACA;EACA;EACA;EACA,SAAS;EACT;EACA;EACA,QAAQ;EACR;EACA;;;;;;;wBAcc,mBACd,gBAAgB,kBAChB,cACA,gBACA,eACC;;;qBA8DU;;;qBAGA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;;qBAGA;qBACA;qBACA;qBACA;qBACA;;qBAEA;;qBAEA;;qBAOA,6BAA6B,SAAS,OAAO;;;wBAQ1C,qBAAqB,kBAAkB,kBAAkB;;;;wBAOzD,mBACd,yCACA,cACA;;;;;wBAac,oBACd,kBAAkB;;wBAgCJ,kBAAkB,eAAe;;;;;wBASjC,oBAAoB,OAAO,0BAA0B;;;;wBAkBrD,kBAAkB,gBAAgB;;;;;;wBAWlC,qBACd,OAAO,eACP;EAAW;EAAc;EAAgB;;;wBAyB3B,eAAe,+BAA+B;;;wBAQ9C,kBAAkB,QAAQ;;;;;wBAgB1B,oBACd,OAAO,kCACP;EAAW;EAAoB;;;;;YAiCrB;EACV;EACA;EACA;EACA;;wBAGc,oBAAoB,gBAAgB;;;;wBAsBpC,oBACd,eACA,uBACA;EACG;EAAe;EAAa;;;;wBAWjB,uBAAuB,eAAe,aAAa;;;YAUvD;EAAqB;EAAY,OAAO;EAAiB;;;wBAGrD,kBACd,kBAAkB,oCAClB;EAAW;EAAc;EAAgB;IACxC;;YAYS;;YAYA;EACV,QAAQ;EACR;EACA;EACA;;;;;qBAMW,kCAAkC;;;;wBA6C/B,2BACd,QAAQ,qBACR,OAAO,KAAK,mFACZ,OAAO,KAAK;;;;wBAsCE,oBAAoB,cAAc;;;YAyBtC;WACD;WACA;WACA;WACA;;;;;;wBAiBK,kBAAkB;;;;YAmBtB;EACV,SAAS,SAAS;EAClB,MAAM,SAAS;EACf,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,QAAQ,SAAS;EACjB,SAAS;IAAW;IAAe,MAAM;;EACzC,YAAY;EACZ,eAAe;EACf,UAAU;EACV,YAAY;EACZ,OAAO;EACP,QAAQ;EACR,OAAO;EACP;EACA;EACA;EACA;EACA;;;;;;;wBAQc,yBACd,cACA,aAAa,qBACZ;;wBA0Ha,qBACd,0BACA;;;;;;wBAkBc,mBAAmB;;;;wBASnB,kBACd;EAAU,YAAY;eACtB;YAaU;EAAyB;EAAY;EAAe,OAAO;;;;;;wBAMvD,4BACd,UAAU,oBAAoB,kBAC9B,SAAS,cAAc;EACpB,WAAW;EAAwB,UAAU,YAAY;;;;;qBA4LjD;;;;YAgGD;EACV,iBAAiB;EACjB,SAAS;EACT,QAAQ;;;EAGR,YAAY;;;EAGZ,SAAS;;;EAGT,QAAQ,SAAS;;EAEjB,aAAa,SAAS;;;EAGtB,UAAU,SAAS;;EAEnB,QAAQ,SAAS;EACjB,YAAY;EACZ,OAAO;EACP,QAAQ,SAAS;;;EAGjB,UAAU;;EAEV,iBAAiB,SAAS;;EAE1B,MAAM;;EAEN,YAAY,SAAS;;EAErB,MAAM,SAAS;;;EAGf,OAAO,SAAS;;EAEhB,cAAc,SAAS;;EAEvB,YAAY;IAAW;IAAe;IAAe;;;;;;;wBAOvC,mBACd,cACA,qCACA,UAAS,UACR;;;;wBA09Ba,wBACd,QAAQ,qBACR,OAAO,KAAK,uDACZ,OAAO,KACL;;;;;;;wBAgBY,yBACd,OAAO,KAAK,uDACZ,OAAO,qBACN;;;;;YA4LS;EACV,QAAQ,SAAS;EACjB,SAAS;;wBAGK,kBAAkB,cAAc,sCAAsC;cA0DhF;;EAEW,MAAA,SAAA"} +{"version":3,"file":"tui.d.ts","names":[],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/sidebar-width.ts","../src/index.tsx"],"mappings":"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"} diff --git a/src/plugins/tui/dist/tui.js b/src/plugins/tui/dist/tui.js index 515e02c1..218c60a0 100644 --- a/src/plugins/tui/dist/tui.js +++ b/src/plugins/tui/dist/tui.js @@ -1500,7 +1500,7 @@ const DEFAULT_TUI_PREFS = { blocks: { context: true, git: true, - todo: true, + todo: false, dispatch: true }, context: { @@ -1557,7 +1557,7 @@ function normalizeTuiPrefs(raw) { blocks: { context: asBool(blocks.context, true), git: asBool(blocks.git, true), - todo: asBool(blocks.todo, true), + todo: asBool(blocks.todo, false), dispatch: asBool(blocks.dispatch, true) }, context: { @@ -1665,7 +1665,6 @@ function buildTuiTab(prefs, languagePref) { rows: [ row("tui.sidebar.block.context", isPt ? "Bloco de contexto" : "Context block", prefs.sidebar.blocks.context, isPt ? "tokens, medidor, custo, uso de modelos" : "tokens, gauge, spend, model usage"), row("tui.sidebar.block.git", isPt ? "Bloco do Git" : "Git block", prefs.sidebar.blocks.git, isPt ? "branch + contagem de alterações" : "branch + working-tree counts"), - row("tui.sidebar.block.todo", isPt ? "Bloco Todo" : "Todo block", prefs.sidebar.blocks.todo, isPt ? "tarefas pendentes mais recentes" : "the newest todowrite"), row("tui.sidebar.block.dispatch", isPt ? "Bloco Dispatch" : "Dispatch block", prefs.sidebar.blocks.dispatch, isPt ? "delegações em tempo real" : "live delegations + rollup") ] }, @@ -2062,7 +2061,7 @@ async function readChangelogForBundle(bundleUrl) { } /** The ambient build-time version, or null outside a tsdown build. */ function embeddedVersion() { - return "2.1.5"; + return "2.1.6"; } /** * Resolve the running Pantheon version for the what's-new window: the plugin @@ -2287,7 +2286,7 @@ function persistUpdateCheckState(previous, latest) { } catch {} } function resolveRunningVersion() { - return "2.1.5"; + return "2.1.6"; } const VALUE_WIDTH = 24; function SettingsWindow(props) { @@ -5611,19 +5610,19 @@ function collectDispatch(context, sessionID, options = {}) { return entries.sort((a, b) => compareDelegations(a.view, b.view)); } /** Sidebar blocks in render order. Spacing is derived from this list instead of -* from the view, so a hidden block can never leave an empty gap behind. */ +* from the view, so a hidden block can never leave an empty gap behind. +* Note: The custom Todo block was removed from the sidebar composition because +* OpenCode 2.x natively renders the Todo panel when `todowrite` is used. */ /** One rendered block: its key, and whether a blank line precedes it. */ /** Header glyph per block — one codepoint each, rendered muted before the bold * label. The fixed header (version/preset/session) takes none. * Measured as one terminal cell by the host (`@opentui/core` counts -* `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), ▾ U+25BE (N), -* ◈ U+25C8 (A). `☑` U+2611 was rejected for the Todo header because it matches -* `emoji-regex` and would occupy two cells; `⌁` U+2301 (the old Dispatch glyph) -* was replaced by the host's own Notice glyph. */ +* `emoji-regex` matches as two): ▤ U+25A4 (EAW=A), ◆ U+25C6 (A), +* ◈ U+25C8 (A). `⌁` U+2301 (the old Dispatch glyph) was replaced by the host's +* own Notice glyph. */ const BLOCK_ICONS = { context: "▤", git: "◆", - todo: "▾", dispatch: "◈" }; /** Tag every block that has content with its spacer: never before the first @@ -6513,7 +6512,7 @@ async function checkForPantheonUpdate(context) { const latest = String((await response.json())?.version ?? ""); if (!latest) return; const notice = pickUpdateNotice({ - currentVersion: "2.1.5", + currentVersion: "2.1.6", latestVersion: latest, state: readState(), nowMs: Date.now() @@ -7057,7 +7056,6 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { const present = []; if (prefs.sidebar.blocks.context && (contextBlockRows(contextUsage(), cost(), prefs.sidebar.context.gauge) !== null || prefs.sidebar.context.localSpend && contextSpendLine(spend()) !== null)) present.push("context"); if (prefs.sidebar.blocks.git && (branch() !== null || gitLine() !== null)) present.push("git"); - if (prefs.sidebar.blocks.todo && todo().visible.length > 0) present.push("todo"); if (prefs.sidebar.blocks.dispatch && dispatch() !== null) present.push("dispatch"); return withBlockSpacers(present); }); @@ -7277,11 +7275,6 @@ function Sidebar(props) { const text = () => context.theme.text?.base; const muted = () => context.theme.text?.muted ?? text(); const tone = (value) => context.theme?.text?.feedback?.[value]?.base ?? text(); - const todoFg = (status) => { - const rowTone = todoTone(status); - if (rowTone === "accent") return tone("warning"); - return rowTone === "muted" ? muted() : text(); - }; const open = (sessionID) => () => navigateToSession(context.ui?.router, sessionID); const block = (key) => model.blocks().find((entry) => entry.key === key); const spacer = (key) => block(key)?.spacer === true; @@ -7325,7 +7318,7 @@ function Sidebar(props) { get children() { var _el$13 = createElement("text"); setProp(_el$13, "attributes", 1); - insert(_el$13, `Pantheon v2.1.5`); + insert(_el$13, `Pantheon v2.1.6`); effect((_$p) => setProp(_el$13, "fg", text(), _$p)); return _el$13; } @@ -7352,24 +7345,24 @@ function Sidebar(props) { }, get fallback() { return (() => { - var _el$26 = createElement("box"); - setProp(_el$26, "height", 0); - return _el$26; + var _el$23 = createElement("box"); + setProp(_el$23, "height", 0); + return _el$23; })(); }, get children() { - var _el$25 = createElement("text"); - insert(_el$25, () => sidebarPlaceholder(props.sessionID)); - effect((_$p) => setProp(_el$25, "fg", muted(), _$p)); - return _el$25; + var _el$22 = createElement("text"); + insert(_el$22, () => sidebarPlaceholder(props.sessionID)); + effect((_$p) => setProp(_el$22, "fg", muted(), _$p)); + return _el$22; } }); }, children: (current) => (() => { - var _el$27 = createElement("text"); - insert(_el$27, () => `Session: ${truncateLabel(current().title || current().id)}`); - effect((_$p) => setProp(_el$27, "fg", text(), _$p)); - return _el$27; + var _el$24 = createElement("text"); + insert(_el$24, () => `Session: ${truncateLabel(current().title || current().id)}`); + effect((_$p) => setProp(_el$24, "fg", text(), _$p)); + return _el$24; })() }), null); insert(_el$12, createComponent(Show, { @@ -7416,9 +7409,9 @@ function Sidebar(props) { return contextRows(); }, children: (rows) => (() => { - var _el$28 = createElement("box"); - setProp(_el$28, "flexDirection", "column"); - insert(_el$28, createComponent(Show, { + var _el$25 = createElement("box"); + setProp(_el$25, "flexDirection", "column"); + insert(_el$25, createComponent(Show, { get when() { return rows().tokens; }, @@ -7434,7 +7427,7 @@ function Sidebar(props) { } }) }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return rows().percent; }, @@ -7450,7 +7443,7 @@ function Sidebar(props) { } }) }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return rows().spent; }, @@ -7466,46 +7459,46 @@ function Sidebar(props) { } }) }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return memo(() => !!tuiPrefs().sidebar.context.modelUsage)() && usageRows().length > 0; }, get children() { return [(() => { - var _el$29 = createElement("text"); - insertNode(_el$29, createTextNode(`Session · reported cost`)); - effect((_$p) => setProp(_el$29, "fg", muted(), _$p)); - return _el$29; + var _el$26 = createElement("text"); + insertNode(_el$26, createTextNode(`Session · reported cost`)); + effect((_$p) => setProp(_el$26, "fg", muted(), _$p)); + return _el$26; })(), (() => { - var _el$31 = createElement("text"); - insertNode(_el$31, createTextNode(`Model Tokens USD`)); - effect((_$p) => setProp(_el$31, "fg", muted(), _$p)); - return _el$31; + var _el$28 = createElement("text"); + insertNode(_el$28, createTextNode(`Model Tokens USD`)); + effect((_$p) => setProp(_el$28, "fg", muted(), _$p)); + return _el$28; })()]; } }), null); - insert(_el$28, createComponent(For, { + insert(_el$25, createComponent(For, { get each() { return usageRows(); }, children: (row) => (() => { - var _el$33 = createElement("box"); - setProp(_el$33, "flexDirection", "column"); - insert(_el$33, createComponent(For, { + var _el$30 = createElement("box"); + setProp(_el$30, "flexDirection", "column"); + insert(_el$30, createComponent(For, { get each() { return modelUsageRowLines(row); }, children: (line) => (() => { - var _el$34 = createElement("text"); - insert(_el$34, line); - effect((_$p) => setProp(_el$34, "fg", text(), _$p)); - return _el$34; + var _el$31 = createElement("text"); + insert(_el$31, line); + effect((_$p) => setProp(_el$31, "fg", text(), _$p)); + return _el$31; })() })); - return _el$33; + return _el$30; })() }), null); - insert(_el$28, createComponent(Show, { + insert(_el$25, createComponent(Show, { get when() { return usageHidden(); }, @@ -7514,14 +7507,14 @@ function Sidebar(props) { return sidebarTextLines(line()); }, children: (part) => (() => { - var _el$35 = createElement("text"); - insert(_el$35, part); - effect((_$p) => setProp(_el$35, "fg", muted(), _$p)); - return _el$35; + var _el$32 = createElement("text"); + insert(_el$32, part); + effect((_$p) => setProp(_el$32, "fg", muted(), _$p)); + return _el$32; })() }) }), null); - return _el$28; + return _el$25; })() }), null); insert(_el$16, createComponent(Show, { @@ -7529,10 +7522,10 @@ function Sidebar(props) { return performanceLine(); }, children: (line) => (() => { - var _el$36 = createElement("text"); - insert(_el$36, line); - effect((_$p) => setProp(_el$36, "fg", muted(), _$p)); - return _el$36; + var _el$33 = createElement("text"); + insert(_el$33, line); + effect((_$p) => setProp(_el$33, "fg", muted(), _$p)); + return _el$33; })() }), null); insert(_el$16, createComponent(Show, { @@ -7544,10 +7537,10 @@ function Sidebar(props) { return contextSpendLines(line()); }, children: (part) => (() => { - var _el$37 = createElement("text"); - insert(_el$37, part); - effect((_$p) => setProp(_el$37, "fg", muted(), _$p)); - return _el$37; + var _el$34 = createElement("text"); + insert(_el$34, part); + effect((_$p) => setProp(_el$34, "fg", muted(), _$p)); + return _el$34; })() }) }), null); @@ -7588,22 +7581,22 @@ function Sidebar(props) { return model.branch(); }, children: (value) => (() => { - var _el$38 = createElement("box"), _el$39 = createElement("text"), _el$41 = createElement("text"); - insertNode(_el$38, _el$39); - insertNode(_el$38, _el$41); - setProp(_el$38, "flexDirection", "row"); - insertNode(_el$39, createTextNode(`⎇ `)); - insert(_el$41, () => truncateLabel(value(), 32)); + var _el$35 = createElement("box"), _el$36 = createElement("text"), _el$38 = createElement("text"); + insertNode(_el$35, _el$36); + insertNode(_el$35, _el$38); + setProp(_el$35, "flexDirection", "row"); + insertNode(_el$36, createTextNode(`⎇ `)); + insert(_el$38, () => truncateLabel(value(), 32)); effect((_p$) => { var _v$5 = muted(), _v$6 = text(); - _v$5 !== _p$.e && (_p$.e = setProp(_el$39, "fg", _v$5, _p$.e)); - _v$6 !== _p$.t && (_p$.t = setProp(_el$41, "fg", _v$6, _p$.t)); + _v$5 !== _p$.e && (_p$.e = setProp(_el$36, "fg", _v$5, _p$.e)); + _v$6 !== _p$.t && (_p$.t = setProp(_el$38, "fg", _v$6, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$38; + return _el$35; })() }), null); insert(_el$18, createComponent(Show, { @@ -7611,10 +7604,10 @@ function Sidebar(props) { return model.gitLine(); }, children: (line) => (() => { - var _el$42 = createElement("text"); - insert(_el$42, line); - effect((_$p) => setProp(_el$42, "fg", text(), _$p)); - return _el$42; + var _el$39 = createElement("text"); + insert(_el$39, line); + effect((_$p) => setProp(_el$39, "fg", text(), _$p)); + return _el$39; })() }), null); return _el$18; @@ -7622,14 +7615,14 @@ function Sidebar(props) { }), null); insert(_el$12, createComponent(Show, { get when() { - return block("todo"); + return block("dispatch"); }, get children() { var _el$20 = createElement("box"); setProp(_el$20, "flexDirection", "column"); insert(_el$20, createComponent(Show, { get when() { - return spacer("todo"); + return spacer("dispatch"); }, get children() { var _el$21 = createElement("box"); @@ -7638,77 +7631,13 @@ function Sidebar(props) { } }), null); insert(_el$20, createComponent(Show, { - get when() { - return model.todo().visible.length > 0; - }, - get children() { - var _el$22 = createElement("box"); - setProp(_el$22, "flexDirection", "column"); - insert(_el$22, createComponent(BlockHeader, { - get icon() { - return BLOCK_ICONS.todo; - }, - label: "Todo", - get fg() { - return tone("warning"); - }, - get muted() { - return muted(); - } - }), null); - insert(_el$22, createComponent(For, { - get each() { - return model.todo().visible; - }, - children: (item) => (() => { - var _el$43 = createElement("text"); - insert(_el$43, () => todoRowText(item)); - effect((_$p) => setProp(_el$43, "fg", todoFg(item.status), _$p)); - return _el$43; - })() - }), null); - insert(_el$22, createComponent(Show, { - get when() { - return hiddenTodoText(model.todo().hidden); - }, - children: (line) => (() => { - var _el$44 = createElement("text"); - insert(_el$44, line); - effect((_$p) => setProp(_el$44, "fg", muted(), _$p)); - return _el$44; - })() - }), null); - return _el$22; - } - }), null); - return _el$20; - } - }), null); - insert(_el$12, createComponent(Show, { - get when() { - return block("dispatch"); - }, - get children() { - var _el$23 = createElement("box"); - setProp(_el$23, "flexDirection", "column"); - insert(_el$23, createComponent(Show, { - get when() { - return spacer("dispatch"); - }, - get children() { - var _el$24 = createElement("box"); - setProp(_el$24, "height", 1); - return _el$24; - } - }), null); - insert(_el$23, createComponent(Show, { get when() { return dispatchView(); }, children: (view) => (() => { - var _el$45 = createElement("box"); - setProp(_el$45, "flexDirection", "column"); - insert(_el$45, createComponent(BlockHeader, { + var _el$40 = createElement("box"); + setProp(_el$40, "flexDirection", "column"); + insert(_el$40, createComponent(BlockHeader, { get icon() { return BLOCK_ICONS.dispatch; }, @@ -7723,89 +7652,89 @@ function Sidebar(props) { return dispatchSummary(); } }), null); - insert(_el$45, createComponent(For, { + insert(_el$40, createComponent(For, { get each() { return view().running; }, children: (row) => (() => { - var _el$47 = createElement("box"), _el$48 = createElement("text"); - insertNode(_el$47, _el$48); - setProp(_el$47, "flexShrink", 0); - insert(_el$48, () => row.text); + var _el$42 = createElement("box"), _el$43 = createElement("text"); + insertNode(_el$42, _el$43); + setProp(_el$42, "flexShrink", 0); + insert(_el$43, () => row.text); effect((_p$) => { var _v$7 = open(row.id), _v$8 = tone("success"); - _v$7 !== _p$.e && (_p$.e = setProp(_el$47, "onMouseDown", _v$7, _p$.e)); - _v$8 !== _p$.t && (_p$.t = setProp(_el$48, "fg", _v$8, _p$.t)); + _v$7 !== _p$.e && (_p$.e = setProp(_el$42, "onMouseDown", _v$7, _p$.e)); + _v$8 !== _p$.t && (_p$.t = setProp(_el$43, "fg", _v$8, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$47; + return _el$42; })() }), null); - insert(_el$45, createComponent(Show, { + insert(_el$40, createComponent(Show, { get when() { return view().runningHidden > 0; }, get children() { - var _el$46 = createElement("text"); - insert(_el$46, () => `\u2026 +${view().runningHidden} rodando`); - effect((_$p) => setProp(_el$46, "fg", muted(), _$p)); - return _el$46; + var _el$41 = createElement("text"); + insert(_el$41, () => `\u2026 +${view().runningHidden} rodando`); + effect((_$p) => setProp(_el$41, "fg", muted(), _$p)); + return _el$41; } }), null); - insert(_el$45, createComponent(Show, { + insert(_el$40, createComponent(Show, { get when() { return view().summary; }, children: (line) => (() => { - var _el$49 = createElement("box"), _el$50 = createElement("text"); - insertNode(_el$49, _el$50); - setProp(_el$49, "flexDirection", "row"); - setProp(_el$49, "flexShrink", 0); - insert(_el$50, line); - insert(_el$49, createComponent(Show, { + var _el$44 = createElement("box"), _el$45 = createElement("text"); + insertNode(_el$44, _el$45); + setProp(_el$44, "flexDirection", "row"); + setProp(_el$44, "flexShrink", 0); + insert(_el$45, line); + insert(_el$44, createComponent(Show, { get when() { return failedSuffix(); }, children: (suffix) => (() => { - var _el$51 = createElement("text"); - insert(_el$51, () => `${SPEND_LINE_SEPARATOR}${suffix()}`); - effect((_$p) => setProp(_el$51, "fg", tone("error"), _$p)); - return _el$51; + var _el$46 = createElement("text"); + insert(_el$46, () => `${SPEND_LINE_SEPARATOR}${suffix()}`); + effect((_$p) => setProp(_el$46, "fg", tone("error"), _$p)); + return _el$46; })() }), null); - effect((_$p) => setProp(_el$50, "fg", muted(), _$p)); - return _el$49; + effect((_$p) => setProp(_el$45, "fg", muted(), _$p)); + return _el$44; })() }), null); - insert(_el$45, createComponent(For, { + insert(_el$40, createComponent(For, { get each() { return view().agents; }, children: (row) => (() => { - var _el$52 = createElement("text"); - insert(_el$52, () => childAgentRowText(row)); - effect((_$p) => setProp(_el$52, "fg", muted(), _$p)); - return _el$52; + var _el$47 = createElement("text"); + insert(_el$47, () => childAgentRowText(row)); + effect((_$p) => setProp(_el$47, "fg", muted(), _$p)); + return _el$47; })() }), null); - insert(_el$45, createComponent(Show, { + insert(_el$40, createComponent(Show, { get when() { return hiddenChildAgentsText(view().agentsHidden, view().agentsHiddenCost); }, children: (line) => (() => { - var _el$53 = createElement("text"); - insert(_el$53, line); - effect((_$p) => setProp(_el$53, "fg", muted(), _$p)); - return _el$53; + var _el$48 = createElement("text"); + insert(_el$48, line); + effect((_$p) => setProp(_el$48, "fg", muted(), _$p)); + return _el$48; })() }), null); - return _el$45; + return _el$40; })() }), null); - return _el$23; + return _el$20; } }), null); effect((_p$) => { @@ -7886,25 +7815,25 @@ function DispatchPanel(props) { return model.visible().rows; }, children: (row) => (() => { - var _el$54 = createElement("box"), _el$55 = createElement("text"), _el$56 = createElement("text"); - insertNode(_el$54, _el$55); - insertNode(_el$54, _el$56); - setProp(_el$54, "flexDirection", "row"); - setProp(_el$54, "flexShrink", 0); - insert(_el$55, () => selected(row.id) ? `▸ ` : " "); - insert(_el$56, () => row.text); + var _el$49 = createElement("box"), _el$50 = createElement("text"), _el$51 = createElement("text"); + insertNode(_el$49, _el$50); + insertNode(_el$49, _el$51); + setProp(_el$49, "flexDirection", "row"); + setProp(_el$49, "flexShrink", 0); + insert(_el$50, () => selected(row.id) ? `▸ ` : " "); + insert(_el$51, () => row.text); effect((_p$) => { var _v$9 = selected(row.id) ? text() : muted(), _v$0 = rowFg(row.state), _v$1 = selected(row.id) ? 1 : 0; - _v$9 !== _p$.e && (_p$.e = setProp(_el$55, "fg", _v$9, _p$.e)); - _v$0 !== _p$.t && (_p$.t = setProp(_el$56, "fg", _v$0, _p$.t)); - _v$1 !== _p$.a && (_p$.a = setProp(_el$56, "attributes", _v$1, _p$.a)); + _v$9 !== _p$.e && (_p$.e = setProp(_el$50, "fg", _v$9, _p$.e)); + _v$0 !== _p$.t && (_p$.t = setProp(_el$51, "fg", _v$0, _p$.t)); + _v$1 !== _p$.a && (_p$.a = setProp(_el$51, "attributes", _v$1, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$54; + return _el$49; })() }); const detail = () => createComponent(For, { @@ -7912,28 +7841,28 @@ function DispatchPanel(props) { return model.detail(); }, children: (line, index) => (() => { - var _el$57 = createElement("text"); - insert(_el$57, line); - effect((_$p) => setProp(_el$57, "fg", index() === 0 ? text() : muted(), _$p)); - return _el$57; + var _el$52 = createElement("text"); + insert(_el$52, line); + effect((_$p) => setProp(_el$52, "fg", index() === 0 ? text() : muted(), _$p)); + return _el$52; })() }); const empty = () => (() => { - var _el$58 = createElement("text"); - insertNode(_el$58, createTextNode(`No delegated sessions`)); - effect((_$p) => setProp(_el$58, "fg", muted(), _$p)); - return _el$58; + var _el$53 = createElement("text"); + insertNode(_el$53, createTextNode(`No delegated sessions`)); + effect((_$p) => setProp(_el$53, "fg", muted(), _$p)); + return _el$53; })(); return (() => { - var _el$60 = createElement("box"), _el$61 = createElement("text"), _el$62 = createElement("text"), _el$66 = createElement("box"), _el$67 = createElement("text"); - insertNode(_el$60, _el$61); - insertNode(_el$60, _el$62); - insertNode(_el$60, _el$66); - insertNode(_el$60, _el$67); - setProp(_el$60, "flexDirection", "column"); - setProp(_el$60, "width", "100%"); - setProp(_el$60, "padding", 1); - insert(_el$60, createComponent(DispatchPanelKeymap, { + var _el$55 = createElement("box"), _el$56 = createElement("text"), _el$57 = createElement("text"), _el$61 = createElement("box"), _el$62 = createElement("text"); + insertNode(_el$55, _el$56); + insertNode(_el$55, _el$57); + insertNode(_el$55, _el$61); + insertNode(_el$55, _el$62); + setProp(_el$55, "flexDirection", "column"); + setProp(_el$55, "width", "100%"); + setProp(_el$55, "padding", 1); + insert(_el$55, createComponent(DispatchPanelKeymap, { get context() { return props.context; }, @@ -7941,30 +7870,30 @@ function DispatchPanel(props) { return props.panel; }, model - }), _el$61); - setProp(_el$61, "attributes", 1); - insert(_el$61, () => model.title()); - insert(_el$60, createComponent(Show, { + }), _el$56); + setProp(_el$56, "attributes", 1); + insert(_el$56, () => model.title()); + insert(_el$55, createComponent(Show, { get when() { return model.header(); }, children: (line) => (() => { - var _el$68 = createElement("text"); - insert(_el$68, line); - effect((_$p) => setProp(_el$68, "fg", muted(), _$p)); - return _el$68; + var _el$63 = createElement("text"); + insert(_el$63, line); + effect((_$p) => setProp(_el$63, "fg", muted(), _$p)); + return _el$63; })() - }), _el$62); - insert(_el$62, () => dispatchPanelRule(props.panel.width - 2)); - insert(_el$60, createComponent(Show, { + }), _el$57); + insert(_el$57, () => dispatchPanelRule(props.panel.width - 2)); + insert(_el$55, createComponent(Show, { get when() { return model.layout().mode === "wide"; }, get fallback() { return (() => { - var _el$69 = createElement("box"); - setProp(_el$69, "flexDirection", "column"); - insert(_el$69, createComponent(Show, { + var _el$64 = createElement("box"); + setProp(_el$64, "flexDirection", "column"); + insert(_el$64, createComponent(Show, { get when() { return model.rows().length > 0; }, @@ -7972,34 +7901,34 @@ function DispatchPanel(props) { return empty(); }, get children() { - var _el$70 = createElement("box"); - setProp(_el$70, "flexDirection", "column"); - insert(_el$70, rows); - return _el$70; + var _el$65 = createElement("box"); + setProp(_el$65, "flexDirection", "column"); + insert(_el$65, rows); + return _el$65; } }), null); - insert(_el$69, createComponent(Show, { + insert(_el$64, createComponent(Show, { get when() { return model.selectedID(); }, get children() { - var _el$71 = createElement("box"), _el$72 = createElement("box"); - insertNode(_el$71, _el$72); - setProp(_el$71, "flexDirection", "column"); - setProp(_el$72, "height", 1); - insert(_el$71, detail, null); - return _el$71; + var _el$66 = createElement("box"), _el$67 = createElement("box"); + insertNode(_el$66, _el$67); + setProp(_el$66, "flexDirection", "column"); + setProp(_el$67, "height", 1); + insert(_el$66, detail, null); + return _el$66; } }), null); - return _el$69; + return _el$64; })(); }, get children() { - var _el$63 = createElement("box"), _el$64 = createElement("box"); - insertNode(_el$63, _el$64); - setProp(_el$63, "flexDirection", "row"); - setProp(_el$64, "flexDirection", "column"); - insert(_el$64, createComponent(Show, { + var _el$58 = createElement("box"), _el$59 = createElement("box"); + insertNode(_el$58, _el$59); + setProp(_el$58, "flexDirection", "row"); + setProp(_el$59, "flexDirection", "column"); + insert(_el$59, createComponent(Show, { get when() { return model.rows().length > 0; }, @@ -8010,36 +7939,36 @@ function DispatchPanel(props) { return rows(); } })); - insert(_el$63, createComponent(Show, { + insert(_el$58, createComponent(Show, { get when() { return model.selectedID(); }, get children() { - var _el$65 = createElement("box"); - setProp(_el$65, "flexDirection", "column"); - insert(_el$65, detail); - effect((_$p) => setProp(_el$65, "width", model.layout().detailWidth, _$p)); - return _el$65; + var _el$60 = createElement("box"); + setProp(_el$60, "flexDirection", "column"); + insert(_el$60, detail); + effect((_$p) => setProp(_el$60, "width", model.layout().detailWidth, _$p)); + return _el$60; } }), null); - effect((_$p) => setProp(_el$64, "width", model.layout().listWidth, _$p)); - return _el$63; + effect((_$p) => setProp(_el$59, "width", model.layout().listWidth, _$p)); + return _el$58; } - }), _el$66); - setProp(_el$66, "height", 1); - insert(_el$67, () => model.footer()); + }), _el$61); + setProp(_el$61, "height", 1); + insert(_el$62, () => model.footer()); effect((_p$) => { var _v$10 = text(), _v$11 = muted(), _v$12 = muted(); - _v$10 !== _p$.e && (_p$.e = setProp(_el$61, "fg", _v$10, _p$.e)); - _v$11 !== _p$.t && (_p$.t = setProp(_el$62, "fg", _v$11, _p$.t)); - _v$12 !== _p$.a && (_p$.a = setProp(_el$67, "fg", _v$12, _p$.a)); + _v$10 !== _p$.e && (_p$.e = setProp(_el$56, "fg", _v$10, _p$.e)); + _v$11 !== _p$.t && (_p$.t = setProp(_el$57, "fg", _v$11, _p$.t)); + _v$12 !== _p$.a && (_p$.a = setProp(_el$62, "fg", _v$12, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$60; + return _el$55; })(); } /** App-level command claim: the only way into the panel. It registers the @@ -8096,10 +8025,10 @@ function HomeStatus(props) { return tuiPrefs().footer.home; }, get children() { - var _el$73 = createElement("text"); - insert(_el$73, () => `Pantheon v2.1.5${preset().name ? ` ▸ ${preset().name}` : ""}`); - effect((_$p) => setProp(_el$73, "fg", muted(), _$p)); - return _el$73; + var _el$68 = createElement("text"); + insert(_el$68, () => `Pantheon v2.1.6${preset().name ? ` ▸ ${preset().name}` : ""}`); + effect((_$p) => setProp(_el$68, "fg", muted(), _$p)); + return _el$68; } }); } @@ -8155,10 +8084,10 @@ function PromptFooter(props) { return memo(() => !!tuiPrefs().footer.prompt)() && model.running() > 0; }, get children() { - var _el$74 = createElement("text"); - insert(_el$74, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`); - effect((_$p) => setProp(_el$74, "fg", muted(), _$p)); - return _el$74; + var _el$69 = createElement("text"); + insert(_el$69, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`); + effect((_$p) => setProp(_el$69, "fg", muted(), _$p)); + return _el$69; } }); } diff --git a/src/plugins/tui/dist/tui.js.map b/src/plugins/tui/dist/tui.js.map index 30cf0452..6d62e93c 100644 --- a/src/plugins/tui/dist/tui.js.map +++ b/src/plugins/tui/dist/tui.js.map @@ -1 +1 @@ -{"version":3,"file":"tui.js","names":["numberOrNull","resolveRunningVersion"],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/autonomy-state.ts","../src/decision-router-state.ts","../src/pantheon-settings-state.ts","../src/update-notice.ts","../src/doctor-state.ts","../src/settings-i18n.ts","../src/j1-gate-status.ts","../src/preset-state.ts","../src/tui-prefs.ts","../src/update-status.ts","../src/whats-new-highlights.ts","../src/sidebar-width.ts","../src/whats-new-state.ts","../src/whats-new-open.ts"],"sourcesContent":["/** Shared, data-only formatting and visual helpers for compact context gauges. */\n\nexport type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'\n\nexport const CONTEXT_BAR_CELLS = 12\nexport const CONTEXT_BAR_FILLED_CELL = '\\u25B0'\nexport const CONTEXT_BAR_EMPTY_CELL = '\\u25B1'\n\nexport type BarShape = 'block' | 'line' | 'smooth' | 'ascii' | 'dots' | 'braille'\n\nexport interface BarShapeGlyphs {\n filled: string\n empty: string\n mark?: string\n}\n\nexport const BAR_SHAPES: Record = {\n block: { filled: '\\u25B0', empty: '\\u25B1', mark: '│' },\n line: { filled: '━', empty: '─', mark: '┼' },\n smooth: { filled: '█', empty: '░', mark: '┆' },\n ascii: { filled: '=', empty: '-', mark: '|' },\n dots: { filled: '●', empty: '○', mark: '│' },\n braille: { filled: '⣿', empty: '⣀', mark: '⡇' },\n}\n\nexport interface ContextBarOptions {\n cells?: number\n shape?: BarShape\n evenMark?: boolean\n}\n\nfunction numberOrNull(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nexport function contextUsageTone(percent: number): ContextProgressTone {\n if (percent > 90) return 'error'\n if (percent > 50) return 'warning'\n if (percent > 25) return 'success'\n return 'info'\n}\n\nexport function formatTokenCount(tokens: number | null | undefined): string | null {\n const value = numberOrNull(tokens)\n if (value === null || value < 0) return null\n return Math.round(value).toLocaleString('en-US')\n}\n\nexport function formatContextWindow(limit: number | null | undefined): string | null {\n const value = numberOrNull(limit)\n if (value === null || value <= 0) return null\n if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`\n if (value >= 1_000) return `${Math.floor(value / 1_000)}K`\n return `${Math.floor(value)}`\n}\n\nexport function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {\n const total = Math.max(1, Math.floor(cells))\n const filled = Math.round((percent / 100) * total)\n if (!Number.isFinite(filled)) return 0\n return Math.min(total, Math.max(0, filled))\n}\n\nexport function contextBar(\n percent: number | null | undefined,\n options: number | ContextBarOptions = CONTEXT_BAR_CELLS,\n): { filled: string; empty: string } | null {\n const value = numberOrNull(percent)\n if (value === null) return null\n const total = Math.max(\n 1,\n Math.floor(typeof options === 'number' ? options : (options?.cells ?? CONTEXT_BAR_CELLS)),\n )\n const shapeKey =\n typeof options === 'object' && options?.shape && options.shape in BAR_SHAPES\n ? options.shape\n : 'block'\n const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block\n const evenMark = typeof options === 'object' ? Boolean(options?.evenMark) : false\n\n const filledCount = contextBarFilled(value, total)\n const emptyCount = total - filledCount\n\n if (!evenMark || total < 4) {\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: glyphs.empty.repeat(emptyCount),\n }\n }\n\n // Insert even-use mark at the midpoint (50%)\n const mid = Math.floor(total / 2)\n const mark = glyphs.mark ?? '|'\n\n if (filledCount <= mid) {\n // Mark is in the empty portion\n const emptyBefore = mid - filledCount\n const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1)\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}`,\n }\n }\n\n // Mark is in the filled portion\n const filledBefore = mid\n const filledAfter = Math.max(0, filledCount - filledBefore - 1)\n return {\n filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`,\n empty: glyphs.empty.repeat(emptyCount),\n }\n}\n\nexport function formatSpent(cost: number | null | undefined): string | null {\n const value = numberOrNull(cost)\n if (value === null || value < 0) return null\n return `$${value.toFixed(2)}`\n}\n","/** Shared bounds for cached recent model-usage aggregation. */\nexport const MODEL_USAGE_VISIBLE_CEILING = 3\nexport const MODEL_USAGE_MESSAGE_LIMIT = 400\nexport const MODEL_USAGE_SESSION_LIMIT = 8\n","/**\n * autonomy-state.ts — the Autonomy tab of the settings window.\n *\n * TUI-local copy doctrine. Two surfaces live here:\n *\n * 1. GOAL LOOP — the persisted-mission loop (Wave 3 mechanics) read/written\n * to `options.goal_loop` in the user's opencode.json (the same V2 config\n * copy the context pruner uses). Startup-applied: the runtime resolves it\n * once at plugin setup, so saving requires an OpenCode restart — the tab\n * says so.\n *\n * 2. DECISION BUDGETS — monthly/per-decision USD caps stored in\n * decision-router.json's companion `decision-budget` semantics. The caps\n * the CLI writes via setup-model flags; here they are read from the\n * decision-router.json envelope extension `budget` (v2 superset — the\n * exact-key validator tolerates it via the documented envelope) and\n * applied live per gated call.\n *\n * The decision-gradiente (decide-solo → Jev → human) is DOCUMENTED here, not\n * enforced: J1 owns the risk axis, budgets own the money axis — this tab\n * shows where the thresholds sit today.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\n\nexport interface GoalLoopPrefs {\n enabled: boolean\n cooldownMs: number\n maxContinuations: number\n}\n\nexport const DEFAULT_GOAL_LOOP_PREFS: GoalLoopPrefs = {\n enabled: false,\n cooldownMs: 5000,\n maxContinuations: 25,\n}\n\nexport const GOAL_LOOP_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const MAX_CONTINUATIONS_CYCLE: readonly string[] = Object.freeze([\n '10',\n '25',\n '50',\n '100',\n '200',\n])\n\nexport const COOLDOWN_MS_CYCLE: readonly string[] = Object.freeze(['1000', '2000', '5000', '10000'])\n\nexport interface DecisionBudgets {\n monthlyUsd: number\n perDecisionUsd: number\n}\n\nexport const DEFAULT_DECISION_BUDGETS: DecisionBudgets = {\n monthlyUsd: 5,\n perDecisionUsd: 0.1,\n}\n\n/** Format USD compactly for a cycler cell (\"$5\", \"$0.10\"). */\nexport function formatUsd(value: number): string {\n return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`\n}\n\n/** Build the USD step ladder used by the budget cyclers. */\nexport const MONTHLY_USD_CYCLE: readonly string[] = Object.freeze(\n [1, 2, 5, 10, 20, 50, 100].map((value) => formatUsd(value)),\n)\nexport const PER_DECISION_USD_CYCLE: readonly string[] = Object.freeze(\n [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1].map((value) => formatUsd(value)),\n)\n\n/** Parse a staged USD cell back to a number; junk keeps the input. */\nexport function parseUsd(cell: string): number | null {\n const value = Number(cell.replace('$', ''))\n return Number.isFinite(value) && value > 0 ? value : null\n}\n\nexport function buildAutonomyTab(input: {\n goalLoop: GoalLoopPrefs\n budgets: DecisionBudgets\n goalLoopRestartPending?: boolean | undefined\n languagePref?: string | undefined\n}): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n\n return {\n id: 'autonomy',\n title: isPt ? 'Autonomia' : 'Autonomy',\n groups: [\n {\n title: isPt\n ? 'Loop Contínuo (auto-continuação de sessões multi-turn)'\n : 'Auto-Continue Loop (multi-turn session auto-continuation)',\n rows: [\n {\n id: 'autonomy.goal_loop.enabled',\n name: isPt ? 'Loop Contínuo' : 'Auto-Continue Loop',\n value: input.goalLoop.enabled ? 'enabled' : 'disabled',\n cycle: GOAL_LOOP_ENABLED_CYCLE,\n note: isPt\n ? 'continua tarefas multi-turn quando a sessão fica ociosa' +\n (input.goalLoopRestartPending\n ? ' · [!] reinício necessário para aplicar (restart)'\n : ' · aplicado após reiniciar o OpenCode')\n : 'auto-continues multi-turn tasks when session goes idle' +\n (input.goalLoopRestartPending\n ? ' · [!] restart required to apply'\n : ' · applies after OpenCode restart'),\n },\n {\n id: 'autonomy.goal_loop.maxContinuations',\n name: isPt ? 'Limite continuações' : 'Max continuations',\n value: String(input.goalLoop.maxContinuations),\n cycle: MAX_CONTINUATIONS_CYCLE,\n note: isPt\n ? '1..200 — teto de segurança contra loops infinitos'\n : '1..200 — safety ceiling to prevent runaway tasks',\n },\n {\n id: 'autonomy.goal_loop.cooldownMs',\n name: isPt ? 'Pausa entre turnos (ms)' : 'Cooldown (ms)',\n value: String(input.goalLoop.cooldownMs),\n cycle: COOLDOWN_MS_CYCLE,\n note: isPt\n ? 'intervalo entre turnos autônomos (mín 1000ms)'\n : 'delay between autonomous turns (min 1000ms)',\n },\n ],\n },\n {\n title: isPt ? 'Orçamentos de Decisão (Jev)' : 'Decision Budgets (Jev)',\n rows: [\n {\n id: 'autonomy.budget.monthly',\n name: isPt ? 'Teto Mensal (USD)' : 'Monthly Budget Cap',\n value: formatUsd(input.budgets.monthlyUsd),\n cycle: MONTHLY_USD_CYCLE,\n note: isPt\n ? 'teto mensal em USD para arbitragem do Jev'\n : 'monthly USD ceiling for gated arbitrator decisions',\n },\n {\n id: 'autonomy.budget.perDecision',\n name: isPt ? 'Teto por Consulta' : 'Per-Decision Cap',\n value: formatUsd(input.budgets.perDecisionUsd),\n cycle: PER_DECISION_USD_CYCLE,\n note: isPt\n ? 'teto de custo por decisão — acima disso é recusada'\n : 'price cap — gated decisions above this are refused',\n },\n ],\n },\n {\n title: isPt\n ? 'Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)'\n : 'Decision Gradient (reference policy · governed by J1 & Budgets)',\n rows: [\n {\n id: 'autonomy.gradient.solo',\n name: isPt ? 'Decisão solo' : 'Decide solo',\n value: isPt ? 'autônomo' : 'autonomous',\n note: isPt\n ? 'ações rotineiras de baixo risco · reversível sem travas (sem portão)'\n : 'reversible & low-risk edits, routine fixes (no gate)',\n },\n {\n id: 'autonomy.gradient.jev',\n name: isPt ? 'Decisão Jev' : 'Jev decides',\n value: isPt ? 'arbitrado' : 'arbitrated',\n note: isPt\n ? 'ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima'\n : 'typed ambiguity & candidate ranking · configured via Budgets above',\n },\n {\n id: 'autonomy.gradient.human',\n name: isPt ? 'Aprovação humana' : 'Human decides',\n value: isPt ? 'revisão humana' : 'human review',\n note: isPt\n ? 'ações destrutivas e de alto risco · configurado no limiar do Portão J1'\n : 'high-risk & destructive operations · configured via J1 Gate',\n },\n ],\n },\n ],\n }\n}\n","/**\n * decision-router-state.ts — the Decision Model section of the settings window.\n *\n * TUI-local replica of the user-level decision-router config\n * (scripts/install/decision-router-config.mjs — the bundle must stay\n * self-contained); tests/tui-decision-router-state.test.mjs pins the schema\n * version, the exact key set and the provider matrix against that source.\n *\n * The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts),\n * so a write here applies live — no restart. The strict exact-key schema is\n * load-bearing: any unknown key fail-closes the runtime to disabled/local,\n * so the writer validates before persisting.\n *\n * Egress consent is CLI-owned: the window never writes `egress_consent`, and\n * refuses to enable the router while remote candidates exist without it.\n */\nimport { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\nexport const DECISION_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const DECISION_CONFIG_SCHEMA_VERSION = 2\n\n/** Exact top-level key set — anything else fail-closes the runtime. */\nexport const DECISION_CONFIG_KEYS: readonly string[] = Object.freeze([\n 'egress_consent',\n 'enabled',\n 'enabled_candidates',\n 'schema_version',\n 'selection',\n])\n\nexport type DecisionSelectionMode = 'local' | 'auto' | 'explicit'\n\nexport interface DecisionSelection {\n mode: DecisionSelectionMode\n provider?: string\n model?: string\n}\n\nexport interface DecisionCandidate {\n provider: string\n model: string\n}\n\nexport interface DecisionRouterConfig {\n schema_version: number\n enabled: boolean\n selection: DecisionSelection\n egress_consent: boolean\n enabled_candidates: readonly DecisionCandidate[]\n}\n\nexport const DEFAULT_DECISION_CONFIG: DecisionRouterConfig = Object.freeze({\n schema_version: DECISION_CONFIG_SCHEMA_VERSION,\n enabled: false,\n selection: Object.freeze({ mode: 'local' as const }),\n egress_consent: false,\n enabled_candidates: Object.freeze([]),\n})\n\n/** The runtime's provider→model matrix (drift-pinned against the installer source). */\nexport const DECISION_KNOWN_PROVIDERS: readonly string[] = Object.freeze([\n 'openai-decisions',\n 'typesafe-jev',\n 'opencode-console-jev',\n 'openrouter-jev',\n 'vercel-gateway-jev',\n 'cloudflare-workers-jev',\n])\n\nexport const DECISION_CONSENT_CYCLE: readonly string[] = Object.freeze(['not granted', 'granted'])\n/** provider → model, straight from the runtime matrix (drift-pinned in tests). */\nexport const DECISION_KNOWN_MODELS: Readonly> = Object.freeze({\n 'openai-decisions': 'gpt-6-luna',\n 'typesafe-jev': 'jev-1.14.0',\n 'opencode-console-jev': 'jev-1.13',\n 'openrouter-jev': 'typesafe/jev-1.13',\n 'vercel-gateway-jev': 'typesafe-ai/jev',\n 'cloudflare-workers-jev': 'clef',\n})\n\n/**\n * Credential surface per provider: the ENV VAR the host provider entry reads\n * (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup\n * note. Drift-pinned against the installer/runtime sources in tests.\n */\nexport const DECISION_PROVIDER_CREDENTIALS: Readonly<\n Record\n> = Object.freeze({\n 'openai-decisions': {\n note: 'host-configured model — provision via `decision-router setup-model openai-decisions`',\n notePt: 'modelo do host — configure via `decision-router setup-model openai-decisions`',\n },\n 'typesafe-jev': {\n env: 'TYPESAFE_API_KEY',\n note: 'export TYPESAFE_API_KEY=… then restart',\n notePt: 'export TYPESAFE_API_KEY=… e depois reinicie',\n },\n 'opencode-console-jev': {\n note: 'rides your OpenCode login — no separate key',\n notePt: 'utiliza login do OpenCode — sem chave separada',\n },\n 'openrouter-jev': {\n env: 'OPENROUTER_API_KEY',\n note: 'export OPENROUTER_API_KEY=… then restart',\n notePt: 'export OPENROUTER_API_KEY=… e depois reinicie',\n },\n 'vercel-gateway-jev': {\n env: 'AI_GATEWAY_API_KEY',\n note: 'export AI_GATEWAY_API_KEY=… then restart',\n notePt: 'export AI_GATEWAY_API_KEY=… e depois reinicie',\n },\n 'cloudflare-workers-jev': {\n env: 'CLOUDFLARE_API_TOKEN',\n note: 'needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n notePt: 'requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n },\n})\n\nexport const DECISION_TARGET_CYCLE: readonly string[] = Object.freeze(\n DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`),\n)\n\nexport function decisionRouterConfigPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'pantheon', 'decision-router.json')\n}\n\nexport interface DecisionConfigRead {\n config: DecisionRouterConfig\n /** The file exists but is not a valid v2 config — the runtime fail-closes. */\n corrupt: boolean\n}\n\n/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */\nexport function readDecisionRouterConfig(\n env: Record = process.env,\n): DecisionConfigRead {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return { config: cloneDefault(), corrupt: false }\n }\n return { config: cloneDefault(), corrupt: true }\n }\n if (isValidDecisionConfig(raw)) return { config: raw, corrupt: false }\n return { config: cloneDefault(), corrupt: true }\n}\n\nfunction cloneDefault(): DecisionRouterConfig {\n return {\n schema_version: DEFAULT_DECISION_CONFIG.schema_version,\n enabled: DEFAULT_DECISION_CONFIG.enabled,\n selection: { ...DEFAULT_DECISION_CONFIG.selection },\n egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,\n enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates],\n }\n}\n\n/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */\nexport function isValidDecisionConfig(value: unknown): value is DecisionRouterConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record\n const keys = Object.keys(record).sort()\n if (keys.length !== DECISION_CONFIG_KEYS.length) return false\n for (const key of DECISION_CONFIG_KEYS) {\n if (!keys.includes(key)) return false\n }\n if (record.schema_version !== DECISION_CONFIG_SCHEMA_VERSION) return false\n if (typeof record.enabled !== 'boolean') return false\n if (typeof record.egress_consent !== 'boolean') return false\n if (!isValidSelection(record.selection)) return false\n if (!Array.isArray(record.enabled_candidates)) return false\n for (const candidate of record.enabled_candidates) {\n if (typeof candidate !== 'object' || candidate === null) return false\n const entry = candidate as Record\n if (typeof entry.provider !== 'string' || typeof entry.model !== 'string') return false\n if (Object.keys(entry).length !== 2) return false\n }\n return true\n}\n\nfunction isValidSelection(value: unknown): value is DecisionSelection {\n if (typeof value !== 'object' || value === null) return false\n const selection = value as Record\n if (selection.mode !== 'local' && selection.mode !== 'auto' && selection.mode !== 'explicit') {\n return false\n }\n const keys = Object.keys(selection).sort()\n for (const key of keys) {\n if (key !== 'mode' && key !== 'provider' && key !== 'model') return false\n }\n if (selection.provider !== undefined && typeof selection.provider !== 'string') return false\n if (selection.model !== undefined && typeof selection.model !== 'string') return false\n return true\n}\n\n/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */\nexport function serializeDecisionConfig(config: DecisionRouterConfig): string {\n const ordered = {\n egress_consent: config.egress_consent,\n enabled: config.enabled,\n enabled_candidates: config.enabled_candidates.map((candidate) => ({\n model: candidate.model,\n provider: candidate.provider,\n })),\n schema_version: config.schema_version,\n selection: {\n mode: config.selection.mode,\n ...(config.selection.model !== undefined ? { model: config.selection.model } : {}),\n ...(config.selection.provider !== undefined ? { provider: config.selection.provider } : {}),\n },\n }\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n/**\n * Enable/disable the router in a config copy. The guard mirrors the runtime's\n * fail-close: with remote candidates and no egress consent, an enabled flag\n * would be a lie — enabling requires consent, or a local-only selection.\n * Never touches `egress_consent` (CLI-owned).\n */\nexport function setDecisionEnabled(\n config: DecisionRouterConfig,\n enabled: boolean,\n): { ok: true; config: DecisionRouterConfig } | { ok: false; reason: string } {\n if (enabled) {\n const localOnly = config.selection.mode === 'local' || config.enabled_candidates.length === 0\n if (!localOnly && !config.egress_consent) {\n return {\n ok: false,\n reason:\n 'remote candidates need egress consent — toggle Egress consent in this tab, then enable',\n }\n }\n }\n return { ok: true, config: { ...config, enabled } }\n}\n\n/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */\nexport function writeDecisionRouterConfig(\n config: DecisionRouterConfig,\n env: Record = process.env,\n): void {\n if (!isValidDecisionConfig(config)) {\n throw new TypeError('Refusing to persist an invalid decision-router configuration')\n }\n const path = decisionRouterConfigPath(env)\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, serializeDecisionConfig(config), { mode: 0o600 })\n renameSync(temp, path)\n chmodSync(path, 0o600)\n}\n\nexport const DECISION_SELECTION_CYCLE: readonly string[] = Object.freeze([\n 'local',\n 'auto',\n 'explicit',\n])\n\n/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */\nexport function applyDecisionRow(\n config: DecisionRouterConfig,\n id: string,\n value: string,\n): DecisionRouterConfig {\n const next: DecisionRouterConfig = {\n ...config,\n selection: { ...config.selection },\n enabled_candidates: [...config.enabled_candidates],\n }\n switch (id) {\n case 'decision.selection.mode': {\n const mode = value as DecisionSelectionMode\n if (mode !== 'local' && mode !== 'auto' && mode !== 'explicit') return config\n next.selection.mode = mode\n if (mode === 'local') next.enabled_candidates = []\n return next\n }\n case 'decision.selection.target': {\n const separator = value.indexOf('/')\n if (separator <= 0) return config\n const provider = value.slice(0, separator)\n const model = value.slice(separator + 1)\n if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config\n if (DECISION_KNOWN_MODELS[provider] !== model) return config\n next.selection = { mode: 'explicit', provider, model }\n next.enabled_candidates = [{ provider, model }]\n return next\n }\n case 'decision.consent': {\n next.egress_consent = value === 'granted'\n return next\n }\n default:\n return config\n }\n}\n\n/** The host's provider auth store (`opencode auth login` writes here). */\nexport function decisionAuthStorePath(env: Record = process.env) {\n const xdgData = env.XDG_DATA_HOME\n const home = env.HOME ?? ''\n const root = xdgData ?? join(home, '.local', 'share')\n return join(root, 'opencode', 'auth.json')\n}\n\n/** Provider ids as they appear in the host auth store / config providers. */\nconst PROVIDER_AUTH_NAMES: Readonly> = Object.freeze({\n 'openai-decisions': Object.freeze(['openai']),\n 'typesafe-jev': Object.freeze(['typesafe-ai']),\n 'opencode-console-jev': Object.freeze([]),\n 'openrouter-jev': Object.freeze(['openrouter']),\n 'vercel-gateway-jev': Object.freeze(['vercel-ai-gateway', 'vercel']),\n 'cloudflare-workers-jev': Object.freeze(['cloudflare-workers-ai']),\n})\n\nexport type CredentialForm = 'env' | 'auth store' | 'config' | 'missing'\n\n/**\n * TWO recognition forms (field feedback beta.6: keys registered via\n * `opencode auth login` showed MISSING because only env vars were checked):\n * env var set → 'env'; provider present in the host auth store → 'auth\n * store'; provider entry in opencode.json providers → 'config'. Values are\n * NEVER read — existence only.\n */\nexport function credentialStatus(\n provider: string,\n env: Record,\n authProviders: ReadonlySet,\n configProviders: ReadonlySet,\n): CredentialForm {\n const credential = DECISION_PROVIDER_CREDENTIALS[provider]\n if (credential?.env !== undefined && env[credential.env]) return 'env'\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (authProviders.has(name)) return 'auth store'\n }\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (configProviders.has(name)) return 'config'\n }\n if (provider === 'opencode-console-jev') return 'auth store'\n return 'missing'\n}\n\nexport function buildDecisionTab(\n read: DecisionConfigRead,\n env: Record = process.env,\n authProviders: ReadonlySet = new Set(),\n configProviders: ReadonlySet = new Set(),\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const { config, corrupt } = read\n const rows: SettingsRow[] = [\n {\n id: 'decision.enabled',\n name: isPt ? 'Assistente Jev' : 'Jev Assistant',\n value: config.enabled ? 'enabled' : 'disabled',\n // Corrupt config → read-only; the notice (glue) carries the remedy.\n ...(corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }),\n note: corrupt\n ? isPt\n ? 'config inválida — runtime fail-closes; repare via `decision-router setup-model`'\n : 'config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`'\n : isPt\n ? 'aplica em tempo real — arbitragem de decisões relida a cada chamada'\n : 'applies live — the runtime re-reads this on every gated call',\n },\n {\n id: 'decision.selection.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: config.selection.mode,\n ...(corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }),\n note: isPt\n ? 'local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)'\n : 'local routes on-device; auto/explicit pick a remote decision model',\n },\n ]\n\n // Model selection row: always visible so the user can choose the decision model\n const explicitTarget = config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : (DECISION_TARGET_CYCLE[0] ?? 'openrouter-jev/typesafe/jev-1.13')\n rows.push({\n id: 'decision.selection.target',\n name: isPt ? 'Modelo de Decisão' : 'Decision Model',\n value:\n config.selection.mode === 'local'\n ? config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : 'local (on-device)'\n : explicitTarget,\n ...(corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }),\n note: isPt\n ? config.selection.mode === 'local'\n ? 'ciclar seleciona modelo remoto e ativa modo explícito'\n : 'provedor/modelo ativo — define candidato para arbitragem'\n : config.selection.mode === 'local'\n ? 'cycle to select a remote model and activate explicit mode'\n : 'provider/model — sets the candidate list',\n })\n\n if ((config.enabled_candidates?.length ?? 0) > 0) {\n rows.push({\n id: 'decision.candidates',\n name: isPt ? 'Candidatos ativos' : 'Candidates',\n value: String(config.enabled_candidates.length),\n note: config.egress_consent\n ? config.enabled_candidates\n .map((candidate) => `${candidate.provider}/${candidate.model}`)\n .join(', ')\n : isPt\n ? 'egress consent NÃO concedido — rotas remotas bloqueadas'\n : 'egress consent NOT granted — remote routes fail closed',\n })\n }\n\n rows.push({\n id: 'decision.consent',\n name: isPt ? 'Acesso à Nuvem' : 'Cloud API Access',\n value: config.egress_consent ? 'granted' : 'not granted',\n ...(corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }),\n note: isPt\n ? config.egress_consent\n ? 'granted = rotas remotas podem consultar gateway de API (com teto de custo)'\n : 'not granted = chamadas remotas bloqueadas; requer granted para nuvem'\n : config.egress_consent\n ? 'granted = remote decision routes may call their gateway (budget-capped)'\n : 'not granted = remote routes fail closed; grant to allow cloud calls',\n })\n\n return {\n id: 'decision',\n title: isPt ? 'Decisão' : 'Decision',\n groups: [\n { title: isPt ? 'Assistente de Decisão (Jev)' : 'Decision Assistant (Jev)', rows },\n {\n title: isPt\n ? 'Credenciais (status apenas — valores nunca gravados na janela)'\n : 'Credentials (status only — values never enter the window)',\n rows: DECISION_KNOWN_PROVIDERS.map((provider) => {\n const status = credentialStatus(provider, env, authProviders, configProviders)\n const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: '' }\n return {\n id: `decision.key.${provider}`,\n name: provider,\n value: status === 'missing' ? 'MISSING' : status,\n note: isPt ? (credential.notePt ?? credential.note) : credential.note,\n }\n }),\n },\n ],\n }\n}\n","/**\n * pantheon-settings-state.ts — the pure state core of the settings window.\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. The behaviors registry mirrors routing.yml's `behaviors:`\n * (drift-pinned by tests/pantheon-settings-state.test.mjs).\n *\n * Model (2.0.0-beta.4, the quota-style full window): the window is a set of\n * TABS; each tab holds GROUPS of setting ROWS; a row carries a display VALUE\n * and — when the setting is editable — the CYCLE of allowed values that\n * ←/→ steps through. Edits stage into a DRAFT (id → pending value); `save`\n * applies the draft through injected writers, `reset` drops it. The disk\n * never changes before save.\n */\n\nexport interface SettingsBehavior {\n id: string\n kind: 'install' | 'runtime'\n title: string\n description: string\n}\n\n/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */\nexport const SETTINGS_BEHAVIORS: readonly SettingsBehavior[] = Object.freeze([\n {\n id: 'skill-auto-continue',\n kind: 'install',\n title: 'Auto-continue skill',\n description: 'Continue multi-step todos while keeping safety gates.',\n },\n {\n id: 'skill-tdd-with-agents',\n kind: 'install',\n title: 'TDD with agents skill',\n description: 'RED, GREEN, REFACTOR test-driven implementation.',\n },\n {\n id: 'skill-code-review-checklist',\n kind: 'install',\n title: 'Code review checklist skill',\n description: 'Systematic code review and quality gates.',\n },\n {\n id: 'skill-prompt-refinery',\n kind: 'install',\n title: 'Prompt refinery skill',\n description: 'Vague requests refined — silent adjust, >> full contract.',\n },\n {\n id: 'gate-idle-todo-enforcer',\n kind: 'runtime',\n title: 'Idle todo enforcer',\n description: 'Continues pending todos when a session goes idle.',\n },\n {\n id: 'gate-context-pruner',\n kind: 'runtime',\n title: 'Context pruner',\n description: 'Prunes repeated tool output before summarization.',\n },\n {\n id: 'gate-j1-risk-gate',\n kind: 'runtime',\n title: 'J1 risk gate',\n description: 'High-risk tool calls demand explicit human approval.',\n },\n])\n\nexport interface OverrideEntry {\n action: 'disable' | 'replace'\n content?: string\n reason?: string\n}\n\nexport type EffectiveOverrides = Record\n\n/** Which behaviors the settings window can write (runtime + install skills). */\nexport const SETTINGS_TOGGLABLE_IDS = new Set(SETTINGS_BEHAVIORS.map((b) => b.id))\n\nexport function isBehaviorDisabled(effective: EffectiveOverrides, id: string): boolean {\n return effective[id]?.action === 'disable'\n}\n\nexport const TOGGLE_REASON = 'toggled in /pantheon-settings'\n\n/**\n * Toggle (a targeted write keeps the toggle semantics: a `replace` entry is\n * never destroyed — disabling keeps its `content`, re-enabling restores the\n * replace; a settings-written disable is removed outright, no toggle noise).\n */\nexport function toggledOverrides(\n effective: EffectiveOverrides,\n id: string,\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const next: EffectiveOverrides = { ...effective }\n const entry = next[id]\n if (entry?.action === 'disable') {\n if (entry.content !== undefined) {\n next[id] =\n entry.reason === reason\n ? { action: 'replace', content: entry.content }\n : {\n action: 'replace',\n content: entry.content,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n }\n } else {\n delete next[id]\n }\n } else {\n next[id] =\n entry?.content !== undefined\n ? { action: 'disable', reason, content: entry.content }\n : { action: 'disable', reason }\n }\n return next\n}\n\n/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */\nexport function setOverrideState(\n effective: EffectiveOverrides,\n id: string,\n target: 'enabled' | 'disabled',\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const disabled = isBehaviorDisabled(effective, id)\n if ((target === 'disabled') === disabled) return effective\n return toggledOverrides(effective, id, reason)\n}\n\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n// ── Overrides load (global + project files) ────────────────────────────\n\nexport interface OverridesLoad {\n global: EffectiveOverrides\n project: EffectiveOverrides\n /** The GLOBAL file exists but does not parse — writes are refused. */\n corruptGlobal: boolean\n}\n\n/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */\nexport function mergedOverrides(load: OverridesLoad): EffectiveOverrides {\n return { ...load.global, ...load.project }\n}\n\nexport function canWriteOverrides(load: OverridesLoad): boolean {\n return !load.corruptGlobal\n}\n\n// ── Tab / group / row model (the cycler window) ────────────────────────\n\nexport interface SettingsRow {\n id: string\n name: string\n /** Current effective value (display); the staged draft may differ. */\n value: string\n /** Allowed values for ←/→; presence marks the row as editable. */\n cycle?: readonly string[]\n /** The row's DEFAULT value — what the Defaults action stages. */\n def?: string\n /** Right-column note (writes-where, applies-live, from-where). */\n note?: string\n /** Enter triggers this action instead of cycling (e.g. `update-check`). */\n action?: string\n}\n\nexport interface SettingsGroup {\n /** Bold group header; undefined renders rows without a header. */\n title?: string\n rows: SettingsRow[]\n}\n\nexport interface SettingsTab {\n id: string\n title: string\n groups: SettingsGroup[]\n}\n\n/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */\nexport const EMPTY_TAB: SettingsTab = { id: 'empty', title: '', groups: [] }\n\n/** Flat, in-order rows of a tab (the up/down navigation space). */\nexport function tabRows(tab: SettingsTab): SettingsRow[] {\n return tab.groups.flatMap((group) => group.rows)\n}\n\nexport function findRow(tab: SettingsTab, id: string): SettingsRow | undefined {\n return tabRows(tab).find((row) => row.id === id)\n}\n\n// ── The cycler ─────────────────────────────────────────────────────────\n\n/** Step through the cycle with wrap-around; non-cyclable rows return the input. */\nexport function cycleValue(value: string, cycle: readonly string[], direction: 1 | -1): string {\n if (cycle.length === 0) return value\n const index = cycle.indexOf(value)\n if (index === -1) return cycle[0] ?? value\n const next = (index + direction + cycle.length) % cycle.length\n return cycle[next] ?? value\n}\n\n// ── The draft (staged edits; the disk never changes before save) ───────\n\nexport type SettingsDraft = Record\n\nexport function stageValue(\n draft: SettingsDraft,\n row: SettingsRow,\n direction: 1 | -1,\n): SettingsDraft {\n if (row.cycle === undefined) return draft\n const current = draft[row.id] ?? row.value\n const staged = cycleValue(current, row.cycle, direction)\n if (staged === row.value) {\n // staged back onto the disk value — drop the entry (no toggle noise)\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: staged }\n}\n\n/** Stage an explicit target value for one row (the Defaults action path). */\nexport function stageRowToValue(\n draft: SettingsDraft,\n row: SettingsRow,\n target: string,\n): SettingsDraft {\n if (!row.cycle?.includes(target)) return draft\n if (target === row.value) {\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: target }\n}\n\n/**\n * Stage every cyclable row's DEFAULT value of a tab. Rows already at their\n * default have their staged entry dropped; rows staged elsewhere keep it\n * until the Defaults action targets them.\n */\nexport function stageDefaults(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n let next = draft\n for (const row of tabRows(tab)) {\n if (row.cycle === undefined || row.def === undefined) continue\n const candidate = next[row.id] ?? row.value\n if (candidate === row.def) {\n if (next[row.id] !== undefined) {\n const copy = { ...next }\n delete copy[row.id]\n next = copy\n }\n continue\n }\n next = stageRowToValue(next, { ...row, value: candidate }, row.def)\n }\n return next\n}\n\n/** Drop every staged entry of one tab (ctrl+r). */\nexport function resetTab(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n const ids = new Set(tabRows(tab).map((row) => row.id))\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!ids.has(id)) next[id] = value\n }\n return next\n}\n\nexport function draftCount(draft: SettingsDraft): number {\n return Object.keys(draft).length\n}\n\nexport function draftDirty(draft: SettingsDraft): boolean {\n return draftCount(draft) > 0\n}\n\nexport function tabDirty(draft: SettingsDraft, tab: SettingsTab): boolean {\n return tabRows(tab).some((row) => draft[row.id] !== undefined)\n}\n\n// ── Applying the draft ─────────────────────────────────────────────────\n\nexport interface DraftWriterResult {\n ok: boolean\n reason?: string\n}\n\n/**\n * One callback that dispatches a staged row to its real writer (gates →\n * overrides file, decision → decision-router.json, preset → active-preset).\n *Injected by the glue so the disk never runs in tests.\n */\nexport type DraftWriter = (id: string, value: string) => DraftWriterResult\n\nexport interface AppliedDraft {\n applied: string[]\n failed: { id: string; reason: string }[]\n}\n\n/** Apply every staged entry; failures are collected, never thrown. */\nexport function applyDraft(draft: SettingsDraft, writer: DraftWriter): AppliedDraft {\n const applied: string[] = []\n const failed: AppliedDraft['failed'] = []\n for (const [id, value] of Object.entries(draft)) {\n const result = writer(id, value)\n if (result.ok) applied.push(id)\n else failed.push({ id, reason: result.reason ?? 'write failed' })\n }\n return { applied, failed }\n}\n\n/** The rows that succeeded and are still in the draft (failed ones stay staged). */\nexport function settledDraft(draft: SettingsDraft, applied: readonly string[]): SettingsDraft {\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!applied.includes(id)) next[id] = value\n }\n return next\n}\n\n// ── Gates / About tabs (behavior-native; the other tabs live in their modules) ──\n\nexport const GATES_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport function buildGatesTab(load: OverridesLoad, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const merged = mergedOverrides(load)\n const rowFor = (behavior: SettingsBehavior): SettingsRow => {\n const fromProject = load.project[behavior.id] !== undefined\n const writable = !fromProject && canWriteOverrides(load)\n return {\n id: `gate.${behavior.id}`,\n name: fromProject ? `${behavior.title} (${isPt ? 'projeto' : 'project'})` : behavior.title,\n value: isBehaviorDisabled(merged, behavior.id) ? 'disabled' : 'enabled',\n ...(writable ? { cycle: GATES_ENABLED_CYCLE } : {}),\n note: fromProject\n ? isPt\n ? 'arquivo do projeto tem precedência · edite .pantheon/overrides.json'\n : 'project file wins at runtime — edit .pantheon/overrides.json'\n : behavior.description,\n }\n }\n const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'install')\n const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'runtime')\n return {\n id: 'gates',\n title: 'Gates',\n groups: [\n { title: isPt ? 'Skills instaladas' : 'Install skills', rows: install.map(rowFor) },\n { title: isPt ? 'Portões de execução' : 'Runtime gates', rows: runtime.map(rowFor) },\n ],\n }\n}\n\nexport interface AboutTabExtra {\n nodeVersion?: string\n platform?: string\n preset?: string | null\n decisionEnabled?: boolean\n j1Mode?: string\n languagePref?: string\n}\n\nexport function buildAboutTab(version: string, extra?: AboutTabExtra): SettingsTab {\n const isPt = extra?.languagePref === 'pt-BR'\n\n const sysRows: SettingsRow[] = [\n {\n id: 'about.version',\n name: isPt ? 'Versão' : 'Version',\n value: `v${version}`,\n note: isPt\n ? 'OpenCode 2.x nativo — contrato V1 descontinuado'\n : 'OpenCode 2.x only — the V1 contract is removed',\n },\n {\n id: 'about.behaviors',\n name: isPt ? 'Comportamentos' : 'Behaviors',\n value: String(SETTINGS_BEHAVIORS.length),\n note: isPt\n ? 'portões e skills de governança registradas'\n : 'registered governance gates and skills',\n },\n ]\n\n if (extra?.nodeVersion) {\n sysRows.push({\n id: 'about.runtime',\n name: 'Runtime Node.js',\n value: `v${extra.nodeVersion}`,\n note: extra.platform ? `${isPt ? 'plataforma' : 'platform'}: ${extra.platform}` : '',\n })\n }\n\n const govRows: SettingsRow[] = [\n {\n id: 'about.preset',\n name: isPt ? 'Predefinição' : 'Active Preset',\n value: extra?.preset ?? 'none',\n note: isPt ? 'modelo global ativo do Pantheon' : 'global model preset active in Pantheon',\n },\n {\n id: 'about.decision',\n name: isPt ? 'Assistente Jev' : 'Decision Router',\n value: extra?.decisionEnabled\n ? isPt\n ? 'ativado'\n : 'enabled'\n : isPt\n ? 'desativado'\n : 'disabled',\n note: isPt ? 'arbitragem de modelos e candidatos' : 'model and candidate arbitration',\n },\n {\n id: 'about.j1',\n name: isPt ? 'Portão J1' : 'J1 Risk Gate',\n value: extra?.j1Mode ?? 'shadow',\n note: isPt\n ? 'portão de risco de segurança operacional'\n : 'operational safety risk score gate',\n },\n ]\n\n const refRows: SettingsRow[] = [\n {\n id: 'about.license',\n name: isPt ? 'Licença' : 'License',\n value: 'MIT',\n note: 'Open source · Pantheon Project',\n },\n {\n id: 'about.repo',\n name: isPt ? 'Repositório' : 'Repository',\n value: 'ils15/pantheon-opencode',\n note: 'github.com/ils15/pantheon-opencode',\n },\n ]\n\n const groups = [{ title: isPt ? 'Sistema & Plataforma' : 'System & Platform', rows: sysRows }]\n if (extra?.preset !== undefined || extra?.decisionEnabled !== undefined) {\n groups.push({ title: isPt ? 'Governança & Roteamento' : 'Governance & Routing', rows: govRows })\n }\n groups.push({ title: isPt ? 'Projeto & Referências' : 'Project & References', rows: refRows })\n\n return {\n id: 'about',\n title: isPt ? 'Sobre' : 'About',\n groups,\n }\n}\n\nexport interface ChangelogHighlightItem {\n title: string\n detail: string\n group?: string | undefined\n}\n\nexport function buildChangelogTab(\n version: string,\n items: ChangelogHighlightItem[] = [],\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n\n const rows: SettingsRow[] = []\n if (items.length > 0) {\n items.forEach((item, index) => {\n rows.push({\n id: `changelog.item.${index + 1}`,\n name: item.title.slice(0, 26),\n value: '',\n note: item.detail,\n })\n })\n } else {\n rows.push({\n id: 'changelog.info',\n name: isPt ? 'Versão' : 'Release',\n value: `v${version}`,\n note: isPt\n ? 'veja o histórico completo no CHANGELOG.md ou no GitHub'\n : 'view full history in CHANGELOG.md or GitHub releases',\n })\n }\n\n return {\n id: 'changelog',\n title: isPt ? 'Changelog' : 'Changelog',\n groups: [\n {\n title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`,\n rows,\n },\n {\n title: isPt ? 'Referências de Versão' : 'Release References',\n rows: [\n {\n id: 'changelog.docs',\n name: isPt ? 'Documentação' : 'Documentation',\n value: 'CHANGELOG.md',\n note: isPt\n ? 'incluído na raiz do plugin e do repositório'\n : 'shipped at plugin root and repository root',\n },\n {\n id: 'changelog.repo',\n name: isPt ? 'Repositório GitHub' : 'GitHub Repository',\n value: 'ils15/pantheon-opencode',\n note: isPt\n ? 'versões, pull requests e discussões'\n : 'releases, pull requests and discussion',\n },\n ],\n },\n ],\n }\n}\n","/**\n * Update notifier core (TUI-local copy — the bundle must stay self-contained,\n * same precedent as cost-data.ts/model-pricing.ts).\n *\n * Pin + notify, never silent auto-update: one notice per newer version,\n * TTL-cached, offline-safe, and a stable install is never advertised a beta\n * (the update guard owns that crossing). docs/design/2.0-settings-and-install.md\n */\n\nexport const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000\n\nexport interface UpdateCheckState {\n /** Last version a notice was surfaced for (no repeats per version). */\n lastNotifiedVersion?: string\n /** Last time the registry was queried, for the TTL. */\n lastCheckMs?: number\n}\n\nexport interface UpdateNoticeInput {\n currentVersion: string\n latestVersion: string\n state?: UpdateCheckState\n nowMs?: number\n ttlMs?: number\n}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\n/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */\nexport function comparePantheonVersions(left: string, right: string): number {\n const parse = (version: string) => {\n const match = String(version)\n .trim()\n .match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-(beta|rc)\\.(\\d+))?$/)\n if (!match) return null\n const [, major = '', minor = '', patch = '', stage = '', stageNum = ''] = match\n const stageRank = stage === 'beta' ? 1 : stage === 'rc' ? 2 : 3\n return {\n core: [+major, +minor, +patch] as [number, number, number],\n stageRank,\n stageNum: stage !== '' ? +stageNum : Number.POSITIVE_INFINITY,\n }\n }\n const a = parse(left)\n const b = parse(right)\n if (!a || !b) return 0\n const [aMajor, aMinor, aPatch] = a.core\n const [bMajor, bMinor, bPatch] = b.core\n if (aMajor !== bMajor) return aMajor - bMajor\n if (aMinor !== bMinor) return aMinor - bMinor\n if (aPatch !== bPatch) return aPatch - bPatch\n if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank\n return a.stageNum - b.stageNum\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now() } = input\n const ttlMs = input.ttlMs ?? UPDATE_CHECK_TTL_MS\n\n const lastCheck = state.lastCheckMs ?? 0\n if (nowMs - lastCheck < ttlMs) return null\n if (state.lastNotifiedVersion === latestVersion) return null\n\n const stable = (version: string) => !/-(?:beta|rc)\\.\\d+$/.test(version)\n // A stable install is never advertised a beta: the update guard owns that\n // crossing and requires explicit opt-in there.\n if (stable(currentVersion) && !stable(latestVersion)) return null\n\n if (comparePantheonVersions(latestVersion, currentVersion) <= 0) return null\n\n return {\n version: latestVersion,\n message:\n `pantheon-opencode ${latestVersion} available — ` +\n 'changelog in /pantheon-settings, adopt with `pantheon-opencode update`',\n }\n}\n\n/** The state to persist after a check (notified or not) for the TTL. */\nexport function nextCheckState(\n previous: UpdateCheckState,\n notice: UpdateNotice | null,\n nowMs: number,\n): UpdateCheckState {\n const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion\n return {\n lastCheckMs: nowMs,\n ...(lastNotifiedVersion !== undefined ? { lastNotifiedVersion } : {}),\n }\n}\n","/**\n * doctor-state.ts — the Doctor section of the settings window (read-only).\n *\n * TUI-local replica (the bundle must stay self-contained — the installed copy\n * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only\n * the FILE-DERIVABLE checks are mirrored here; everything that spawns\n * processes, reads the network, or writes (MCP smoke, python validators, git,\n * venv pins, --fix quarantines) stays in the CLI and the section says so.\n *\n * The install-state path mirrors doctor's checkInstallVersionDrift\n * (`/opencode/.pantheon/install-state.json`); the Node floor is\n * drift-pinned against scripts/node-engine-policy.mjs by\n * tests/tui-doctor-state.test.mjs.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { readDecisionRouterConfig } from './decision-router-state.ts'\nimport type { OverridesLoad } from './pantheon-settings-state.ts'\nimport {\n SETTINGS_BEHAVIORS,\n type SettingsRow,\n type SettingsTab,\n} from './pantheon-settings-state.ts'\nimport { comparePantheonVersions } from './update-notice.ts'\n\n/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */\nexport const MIN_SUPPORTED_NODE_VERSION = '26.4.0'\n\nexport function opencodePantheonDir(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon')\n}\n\nexport interface InstallVersionHealth {\n status: 'ok' | 'older' | 'newer' | 'unknown'\n installed: string | null\n}\n\n/**\n * H2: the installed package version (install-state) vs the running one.\n * Fail-open: a missing/unreadable state file means \"unknown\", not a failure —\n * pre-2.0 installs may not have one.\n */\nexport function classifyInstallVersion(\n runningVersion: string,\n env: Record = process.env,\n): InstallVersionHealth {\n let installed: string | null = null\n try {\n const path = join(opencodePantheonDir(env), 'install-state.json')\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { pantheon_version?: unknown }\n if (typeof raw?.pantheon_version === 'string' && raw.pantheon_version !== '') {\n installed = raw.pantheon_version\n }\n } catch {\n installed = null\n }\n if (installed === null) return { status: 'unknown', installed: null }\n const compared = comparePantheonVersions(installed, runningVersion)\n if (compared === 0) return { status: 'ok', installed }\n return { status: compared < 0 ? 'older' : 'newer', installed }\n}\n\nexport function isSupportedNodeFloor(version: string): boolean {\n // Same shape as the canonical parser: a prerelease is outside the floor.\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([^+]+))?(?:\\+([\\w.-]+))?$/.exec(String(version))\n const minimum = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(MIN_SUPPORTED_NODE_VERSION)\n if (!match || !minimum) return false\n const [, major = '', minor = '', patch = '', prerelease = ''] = match\n if (prerelease !== '') return false\n const [, minMajor = '0', minMinor = '0', minPatch = '0'] = minimum\n const currentParts = [+major, +minor, +patch]\n const minimumParts = [+minMajor, +minMinor, +minPatch]\n for (let index = 0; index < 3; index += 1) {\n const currentPart = currentParts[index] ?? 0\n const minimumPart = minimumParts[index] ?? 0\n if (currentPart !== minimumPart) return currentPart > minimumPart\n }\n return true\n}\n\nexport interface OverridesHealth {\n status: 'clean' | 'unknown-ids' | 'corrupt'\n unknownIds: string[]\n}\n\n/** K: validate both overrides files against the window's registry. */\nexport function classifyOverridesHealth(load: OverridesLoad): OverridesHealth {\n if (load.corruptGlobal) return { status: 'corrupt', unknownIds: [] }\n const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id))\n const unknownIds = Object.keys({ ...load.global, ...load.project }).filter((id) => !known.has(id))\n return { status: unknownIds.length > 0 ? 'unknown-ids' : 'clean', unknownIds }\n}\n\nexport interface DecisionConfigHealth {\n status: 'ok' | 'corrupt' | 'absent'\n}\n\nexport function classifyDecisionConfigHealth(\n env: Record = process.env,\n): DecisionConfigHealth {\n if (\n !existsSync(\n join(\n env.XDG_CONFIG_HOME ?? join(env.HOME ?? '', '.config'),\n 'pantheon',\n 'decision-router.json',\n ),\n )\n ) {\n return { status: 'absent' }\n }\n return readDecisionRouterConfig(env).corrupt ? { status: 'corrupt' } : { status: 'ok' }\n}\n\nexport interface DoctorSectionInput {\n runningVersion: string\n nodeVersion: string\n load: OverridesLoad\n env?: Record\n}\n\nexport function buildDoctorTab(input: DoctorSectionInput): SettingsTab {\n const env = input.env ?? process.env\n const rows: SettingsRow[] = []\n\n const version = classifyInstallVersion(input.runningVersion, env)\n rows.push({\n id: 'doctor.version',\n name: 'Install version',\n value:\n version.status === 'ok'\n ? `v${version.installed} — matches`\n : version.status === 'older'\n ? `v${version.installed} older`\n : version.status === 'newer'\n ? `v${version.installed} newer`\n : 'unknown',\n note:\n version.status === 'older'\n ? 'refresh with `pantheon-opencode update`'\n : 'read from /opencode/.pantheon/install-state.json',\n })\n\n const nodeOk = isSupportedNodeFloor(input.nodeVersion)\n rows.push({\n id: 'doctor.node',\n name: 'Node runtime',\n value: input.nodeVersion.replace(/^v/, ''),\n note: nodeOk\n ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`\n : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,\n })\n\n const overrides = classifyOverridesHealth(input.load)\n rows.push({\n id: 'doctor.overrides',\n name: 'Overrides',\n value:\n overrides.status === 'clean'\n ? 'valid'\n : overrides.status === 'corrupt'\n ? 'unreadable'\n : `${overrides.unknownIds.length} unknown id(s)`,\n note:\n overrides.status === 'unknown-ids'\n ? `${overrides.unknownIds.join(', ')} — harmless; repair with doctor --fix`\n : overrides.status === 'corrupt'\n ? 'writes are refused until repaired (doctor --fix)'\n : 'both files parse against the behavior registry',\n })\n\n const decision = classifyDecisionConfigHealth(env)\n rows.push({\n id: 'doctor.decision',\n name: 'Decision config',\n value:\n decision.status === 'ok' ? 'valid' : decision.status === 'corrupt' ? 'corrupt' : 'absent',\n note:\n decision.status === 'corrupt'\n ? 'runtime fail-closes to disabled · read from /pantheon/decision-router.json'\n : 'read from /pantheon/decision-router.json',\n })\n\n return {\n id: 'doctor',\n title: 'Doctor',\n groups: [\n {\n title: 'Health (file-derived)',\n rows,\n },\n {\n rows: [\n {\n id: 'doctor.cli',\n name: 'Full check',\n value: '`pantheon-opencode doctor`',\n note: 'MCP smoke, venv pins, git stay in the CLI',\n },\n ],\n },\n ],\n }\n}\n","/**\n * settings-i18n.ts — Bilingual (PT-BR / EN) internationalization for TUI settings.\n *\n * Provides localized titles, labels, and explanations for:\n * - Decision Router & Jev model selection\n * - Autonomy & Budgets\n * - Safety & J1 Risk Gate\n *\n * Automatically detects environment locale (LANG / LC_ALL) while allowing\n * manual override in TUI preferences.\n */\n\nexport type SettingsLanguage = 'auto' | 'pt-BR' | 'en'\n\nexport const SETTINGS_LANGUAGES_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\nexport const SUPPORTED_LANGUAGES = SETTINGS_LANGUAGES_CYCLE\n\n/**\n * Resolve effective language: 'pt-BR' or 'en'.\n * Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt,\n * or if system timezone is Brazilian/Portuguese; otherwise 'en'.\n */\nexport function resolveLanguage(\n preference: string = 'auto',\n env: Record = process.env,\n): 'pt-BR' | 'en' {\n if (preference === 'pt-BR') return 'pt-BR'\n if (preference === 'en') return 'en'\n\n // 1. Auto-detection based on environment locale variables\n const lang = (env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? '').toLowerCase()\n if (lang.startsWith('pt')) return 'pt-BR'\n\n // 2. Auto-detection based on Intl locale\n try {\n const intlLocale = Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()\n if (intlLocale.startsWith('pt')) return 'pt-BR'\n } catch {}\n\n // 3. Auto-detection based on timezone (Brazil & Portugal)\n try {\n const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? '').toLowerCase()\n if (\n tz.includes('sao_paulo') ||\n tz.includes('brazil') ||\n tz.includes('fortaleza') ||\n tz.includes('recife') ||\n tz.includes('manaus') ||\n tz.includes('belem') ||\n tz.includes('cuiaba') ||\n tz.includes('campo_grande') ||\n tz.includes('porto_velho') ||\n tz.includes('rio_branco') ||\n tz.includes('boa_vista') ||\n tz.includes('maceio') ||\n tz.includes('bahia') ||\n tz.includes('noronha') ||\n tz.includes('araguaina') ||\n tz.includes('santarem') ||\n tz.includes('lisbon') ||\n tz.includes('madeira') ||\n tz.includes('azores')\n ) {\n return 'pt-BR'\n }\n } catch {}\n\n return 'en'\n}\n\nexport interface I18nStringPair {\n en: string\n pt: string\n}\n\nexport const I18N = {\n tabs: {\n decision: { en: 'Decision (Jev)', pt: 'Decisão (Jev)' },\n autonomy: { en: 'Autonomy', pt: 'Autonomia' },\n safety: { en: 'Safety (J1)', pt: 'Segurança (J1)' },\n tui: { en: 'TUI', pt: 'TUI' },\n },\n decision: {\n groupRouter: {\n en: 'Decision Router (Jev Assistant)',\n pt: 'Assistente de Decisão (Jev)',\n },\n groupCredentials: {\n en: 'Credentials (status only — values never enter the window)',\n pt: 'Credenciais (apenas status — valores protegidos)',\n },\n routerName: {\n en: 'Router (Decision Assistant)',\n pt: 'Assistente Jev',\n },\n routerNote: {\n en: 'applies live — enables intelligent route arbitration and candidate ranking',\n pt: 'aplica em tempo real — motor de arbitragem inteligente e ranking de rotas',\n },\n modelName: {\n en: 'Decision model',\n pt: 'Modelo de Decisão',\n },\n modelNote: {\n en: 'local routes on-device (free); auto/explicit pick a remote decision model',\n pt: 'local decide no seu PC (grátis); auto/explícito usa modelo nuvem (OpenRouter)',\n },\n selectionModeName: {\n en: 'Selection mode',\n pt: 'Modo de operação',\n },\n selectionModeNote: {\n en: 'local routes on-device; auto/explicit pick a remote decision model',\n pt: 'local decide no dispositivo; auto/explícito usa modelo remoto',\n },\n egressName: {\n en: 'Cloud API access (Egress)',\n pt: 'Acesso à Nuvem (Egress)',\n },\n egressNoteGranted: {\n en: 'granted = remote decision routes may call their gateway (budget-capped)',\n pt: 'permitido = rotas remotas podem consultar a API (com limite de orçamento)',\n },\n egressNoteNotGranted: {\n en: 'not granted = remote routes blocked; local heuristic decisions only',\n pt: 'não permitido = chamadas remotas bloqueadas; apenas heurística local',\n },\n candidatesName: {\n en: 'Active candidates',\n pt: 'Candidatos ativos',\n },\n },\n autonomy: {\n groupGoalLoop: {\n en: 'Goal loop (multi-turn session auto-continuation)',\n pt: 'Execução Contínua (Goal Loop)',\n },\n goalLoopName: {\n en: 'Goal loop',\n pt: 'Loop contínuo',\n },\n goalLoopNote: {\n en: 'auto-continues multi-turn tasks when session goes idle · applies after OpenCode restart',\n pt: 'continua tarefas de múltiplos passos automaticamente · requer reinício',\n },\n maxContinuationsName: {\n en: 'Max continuations',\n pt: 'Limite de turnos',\n },\n maxContinuationsNote: {\n en: '1..200 — safety ceiling to prevent runaway tasks',\n pt: '1..200 — teto de segurança contra tarefas infinitas',\n },\n cooldownName: {\n en: 'Cooldown (ms)',\n pt: 'Intervalo (ms)',\n },\n cooldownNote: {\n en: 'delay between autonomous turns (min 1000ms)',\n pt: 'tempo de espera entre turnos autônomos (mín 1000ms)',\n },\n groupBudgets: {\n en: 'Decision budgets (applies live per gated call)',\n pt: 'Orçamento Jev (teto financeiro de proteção)',\n },\n monthlyCapName: {\n en: 'Monthly cap',\n pt: 'Teto mensal (USD)',\n },\n monthlyCapNote: {\n en: 'monthly USD ceiling for gated arbitrator decisions',\n pt: 'teto mensal em dólares para decisões do assistente Jev',\n },\n perDecisionCapName: {\n en: 'Per-decision cap',\n pt: 'Teto por consulta (USD)',\n },\n perDecisionCapNote: {\n en: 'price cap — gated decisions above this are refused',\n pt: 'teto por decisão — consultas remotas que excederem são recusadas',\n },\n groupGradient: {\n en: 'Decision gradient (reference policy · J1 owns the risk axis)',\n pt: 'Níveis de Decisão & Segurança (Referência)',\n },\n soloName: {\n en: 'Decide solo',\n pt: 'Decisão direta',\n },\n soloNote: {\n en: 'reversible & low-risk edits, routine fixes (no gate)',\n pt: 'edições reversíveis e baixo risco, sem portão de bloqueio',\n },\n jevName: {\n en: 'Jev decides',\n pt: 'Decisão Jev',\n },\n jevNote: {\n en: 'typed ambiguity & candidate ranking (budget-capped)',\n pt: 'ambiguidade e ranking de skills com teto de orçamento',\n },\n humanName: {\n en: 'Human decides',\n pt: 'Aprovação humana',\n },\n humanNote: {\n en: 'high-risk & destructive operations (J1 gate)',\n pt: 'ações de alto risco e destrutivas (portão de segurança J1)',\n },\n },\n safety: {\n groupSafety: {\n en: 'Safety & Risk Level (J1 Gate)',\n pt: 'Nível de Proteção & Portão de Risco (J1)',\n },\n modeName: {\n en: 'Protection mode',\n pt: 'Modo de proteção',\n },\n thresholdName: {\n en: 'Enforce threshold',\n pt: 'Teto para bloqueio',\n },\n thresholdNote: {\n en: 'deny at or above · 0..1 · default 0.8',\n pt: 'bloqueia em ou acima de · 0..1 · padrão 0.8',\n },\n gateName: {\n en: 'Safety gate',\n pt: 'Portão de segurança',\n },\n },\n} as const\n\n/** Helper to get localized text */\nexport function t(entry: I18nStringPair, lang: 'pt-BR' | 'en'): string {\n return lang === 'pt-BR' ? entry.pt : entry.en\n}\n","/**\n * j1-gate-status.ts — the J1 Risk Gate section of the settings window.\n *\n * TUI-local replica of the ladder in src/pantheon/jev-risk-gate.ts (the\n * bundle must stay self-contained); tests/tui-settings-j1.test.mjs pins the\n * env names, the ladder values and the default threshold against that source.\n *\n * STATUS ONLY by design: the ladder has no file surface yet — mode and\n * threshold are env-only and read once at plugin setup — so nothing here\n * writes, and the section says so. A file surface is a runtime-plugin change\n * (beta.3 candidate), not a window change.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport const J1_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'\nexport const J1_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'\nexport const J1_THRESHOLD_DEFAULT = 0.8\n\nexport type J1Mode = 'off' | 'shadow' | 'warn' | 'enforce'\n\n/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */\nconst FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])\n\nexport function j1ModeFromEnv(env: Record = process.env): J1Mode {\n const raw = (env[J1_FLAG_ENV] ?? '').trim().toLowerCase()\n if (raw === 'enforce') return 'enforce'\n if (raw === 'warn') return 'warn'\n return FLAG_ON.has(raw) ? 'shadow' : 'off'\n}\n\n/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */\nexport function j1ThresholdFromEnv(env: Record = process.env): number {\n const text = (env[J1_THRESHOLD_ENV] ?? '').trim()\n if (text === '') return J1_THRESHOLD_DEFAULT\n const raw = Number(text)\n if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT\n return raw\n}\n\nconst MODE_DESCRIPTION_EN: Record = {\n off: 'nothing fires (hard zero)',\n shadow: 'observe + record; invisible in the session',\n warn: 'RESERVED — behaves as shadow in this release',\n enforce: 'high-risk scores DENY the tool call (fail-open on gate unavailability)',\n}\n\nconst MODE_DESCRIPTION_PT: Record = {\n off: 'desativado (hard zero)',\n shadow: 'observa + registra telemetria (modo silencioso)',\n warn: 'RESERVADO (RESERVED) — comporta-se como shadow nesta versão',\n enforce: 'alto risco bloqueia a ferramenta (fail-open se indisponível)',\n}\n\nexport function buildJ1Tab(\n env: Record,\n disabledByOverride: boolean,\n languagePref?: string | undefined,\n): SettingsTab {\n const lang = resolveLanguage(languagePref)\n const isPt = lang === 'pt-BR'\n const mode = j1ModeFromEnv(env)\n const threshold = j1ThresholdFromEnv(env)\n const gateState = disabledByOverride\n ? 'disabled via overrides'\n : mode === 'off'\n ? 'off (env unset)'\n : 'active'\n const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]\n\n return {\n id: 'j1',\n title: isPt ? 'Segurança J1' : 'J1 Safety',\n groups: [\n {\n title: isPt ? 'Portão de Segurança (J1)' : 'Safety Risk Gate (J1)',\n rows: [\n {\n id: 'j1.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: mode,\n note: `${desc} · ${isPt ? 'reinício necessário (restart applies)' : 'restart applies'}`,\n },\n {\n id: 'j1.threshold',\n name: isPt ? 'Limiar de bloqueio' : 'Enforce threshold',\n value: String(threshold),\n note: isPt\n ? 'bloqueia em ou acima · 0..1 · padrão 0.8'\n : 'deny at or above · 0..1 · default 0.8',\n },\n {\n id: 'j1.gate',\n name: isPt ? 'Portão de Segurança' : 'Safety Risk Gate',\n value: gateState,\n note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? 'lido na inicialização' : 'read once at startup'}`,\n },\n ],\n },\n ],\n }\n}\n","/**\n * preset-state.ts — the Model Preset section of the settings window.\n *\n * TUI-local replica (the bundle must stay self-contained). The preset NAMES\n * mirror routing.yml's `presets:` and are drift-pinned by\n * tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file\n * shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile`\n * (version 1), and the readers (`resolveActivePreset`, vision.ts candidates)\n * only consult `.preset`, so the window writes `source: 'tui-settings'`.\n *\n * Scope note: the window writes the GLOBAL marker only\n * (`/opencode/.pantheon/active-preset.json`). A project marker\n * wins (it precedes the global path in every runtime candidate list), so it\n * is displayed read-only. `none` DELETES the marker with a .bak backup — the\n * same contract as the CLI's `set-tier none`.\n */\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\n/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */\nexport const PRESET_NAMES: readonly string[] = Object.freeze([\n 'go-free',\n 'go-fast',\n 'go-premium',\n 'go-hybrid',\n 'anthropic',\n 'openai',\n])\n\nexport interface ActivePresetMarker {\n version: number\n preset: string\n source: string\n updated_at: string\n}\n\nexport function globalActivePresetPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon', 'active-preset.json')\n}\n\nexport function projectActivePresetPath() {\n return join(process.cwd(), '.pantheon', 'active-preset.json')\n}\n\n/** Fail-open read: missing/corrupt marker = no active preset. */\nexport function readActivePresetMarker(path: string): { name: string; updatedAt: string } | null {\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { preset?: unknown; updated_at?: unknown }\n if (typeof raw?.preset !== 'string' || raw.preset === '' || raw.preset === 'none') return null\n return {\n name: raw.preset,\n updatedAt: typeof raw.updated_at === 'string' ? raw.updated_at : '',\n }\n } catch {\n return null\n }\n}\n\nfunction writeMarkerAtomically(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, content)\n renameSync(temp, path)\n}\n\n/** Select a preset globally: .bak backup, atomic write, version-1 marker. */\nexport function writeActivePreset(\n path: string,\n name: string,\n nowIso = new Date().toISOString(),\n): void {\n if (!PRESET_NAMES.includes(name)) {\n throw new TypeError(`Refusing to persist unknown preset \"${name}\"`)\n }\n backupMarker(path)\n const marker: ActivePresetMarker = {\n version: 1,\n preset: name,\n source: 'tui-settings',\n updated_at: nowIso,\n }\n writeMarkerAtomically(path, `${JSON.stringify(marker, null, 2)}\\n`)\n}\n\n/** Clear the global marker (the `none` contract): .bak backup, then remove. */\nexport function clearActivePreset(path: string): void {\n backupMarker(path)\n rmSync(path, { force: true })\n}\n\nfunction backupMarker(path: string): void {\n if (!existsSync(path)) return\n mkdirSync(dirname(path), { recursive: true })\n copyFileSync(path, `${path}.bak`)\n}\n\nexport const VISION_MODEL_OPTIONS: readonly string[] = Object.freeze([\n 'auto',\n 'opencode-go/mimo-v2.6-flash',\n 'google/gemini-2.5-flash',\n 'openai/gpt-5-mini',\n 'anthropic/claude-3-5-haiku',\n 'opencode-go/mimo-v2.5',\n])\n\nexport function visionConfigPaths(\n cwd = process.cwd(),\n env: Record = process.env,\n): string[] {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n return [\n join(cwd, '.opencode', 'opencode-vision.json'),\n join(xdg, 'opencode', 'opencode-vision.json'),\n ]\n}\n\nexport function readConfiguredVisionModel(\n cwd = process.cwd(),\n env: Record = process.env,\n): string {\n for (const path of visionConfigPaths(cwd, env)) {\n try {\n if (existsSync(path)) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as { visionModel?: unknown }\n if (typeof parsed?.visionModel === 'string' && parsed.visionModel.trim()) {\n return parsed.visionModel.trim()\n }\n }\n } catch {\n // ignore corrupt/missing\n }\n }\n return 'auto'\n}\n\nexport function writeConfiguredVisionModel(\n model: string,\n cwd = process.cwd(),\n env: Record = process.env,\n): void {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n const projectDir = join(cwd, '.opencode')\n const targetPath = existsSync(projectDir)\n ? join(projectDir, 'opencode-vision.json')\n : join(xdg, 'opencode', 'opencode-vision.json')\n\n let current: Record = {}\n try {\n if (existsSync(targetPath)) {\n current = JSON.parse(readFileSync(targetPath, 'utf8')) as Record\n }\n } catch {\n current = {}\n }\n\n if (model === 'auto' || !model.trim()) {\n delete current.visionModel\n } else {\n current.visionModel = model.trim()\n }\n\n mkdirSync(dirname(targetPath), { recursive: true })\n const temp = `${targetPath}.tui.tmp`\n writeFileSync(temp, `${JSON.stringify(current, null, 2)}\\n`, 'utf8')\n renameSync(temp, targetPath)\n}\n\nexport interface PresetSectionInput {\n globalName: string | null\n projectName: string | null\n visionModel?: string\n}\n\n/** The staged value 'none' means: delete the global marker (the CLI contract). */\nexport const PRESET_NONE = 'none'\n\nexport const PRESET_CYCLE: readonly string[] = Object.freeze([PRESET_NONE, ...PRESET_NAMES])\n\nexport function buildPresetTab(input: PresetSectionInput, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const rows: SettingsRow[] = [\n {\n id: 'preset',\n name: isPt ? 'Predefinição' : 'Preset',\n value: input.globalName ?? PRESET_NONE,\n cycle: PRESET_CYCLE,\n note: isPt\n ? 'marcador global · gravação atômica, backup .bak · none = padrão OpenCode'\n : 'global marker · atomic write, .bak backup · none = opencode defaults',\n },\n ]\n if (input.projectName !== null) {\n rows.push({\n id: 'preset.project',\n name: isPt ? 'Projeto' : 'Project',\n value: input.projectName,\n note: isPt\n ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui`\n : `${projectActivePresetPath()} wins over the global marker — read-only here`,\n })\n }\n if (input.visionModel !== undefined) {\n rows.push({\n id: 'preset.vision_model',\n name: isPt ? 'Modelo de Visão' : 'Vision Model',\n value: input.visionModel || 'auto',\n cycle: VISION_MODEL_OPTIONS,\n note: isPt\n ? 'modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json'\n : 'model for image inspection (vision_describe) · saved in opencode-vision.json',\n })\n }\n return {\n id: 'preset',\n title: 'Preset',\n groups: [{ title: isPt ? 'Predefinição de modelo' : 'Model preset', rows }],\n }\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: stored prefs are host JSON of a known shape.\n/**\n * tui-prefs.ts — the TUI personalization core (the settings window's TUI tab).\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. Persistence is the HOST's durable plugin storage\n * (`context.storage.store('tui-prefs', { initial })` — reactive solid store,\n * live-synced across TUI instances); this module owns the SHAPE and the pure\n * operations, never the store handle.\n *\n * v1 surfaces: sidebar fixed headers, sidebar blocks, the Context block's\n * sub-lines and gauge style, and the two Pantheon footer lines. Everything\n * defaults to on — the window exists to turn things OFF.\n */\n\nimport type { Context } from '@opencode/plugin/tui/context'\nimport type { Accessor, Setter } from 'solid-js'\nimport { createSignal } from 'solid-js'\nimport type { SettingsDraft, SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\n// ── The durable store handle (host storage, one per plugin) ────────────\n// Created once at setup and stashed under a globalThis symbol so\n// hot-reload generations keep sharing the same live store (the same\n// singleton doctrine as the plugin's SINGLETON guard).\n\nconst PREFS_SYMBOL = Symbol.for('pantheon.tui.prefs.v1')\nconst DRAFT_PREVIEW_SYMBOL = Symbol.for('pantheon.tui.draft_preview.v1')\ntype PrefsStore = readonly [TuiPrefs, (mutation: (draft: TuiPrefs) => void) => Promise]\ntype DraftSignal = [Accessor, Setter]\n\nfunction stash(): PrefsStore | undefined {\n return (globalThis as Record)[PREFS_SYMBOL] as PrefsStore | undefined\n}\n\nfunction getDraftPreviewSignal(): DraftSignal {\n const g = globalThis as Record\n if (!g[DRAFT_PREVIEW_SYMBOL]) {\n g[DRAFT_PREVIEW_SYMBOL] = createSignal(undefined)\n }\n return g[DRAFT_PREVIEW_SYMBOL] as DraftSignal\n}\n\n/** Set the active draft preview overlay (used by settings window to provide live preview). */\nexport function setTuiDraftPreview(draft: SettingsDraft | undefined): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : undefined)\n}\n\n/** Clear the active draft preview overlay. */\nexport function clearTuiDraftPreview(): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(undefined)\n}\n\n/** The active draft preview accessor. */\nexport function tuiDraftPreview(): SettingsDraft | undefined {\n const [draft] = getDraftPreviewSignal()\n return draft()\n}\n\n/** Create (or reuse) the durable prefs store. Fail-open: without host\n * storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */\nexport function initTuiPrefs(context: Context): void {\n if (stash() !== undefined) return\n try {\n const handle = context.storage?.store?.('tui-prefs', { initial: DEFAULT_TUI_PREFS }) as\n | PrefsStore\n | undefined\n if (handle !== undefined) {\n ;(globalThis as unknown as Record)[PREFS_SYMBOL] = handle\n // Self-heal: if store was persisted before layout existed, backfill missing top-level defaults\n if (!handle[0]?.layout) {\n handle[1]((draft: any) => {\n if (!draft.layout) {\n draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n }\n }).catch(() => {})\n }\n }\n } catch {\n /* no host storage — defaults stay read-only */\n }\n}\n\n/** Deep clone and overlay staged settings draft onto base TuiPrefs. */\nexport function previewTuiPrefs(base: TuiPrefs, draft?: SettingsDraft): TuiPrefs {\n if (!draft || Object.keys(draft).length === 0) return base\n let hasTui = false\n for (const k of Object.keys(draft)) {\n if (k.startsWith('tui.')) {\n hasTui = true\n break\n }\n }\n if (!hasTui) return base\n\n const normalized = normalizeTuiPrefs(base)\n const effective: TuiPrefs = {\n version: 1,\n layout: { ...normalized.layout },\n sidebar: {\n header: { ...normalized.sidebar.header },\n blocks: { ...normalized.sidebar.blocks },\n context: { ...normalized.sidebar.context },\n },\n footer: { ...normalized.footer },\n }\n\n for (const [id, value] of Object.entries(draft)) {\n if (id.startsWith('tui.')) {\n applyTuiRow(effective, id, value)\n }\n }\n return effective\n}\n\n/** The raw persisted prefs from host storage (no draft overlay). */\nexport function savedTuiPrefs(): TuiPrefs {\n const s = stash()?.[0]\n if (!s) return DEFAULT_TUI_PREFS\n if (!s.layout) {\n return {\n ...s,\n layout: DEFAULT_TUI_PREFS.layout,\n }\n }\n return s\n}\n\n/** The live reactive prefs (read properties inside memos/JSX — tracked).\n * When a settings window has an active draft, preview overlays on top\n * of durable storage in real time. */\nexport function tuiPrefs(): TuiPrefs {\n const base = savedTuiPrefs()\n const preview = tuiDraftPreview()\n if (!preview) return base\n return previewTuiPrefs(base, preview)\n}\n\n/** Stage a mutation against the durable store; resolves when persisted. */\nexport function mutateTuiPrefs(mutation: (draft: TuiPrefs) => void): Promise {\n const handle = stash()\n if (handle === undefined) return Promise.resolve()\n return handle[1](mutation)\n}\n\nexport const GAUGE_STYLES: readonly string[] = Object.freeze(['both', 'bar', 'percent', 'off'])\nexport const ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const BAR_SHAPES_CYCLE: readonly string[] = Object.freeze([\n 'line',\n 'block',\n 'smooth',\n 'ascii',\n 'dots',\n 'braille',\n])\nexport const BAR_WIDTHS_CYCLE: readonly string[] = Object.freeze([\n 'standard',\n 'compact',\n 'wide',\n 'full',\n])\nexport const LAYOUT_PRESETS_CYCLE: readonly string[] = Object.freeze(['comfortable', 'compact'])\nexport const SEPARATOR_STYLES_CYCLE: readonly string[] = Object.freeze([\n 'spaces',\n 'pipes',\n 'dots',\n 'slashes',\n])\nexport const SETTINGS_VIEW_MODES: readonly string[] = Object.freeze([\n 'docked',\n 'fullscreen',\n 'dialog',\n])\n\nexport type GaugeStyle = 'both' | 'bar' | 'percent' | 'off'\nexport type BarShapePref = 'line' | 'block' | 'smooth' | 'ascii' | 'dots' | 'braille'\nexport type BarWidthPref = 'standard' | 'compact' | 'wide' | 'full'\nexport type LayoutPresetPref = 'comfortable' | 'compact'\nexport type SeparatorStylePref = 'spaces' | 'pipes' | 'dots' | 'slashes'\nexport type SettingsViewModePref = 'docked' | 'fullscreen' | 'dialog'\nexport type LanguagePref = 'auto' | 'pt-BR' | 'en'\n\nexport const LANGUAGE_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\n\nexport interface TuiPrefs {\n version: 1\n layout: {\n preset: LayoutPresetPref\n separator: SeparatorStylePref\n settingsView?: SettingsViewModePref\n language?: LanguagePref\n }\n sidebar: {\n header: { version: boolean; preset: boolean; session: boolean }\n blocks: { context: boolean; git: boolean; todo: boolean; dispatch: boolean }\n context: {\n gauge: GaugeStyle\n barShape: BarShapePref\n barWidth: BarWidthPref\n evenMark: boolean\n tokens: boolean\n spent: boolean\n modelUsage: boolean\n performance: boolean\n localSpend: boolean\n }\n }\n footer: { prompt: boolean; home: boolean }\n}\n\nexport const DEFAULT_TUI_PREFS: TuiPrefs = {\n version: 1,\n layout: {\n preset: 'comfortable',\n separator: 'spaces',\n settingsView: 'fullscreen',\n language: 'auto',\n },\n sidebar: {\n header: { version: true, preset: true, session: true },\n blocks: { context: true, git: true, todo: true, dispatch: true },\n context: {\n gauge: 'both',\n barShape: 'line',\n barWidth: 'standard',\n evenMark: false,\n tokens: true,\n spent: true,\n modelUsage: true,\n performance: true,\n localSpend: true,\n },\n },\n footer: { prompt: true, home: true },\n}\n\nfunction asBool(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback\n}\n\n/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */\nexport function normalizeTuiPrefs(raw: unknown): TuiPrefs {\n const stored = (typeof raw === 'object' && raw !== null ? raw : {}) as Record\n const layout = (\n typeof stored.layout === 'object' && stored.layout !== null ? stored.layout : {}\n ) as Record\n const sidebar = (\n typeof stored.sidebar === 'object' && stored.sidebar !== null ? stored.sidebar : {}\n ) as Record\n const header = (\n typeof sidebar.header === 'object' && sidebar.header !== null ? sidebar.header : {}\n ) as Record\n const blocks = (\n typeof sidebar.blocks === 'object' && sidebar.blocks !== null ? sidebar.blocks : {}\n ) as Record\n const context = (\n typeof sidebar.context === 'object' && sidebar.context !== null ? sidebar.context : {}\n ) as Record\n const footer = (\n typeof stored.footer === 'object' && stored.footer !== null ? stored.footer : {}\n ) as Record\n const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset as string)\n ? (layout.preset as LayoutPresetPref)\n : DEFAULT_TUI_PREFS.layout.preset\n const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator as string)\n ? (layout.separator as SeparatorStylePref)\n : DEFAULT_TUI_PREFS.layout.separator\n const settingsView = (\n SETTINGS_VIEW_MODES.includes(layout.settingsView as string)\n ? layout.settingsView\n : DEFAULT_TUI_PREFS.layout.settingsView\n ) as SettingsViewModePref\n const language = (\n LANGUAGE_CYCLE.includes(layout.language as string)\n ? layout.language\n : DEFAULT_TUI_PREFS.layout.language\n ) as LanguagePref\n const gauge = GAUGE_STYLES.includes(context.gauge as string)\n ? (context.gauge as GaugeStyle)\n : DEFAULT_TUI_PREFS.sidebar.context.gauge\n const barShape = BAR_SHAPES_CYCLE.includes(context.barShape as string)\n ? (context.barShape as BarShapePref)\n : DEFAULT_TUI_PREFS.sidebar.context.barShape\n const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth as string)\n ? (context.barWidth as BarWidthPref)\n : DEFAULT_TUI_PREFS.sidebar.context.barWidth\n const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark)\n\n return {\n version: 1,\n layout: {\n preset,\n separator,\n settingsView,\n language,\n },\n sidebar: {\n header: {\n version: asBool(header.version, true),\n preset: asBool(header.preset, true),\n session: asBool(header.session, true),\n },\n blocks: {\n context: asBool(blocks.context, true),\n git: asBool(blocks.git, true),\n todo: asBool(blocks.todo, true),\n dispatch: asBool(blocks.dispatch, true),\n },\n context: {\n gauge,\n barShape,\n barWidth,\n evenMark,\n tokens: asBool(context.tokens, true),\n spent: asBool(context.spent, true),\n modelUsage: asBool(context.modelUsage, true),\n performance: asBool(context.performance, true),\n localSpend: asBool(context.localSpend, true),\n },\n },\n footer: {\n prompt: asBool(footer.prompt, true),\n home: asBool(footer.home, true),\n },\n }\n}\n\n// ── The TUI tab (cycler rows over the dotted pref paths) ───────────────\n\nconst onOff = ENABLED_CYCLE\nconst row = (id: string, name: string, value: boolean, note: string): SettingsRow => ({\n id,\n name,\n value: value ? 'enabled' : 'disabled',\n cycle: onOff,\n note,\n})\n\nexport function buildTuiTab(prefs: TuiPrefs, languagePref?: string): SettingsTab {\n const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === 'pt-BR'\n return {\n id: 'tui',\n title: 'TUI',\n groups: [\n {\n title: isPt ? 'Predefinição & Layout' : 'Preset & Layout',\n rows: [\n {\n id: 'tui.layout.preset',\n name: isPt ? 'Predefinição de layout' : 'Layout preset',\n value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset,\n cycle: LAYOUT_PRESETS_CYCLE,\n note: isPt\n ? 'comfortable | compact — define espaçamento e bordas'\n : 'comfortable | compact — sets spacing & borders',\n },\n {\n id: 'tui.layout.separator',\n name: isPt ? 'Separador' : 'Separator',\n value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator,\n cycle: SEPARATOR_STYLES_CYCLE,\n note: isPt\n ? 'spaces | pipes | dots | slashes — glifos na linha de status'\n : 'spaces | pipes | dots | slashes — status line glyphs',\n },\n {\n id: 'tui.layout.settingsView',\n name: isPt ? 'Superfície de configurações' : 'Settings surface',\n value: tuiRowValue(prefs, 'tui.layout.settingsView') ?? 'docked',\n cycle: SETTINGS_VIEW_MODES,\n note: isPt\n ? 'docked (acima do prompt) | fullscreen | dialog'\n : 'docked (above prompt) | fullscreen router page | dialog overlay',\n },\n {\n id: 'tui.layout.language',\n name: isPt ? 'Idioma / Language' : 'Language / Idioma',\n value: tuiRowValue(prefs, 'tui.layout.language') ?? 'auto',\n cycle: LANGUAGE_CYCLE,\n note: isPt\n ? 'auto (detecta via fuso/locale) | pt-BR (Português) | en (English)'\n : 'auto (detect via timezone/locale) | pt-BR (Português) | en (English)',\n },\n ],\n },\n {\n title: isPt ? 'Barras & Medidores' : 'Bars & Gauges',\n rows: [\n {\n id: 'tui.sidebar.context.barShape',\n name: isPt ? 'Formato da barra' : 'Bar shape',\n value: prefs.sidebar.context.barShape,\n cycle: BAR_SHAPES_CYCLE,\n note: 'line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille',\n },\n {\n id: 'tui.sidebar.context.barWidth',\n name: isPt ? 'Largura da barra' : 'Bar width',\n value: prefs.sidebar.context.barWidth,\n cycle: BAR_WIDTHS_CYCLE,\n note: isPt\n ? 'standard (12) | compact (8) | wide (16) | full (20 células)'\n : 'standard (12) | compact (8) | wide (16) | full (20 cells)',\n },\n row(\n 'tui.sidebar.context.evenMark',\n isPt ? 'Marca central (50%)' : 'Even-use mark',\n prefs.sidebar.context.evenMark,\n isPt\n ? '| indicador aos 50% nas barras de medição'\n : '| indicator at 50% midpoint in gauge bars',\n ),\n {\n id: 'tui.sidebar.context.gauge',\n name: isPt ? 'Estilo do medidor' : 'Gauge style',\n value: prefs.sidebar.context.gauge,\n cycle: GAUGE_STYLES,\n note: 'both | bar | percent | off — `▰▱ 42% of 200k`',\n },\n ],\n },\n {\n title: isPt ? 'Cabeçalho da barra lateral' : 'Sidebar header',\n rows: [\n row(\n 'tui.sidebar.header.version',\n isPt ? 'Linha de versão' : 'Version line',\n prefs.sidebar.header.version,\n isPt ? 'linha `Pantheon v…`' : 'the `Pantheon v…` line',\n ),\n row(\n 'tui.sidebar.header.preset',\n isPt ? 'Linha de preset' : 'Preset line',\n prefs.sidebar.header.preset,\n isPt ? 'linha `▸ preset · provider`' : 'the `▸ preset · provider` line',\n ),\n row(\n 'tui.sidebar.header.session',\n isPt ? 'Linha de sessão' : 'Session line',\n prefs.sidebar.header.session,\n isPt ? 'título da sessão ativa' : 'the active session title',\n ),\n ],\n },\n {\n title: isPt ? 'Blocos da barra lateral' : 'Sidebar blocks',\n rows: [\n row(\n 'tui.sidebar.block.context',\n isPt ? 'Bloco de contexto' : 'Context block',\n prefs.sidebar.blocks.context,\n isPt ? 'tokens, medidor, custo, uso de modelos' : 'tokens, gauge, spend, model usage',\n ),\n row(\n 'tui.sidebar.block.git',\n isPt ? 'Bloco do Git' : 'Git block',\n prefs.sidebar.blocks.git,\n isPt ? 'branch + contagem de alterações' : 'branch + working-tree counts',\n ),\n row(\n 'tui.sidebar.block.todo',\n isPt ? 'Bloco Todo' : 'Todo block',\n prefs.sidebar.blocks.todo,\n isPt ? 'tarefas pendentes mais recentes' : 'the newest todowrite',\n ),\n row(\n 'tui.sidebar.block.dispatch',\n isPt ? 'Bloco Dispatch' : 'Dispatch block',\n prefs.sidebar.blocks.dispatch,\n isPt ? 'delegações em tempo real' : 'live delegations + rollup',\n ),\n ],\n },\n {\n title: isPt ? 'Detalhe do bloco de contexto' : 'Context block detail',\n rows: [\n row(\n 'tui.sidebar.context.tokens',\n isPt ? 'Linha de tokens' : 'Tokens row',\n prefs.sidebar.context.tokens,\n isPt ? 'contagem bruta de tokens' : 'the raw token count line',\n ),\n row(\n 'tui.sidebar.context.spent',\n isPt ? 'Linha de custo' : 'Spent row',\n prefs.sidebar.context.spent,\n isPt ? 'linha `$… gastos na sessão`' : 'the `$… spent in session` line',\n ),\n row(\n 'tui.sidebar.context.modelUsage',\n isPt ? 'Tabela de uso de modelos' : 'Model usage table',\n prefs.sidebar.context.modelUsage,\n isPt ? 'resumo de chamadas por modelo' : 'per-model tokens/USD',\n ),\n row(\n 'tui.sidebar.context.performance',\n isPt ? 'Linha de desempenho' : 'Performance row',\n prefs.sidebar.context.performance,\n isPt ? 'tokens/segundo e latência' : 'cache % + tok/s',\n ),\n row(\n 'tui.sidebar.context.localSpend',\n isPt ? 'Linha de custo local' : 'Local spend row',\n prefs.sidebar.context.localSpend,\n isPt ? 'totais de hoje / 30 dias' : 'hoje / 30d totals',\n ),\n ],\n },\n {\n title: isPt ? 'Rodapés' : 'Footers',\n rows: [\n row(\n 'tui.footer.prompt',\n isPt ? 'Prompt inferior' : 'Prompt footer',\n prefs.footer.prompt,\n isPt\n ? 'linha `▸preset · ✦n ativos` durante delegações'\n : 'the `▸preset · ✦n ativos` line while delegations run',\n ),\n row(\n 'tui.footer.home',\n isPt ? 'Status inicial' : 'Home status',\n prefs.footer.home,\n isPt\n ? 'linha `Pantheon v…` sob o prompt inicial'\n : 'the `Pantheon v…` line under the home prompt',\n ),\n ],\n },\n ],\n }\n}\n\n/**\n * Apply one staged row INTO a prefs draft (in place — the storage mutate\n * callback hands an immer-style draft). Unknown ids or junk values are no-ops.\n */\nexport function applyTuiRow(draft: TuiPrefs, id: string, value: string): void {\n const enabled = value === 'enabled'\n switch (id) {\n case 'tui.layout.preset':\n if (LAYOUT_PRESETS_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.preset = value as LayoutPresetPref\n }\n return\n case 'tui.layout.separator':\n if (SEPARATOR_STYLES_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.separator = value as SeparatorStylePref\n }\n return\n case 'tui.layout.settingsView':\n if (SETTINGS_VIEW_MODES.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.settingsView = value as SettingsViewModePref\n }\n return\n case 'tui.layout.language':\n if (LANGUAGE_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.language = value as LanguagePref\n }\n return\n case 'tui.sidebar.context.barShape':\n if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value as BarShapePref\n return\n case 'tui.sidebar.context.barWidth':\n if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value as BarWidthPref\n return\n case 'tui.sidebar.context.evenMark':\n draft.sidebar.context.evenMark = enabled\n return\n case 'tui.sidebar.header.version':\n draft.sidebar.header.version = enabled\n return\n case 'tui.sidebar.header.preset':\n draft.sidebar.header.preset = enabled\n return\n case 'tui.sidebar.header.session':\n draft.sidebar.header.session = enabled\n return\n case 'tui.sidebar.block.context':\n draft.sidebar.blocks.context = enabled\n return\n case 'tui.sidebar.block.git':\n draft.sidebar.blocks.git = enabled\n return\n case 'tui.sidebar.block.todo':\n draft.sidebar.blocks.todo = enabled\n return\n case 'tui.sidebar.block.dispatch':\n draft.sidebar.blocks.dispatch = enabled\n return\n case 'tui.sidebar.context.gauge':\n if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value as GaugeStyle\n return\n case 'tui.sidebar.context.tokens':\n draft.sidebar.context.tokens = enabled\n return\n case 'tui.sidebar.context.spent':\n draft.sidebar.context.spent = enabled\n return\n case 'tui.sidebar.context.modelUsage':\n draft.sidebar.context.modelUsage = enabled\n return\n case 'tui.sidebar.context.performance':\n draft.sidebar.context.performance = enabled\n return\n case 'tui.sidebar.context.localSpend':\n draft.sidebar.context.localSpend = enabled\n return\n case 'tui.footer.prompt':\n draft.footer.prompt = enabled\n return\n case 'tui.footer.home':\n draft.footer.home = enabled\n return\n default:\n return\n }\n}\n\n/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */\nexport function tuiRowValue(prefs: TuiPrefs, id: string): string | undefined {\n if (id === 'tui.layout.preset') return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset\n if (id === 'tui.layout.separator')\n return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator\n if (id === 'tui.layout.settingsView')\n return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? 'docked'\n if (id === 'tui.layout.language') return prefs.layout?.language ?? 'auto'\n if (id === 'tui.sidebar.context.barShape') return prefs.sidebar.context.barShape\n if (id === 'tui.sidebar.context.barWidth') return prefs.sidebar.context.barWidth\n if (id === 'tui.sidebar.context.gauge') return prefs.sidebar.context.gauge\n if (id === 'tui.sidebar.context.evenMark')\n return prefs.sidebar.context.evenMark ? 'enabled' : 'disabled'\n const enabled = (() => {\n switch (id) {\n case 'tui.sidebar.header.version':\n return prefs.sidebar.header.version\n case 'tui.sidebar.header.preset':\n return prefs.sidebar.header.preset\n case 'tui.sidebar.header.session':\n return prefs.sidebar.header.session\n case 'tui.sidebar.block.context':\n return prefs.sidebar.blocks.context\n case 'tui.sidebar.block.git':\n return prefs.sidebar.blocks.git\n case 'tui.sidebar.block.todo':\n return prefs.sidebar.blocks.todo\n case 'tui.sidebar.block.dispatch':\n return prefs.sidebar.blocks.dispatch\n case 'tui.sidebar.context.tokens':\n return prefs.sidebar.context.tokens\n case 'tui.sidebar.context.spent':\n return prefs.sidebar.context.spent\n case 'tui.sidebar.context.modelUsage':\n return prefs.sidebar.context.modelUsage\n case 'tui.sidebar.context.performance':\n return prefs.sidebar.context.performance\n case 'tui.sidebar.context.localSpend':\n return prefs.sidebar.context.localSpend\n case 'tui.footer.prompt':\n return prefs.footer.prompt\n case 'tui.footer.home':\n return prefs.footer.home\n default:\n return undefined\n }\n })()\n return enabled === undefined ? undefined : enabled ? 'enabled' : 'disabled'\n}\n","/**\n * update-status.ts — the Updates section of the settings window.\n *\n * TUI-local; derives rows from the update-notice.ts primitives. The registry\n * fetch and state persistence stay in the .tsx glue (host side) — this module\n * only classifies the channel and builds rows from injected state, so the\n * whole thing is testable without network.\n */\n\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { comparePantheonVersions, type UpdateCheckState } from './update-notice.ts'\n\nexport type UpdateChannel = 'stable' | 'beta'\n\n/** The running version's channel: a `-beta.N` suffix rides the beta dist-tag. */\nexport function updateChannelFor(version: string): UpdateChannel {\n return /-beta\\.\\d+$/.test(version) ? 'beta' : 'stable'\n}\n\n/** The npm dist-tag the registry check should query for the channel. */\nexport function registryTagForChannel(channel: UpdateChannel): string {\n return channel === 'beta' ? 'beta' : 'latest'\n}\n\nexport function registryUrlForChannel(channel: UpdateChannel): string {\n return `https://registry.npmjs.org/pantheon-opencode/${registryTagForChannel(channel)}`\n}\n\nfunction formatAgo(ms: number, isPt = false): string {\n if (ms < 60_000) return isPt ? 'agora mesmo' : 'just now'\n if (ms < 3_600_000)\n return isPt ? `há ${Math.floor(ms / 60_000)}m` : `${Math.floor(ms / 60_000)}m ago`\n if (ms < 86_400_000)\n return isPt ? `há ${Math.floor(ms / 3_600_000)}h` : `${Math.floor(ms / 3_600_000)}h ago`\n return isPt ? `há ${Math.floor(ms / 86_400_000)}d` : `${Math.floor(ms / 86_400_000)}d ago`\n}\n\nexport interface UpdatesSectionInput {\n currentVersion: string\n state: UpdateCheckState\n /** Selected channel (defaults to updateChannelFor(currentVersion)). */\n selectedChannel?: UpdateChannel\n /** Latest version seen this session (a check-now inside this window). */\n lastCheckedVersion?: string\n /** A check-now is in flight (this window). */\n checking?: boolean\n /** An update run is in flight (this window). */\n updating?: boolean\n nowMs?: number\n languagePref?: string\n}\n\nexport function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n const nowMs = input.nowMs ?? Date.now()\n const channel = input.selectedChannel ?? updateChannelFor(input.currentVersion)\n const lastCheckMs = input.state.lastCheckMs\n const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion\n\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n const newer =\n latest !== undefined &&\n comparePantheonVersions(latest, input.currentVersion) > 0 &&\n !(stable(input.currentVersion) && !stable(latest))\n\n const rows: SettingsRow[] = [\n {\n id: 'update.channel',\n name: isPt ? 'Canal' : 'Channel',\n value: channel,\n cycle: ['stable', 'beta'] as const,\n note: isPt\n ? 'stable segue npm `latest`; beta segue npm `beta`'\n : 'stable tracks npm `latest`; beta tracks npm `beta`',\n },\n {\n id: 'update.check',\n name: isPt ? 'Verificar agora' : 'Check now',\n value: input.checking\n ? isPt\n ? 'verificando…'\n : 'checking…'\n : lastCheckMs\n ? isPt\n ? `última verificação ${formatAgo(nowMs - lastCheckMs, true)}`\n : `last check ${formatAgo(nowMs - lastCheckMs, false)}`\n : isPt\n ? 'nunca verificado'\n : 'never checked',\n action: 'update-check',\n note: isPt\n ? 'enter consulta o registro npm para o canal ativo'\n : 'enter probes the registry for the running channel',\n },\n ]\n\n if (latest) {\n rows.push({\n id: 'update.latest',\n name: isPt ? 'Registro (npm)' : 'Registry',\n value: newer\n ? `v${latest} ${isPt ? 'disponível' : 'available'}`\n : isPt\n ? 'atualizado'\n : 'up to date',\n note: newer\n ? isPt\n ? 'instale com `pantheon-opencode update`'\n : 'adopt with `pantheon-opencode update`'\n : isPt\n ? 'nenhuma versão mais recente compatível'\n : 'no newer compatible version',\n })\n rows.push({\n id: 'update.run',\n name: isPt ? 'Atualizar agora' : 'Update now',\n value: input.updating\n ? isPt\n ? 'atualizando…'\n : 'updating…'\n : newer\n ? `${isPt ? 'instalar' : 'install'} v${latest}`\n : isPt\n ? 'reinstalar / atualizar'\n : 'reinstall / refresh',\n action: 'update-run',\n note: newer\n ? isPt\n ? 'enter executa `pantheon-opencode update`'\n : 'enter runs `pantheon-opencode update`'\n : isPt\n ? 'enter atualiza a cópia instalada'\n : 'enter refreshes installed copy',\n })\n }\n\n rows.push({\n id: 'update.command',\n name: isPt ? 'Comando CLI' : 'CLI command',\n value: channel === 'beta' ? 'pantheon-opencode update' : 'pantheon-opencode update --stable',\n note: isPt\n ? 'execute no terminal ou no terminal integrado do OpenCode'\n : 'run in terminal or OpenCode Desktop terminal',\n })\n\n return {\n id: 'updates',\n title: isPt ? 'Atualizações' : 'Updates',\n groups: [{ title: isPt ? 'Atualizações & Manutenção' : 'Updates & Maintenance', rows }],\n }\n}\n","/**\n * whats-new-highlights.ts — release highlights for the one-time \"What's new\"\n * window, extracted from the CHANGELOG.md shipped with the plugin copy.\n *\n * The section-finding logic is an inline replica of scripts/changelog-extract.mjs\n * `extractSection` (pinned by a parity test in tests/tui-whats-new.test.mjs):\n * the copied plugin ships only dist/ + package.json (+ CHANGELOG.md, copied by\n * both installers), so it cannot reach scripts/ at runtime — the same reason\n * the preset resolver is mirrored in index.tsx/index-v2.tsx rather than\n * imported. The script's CLI main is NOT replicated; the plugin only needs the\n * pure extraction.\n *\n * Everything is reduced to bounded plain text: no markdown syntax artifacts,\n * at most WHATS_NEW_MAX_ITEMS bullets. Missing CHANGELOG.md, an unknown\n * version or an empty section all resolve to an empty highlight set — the\n * window simply does not show (fail-open, like the rest of the plugin).\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/** Hard cap on bullets shown in the window (the remainder is counted). */\nexport const WHATS_NEW_MAX_ITEMS = 12\n\n/**\n * Cap for the curated `🆕 What's New` summary block — the window shows the\n * summary, never the full Added/Changed/Fixed walls.\n */\nexport const WHATS_NEW_SUMMARY_MAX_ITEMS = 6\n\n/** Bullets longer than this are truncated with an ellipsis (one-line rule). */\nexport const WHATS_NEW_ITEM_MAX_CHARS = 140\n\n/** Prefix of the \"+N more\" line appended when the bullet budget is exceeded. */\nexport const WHATS_NEW_MORE_PREFIX = '… +'\n\n/** H3 subsection headings are kept as plain-text group labels. */\nexport interface WhatsNewGroup {\n heading: string | null\n items: string[]\n}\n\nexport interface WhatsNewHighlights {\n /** Normalized version the highlights belong to (null when not found). */\n version: string | null\n found: boolean\n groups: WhatsNewGroup[]\n /** Total bullets in the section, before the WHATS_NEW_MAX_ITEMS cut. */\n totalItems: number\n /** True when totalItems exceeded WHATS_NEW_MAX_ITEMS. */\n truncated: boolean\n}\n\nexport const EMPTY_HIGHLIGHTS: WhatsNewHighlights = {\n version: null,\n found: false,\n groups: [],\n totalItems: 0,\n truncated: false,\n}\n\n/** Escape regex metacharacters so a version like 1.0.0 matches literally. */\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Extract the body of a version section from changelog text — inline replica\n * of scripts/changelog-extract.mjs `extractSection` (see that file for the\n * full contract: `## [] - YYYY-MM-DD`, leading `v` and the date\n * optional, `## [Unreleased]` never matched).\n */\nexport function extractSection(\n changelogText: string,\n version: string,\n): { found: boolean; body: string | null } {\n const normalized = String(version).trim().replace(/^v/i, '')\n if (!normalized || /^unreleased$/i.test(normalized)) return { found: false, body: null }\n\n const escaped = escapeRegExp(normalized)\n // Single-line heading: `## [v?1.2.1]` optionally followed by ` - YYYY-MM-DD`.\n // [ \\t] (not \\s) keeps the match from crossing newlines; the lookahead\n // requires end-of-line or whitespace so `[1.0.0-beta]` can never match `1.0.0`.\n const headingRe = new RegExp(\n `^##[ \\\\t]+\\\\[v?${escaped}\\\\](?:[ \\\\t]*-[ \\\\t]*\\\\d{4}-\\\\d{2}-\\\\d{2})?(?=[ \\\\t]|$)`,\n 'm',\n )\n const match = headingRe.exec(changelogText)\n if (!match) return { found: false, body: null }\n\n // Advance past the heading line (match.index may point mid-line).\n const newline = changelogText.indexOf('\\n', match.index)\n const start = newline === -1 ? changelogText.length : newline + 1\n\n // Body ends at the next `## [` heading or end of text.\n const nextHeading = /^##[ \\t]+\\[/m.exec(changelogText.slice(start))\n const end = nextHeading ? start + nextHeading.index : changelogText.length\n\n return { found: true, body: changelogText.slice(start, end).trim() }\n}\n\n/**\n * Reduce one markdown line to plain text: links keep their label, emphasis\n * and inline-code markers are dropped, HTML comment fragments are removed,\n * and whitespace collapses. Deliberately simple — the input is our own\n * CHANGELOG (lint-capped at 200 chars per bullet), not hostile input.\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(//g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('/g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('