@nandoblanco/opencode-relay-orchestration 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,141 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2026-11-27)
4
+
5
+ - Fail fast in `/relay` (`src/planner.ts`) before creating a draft record, switching models, or prompting when required worker roles (`builder`, `reviewer`) are not configured, pointing the user to `/relay-configure`.
6
+ - Documented the no-default-models behavior, up-front `builder`/`reviewer` check, and optional `planner`/`explorer` fallbacks in `README.md`.
7
+
8
+ ## 0.3.0 (2026-11-26)
9
+
10
+ - Add `brainstormFirst` configuration option (default `true`) to `src/config.ts`, `src/rpc.ts`, `src/server.ts`, and `src/planner.ts`. When enabled, `/relay` leads with an explicit two-phase prompt (**Phase 1: Brainstorm first**, blocking `relay_plan_add` / `relay_plan_submit` until the planner explores read-only, presents 2-3 approaches with tradeoffs, risks, and non-goals, and aligns via `question`; **Phase 2: Draft and submit** only after the user confirms direction, or `relay_plan_cancel` if abandoned). Expose the toggle in `/relay-configure` (10 batched questions: 4 jobs + 6 settings), `relay_config_set`, `validateConfig`, and `configSummary` (`brainstorm on|off`).
11
+ - Standardize `README.md` to match sibling OpenCode plugins: unscoped `# opencode-relay-orchestration` title, Desktop and TUI preview screenshots (`assets/screenshot.png` and `assets/screenshot-tui.png`, included in `package.json` `"files"`), OpenCode Desktop Support section, Problem -> Solution Background, 2-column Features table, OpenCode V2 `"plugins"` manual configuration, Commands & Keyboard Shortcuts tables, numbered Architecture & Internals deep dive (with Agent Tools and Token Usage Breakdown tables), Directory & Storage Structure, and 4-column Configuration Options table.
12
+
13
+ ## 0.2.1 (2026-11-24)
14
+
15
+ - Redesign Desktop GUI (`src/gui.tsx`, `src/gui.css`) with native OpenCode theme tokens, clearer hierarchy (active record hero, Tasks, Verification, Approvals, Audit, New record, and compact bottom Role configuration grid), semantic status pills/cards, 3-line expandable clamp for long task prompts, inline `Validate config` confirmation feedback, and proportional form/select grids across 280px to 1280px widths.
16
+ - Redesign TUI panel (`src/tui.ts`) using structured OpenTUI `box`/`scrollbox` layouts, live `ctx.theme` tokens (`background`, `border`, `text.base/muted/faint/action/feedback`), semantic bordered cards for hero, tasks, verification evidence, and approvals, clipped task prompts/summaries, and compact single-line-per-role configuration rows at the bottom. Remove duplicate background `checkConfig()` calls on mount/session change so transient server reloads never pop unsolicited error toasts, and add regression tests in `test/tui.test.ts`.
17
+ - Release audit cleanup: deduplicate `promptTitle` in `src/server.ts` by reusing `cleanTitle` from `src/orchestrator.ts`, remove unused `configText` from `src/config.ts`, remove one-off dev probe migration code from `src/server.ts`, neutralize Windows test fixture paths, and add public npm/GitHub metadata plus `.gitignore`/`.npmignore`.
18
+
19
+ ## 0.2.0 (2026-11-24)
20
+
21
+ - M7.4: bump package version to `0.2.0`, rewrite `README.md` for the complete v0.2.0 workflow, cut dated release notes, and verify clean `npm pack --dry-run` tarball contents.
22
+
23
+ - M7.3: add optional per-task builder file-scope gate (`allowedPaths`) with pure repo-relative/glob validation and matching in `src/scope.ts`, enforced structurally via `ctx.permission.hook('evaluate')` for `edit`/`write`/`patch`/`apply_patch`/`multiedit` (plus builder/reviewer prompt guidance and GUI/TUI/planner/report visibility).
24
+
25
+ - M7.2: add optional verification check scope (`scope: 'task' | 'final'`) so record-level final-gate checks defer until the final task review without splitting UI edits from tests, serialize parallel final reviews to avoid check skips, and enforce freshness against every task's latest build at sign-off.
26
+
27
+ - M7.1: fix closing HTML/XML tag path-redaction false positive (`</footer>`) in `src/report.ts` while keeping delimited paths redacted, shorten repeated task titles in Evidence and Reviews sections, and enforce explicit screenshot count and total-byte caps (`MAX_SCREENSHOT_COUNT = 8`, `MAX_SCREENSHOT_BYTES = 12 MiB` per check; `MAX_REVIEW_SCREENSHOTS = 12`, `MAX_REVIEW_SCREENSHOT_BYTES = 16 MiB` per review).
28
+
29
+ - M6.5: live Desktop e2e verified batched 9-question `/relay-configure` saved to plugin storage, completed `/relay` flow (planner switch/restore + token delta, live `relay_explore`, build, review inspecting 1280px and 390px screenshots, user-confirmed Allow, Sign off, Audit panel and Markdown export), live M6.3 width-gate/self-check escalation, and live `relay_plan_cancel`.
30
+
31
+ - Planner prompt: instruct the planner to use the `question` tool when requirements, scope, or acceptance criteria are ambiguous, conflicting, or high-risk before submitting, and note that Relay runs every verification check and reviewer width check after each individual task so tasks stay self-contained without splitting UI edits from their required test/screenshot updates.
32
+
33
+ - Pre-M6.5: use one model list with image capability labels and batch all nine `/relay-configure` questions in one question-tool call.
34
+
35
+ - M6.4 review fix cycle 2: redact file URLs, doubled drive slashes, UNC and home paths while preserving HTTP(S) and safe relative text; log report write failures server-side and label the unverified TUI export capture explicitly.
36
+
37
+ - M6.4 review fix cycle 1: redact delimited absolute paths while preserving URLs, improve report task/attempt/evidence context, return readable write errors, clarify current-record actions and add populated Audit verification.
38
+
39
+ - M6.4: add related-record Audit summaries, pure escaped Markdown reports, GUI save/copy feedback and explicit TUI audit/export commands writing only the validated report filename.
40
+
41
+ - M6.3 review fix cycle 1: cap cancellation reason tool input at 500 characters and document self-check counts as latest-report, prompt-dependent claims.
42
+
43
+ - M6.3: require effective explorer/viewport planning rules and reviewer width findings, add draft-only reasoned cancellation through shared withdrawal/restoration/lock cleanup, and expose failed builder self-check counts.
44
+
45
+ - M6.2 review fix cycle 2: persist lockdown ownership only after successful acquisition, clear failed ownership for retries, preserve subsequently added user denies, and clarify settings-dependent plan submission.
46
+
47
+ - M6.2 review fix cycle 1: isolate lockdown failures, preserve current user rules on release, reconcile terminal locks, validate option settings and enabled models, clarify manual start/effective roles, stamp saves after approval and return readable permission denials.
48
+
49
+ - M6.2: add fact-filtered `/relay-configure`, permission-gated saved configuration overlays, live model/limit reads, configurable auto-start, shared configuration summary and invoking-session shell self-reply lockdown.
50
+
51
+ - M6.1 review fix cycle 1: skip switches without an explicit session model, restore after prompt failure, show unavailable terminal/decreased token totals, and cover concurrent restoration, capture timeout and legacy GUI rendering.
52
+
53
+ - M6.1: replace the failed agent spike/fallback with temporary session model switching to the planner role. Restore once on submission or terminal closure, restore after failed draft creation, and log non-fatal host failures. Track optional primary-session token deltas separately from worker totals in GUI/TUI without changing legacy records or the schema version.
54
+
55
+ - M5.4: live end-to-end `/relay` run in Desktop (records `ecf41255`, `49702773`) completed plan approval (host prompt, `permission-assert`), build, Playwright check, review with exact screenshot inspection and user sign-off (per user report). Gaps for M6 recorded in M5-REPORT.md (planner model not applied, explorer not exercised live, single-viewport evidence, no planner token delta, no "already done" short-circuit, builder self-check failures not recorded).
56
+
57
+ - M5.3 review fix cycle 1: interrupt explorers on failed prompt/wait/context/token retrieval, clean reviewer attachment tracking on every settlement/stop/launch failure, and cap inspected names at 300 characters with a run-aware max(50, required attachment count) entry limit. Add failure, legacy-view, builder-rejection and 51-attachment regressions; defer unbounded attachment count and explorer concurrency to M6.
58
+
59
+ - M5.3: add optional explorer model and read-only relay_explore with child-session guards, explicit permission denials, 10-minute timeout/abort interruption, capped final text and token usage. Require complete exact-name screenshot inspection acknowledgments before review completion; retain legacy report reads and explain incomplete inspection in GUI/TUI.
60
+
61
+ - M5.2 review fix cycle 1: preserve full task text in planner instructions, select the newest active session record, explain invalid/duplicate/limited check and task inputs, and retain approved outcomes when automatic start fails. Add focused regressions and clarify user-confirmed live approval and planner trust boundaries.
62
+
63
+ - M5.2: add `/relay` with explicit planner prompt delivery, session-bound draft creation, duplicate-active-record rejection, relay_plan_add/relay_plan_submit/relay_status tools, and approved-only automatic start through the orchestrator. Add structural worker/probe guards and planner-tool permission denials. Spike proves callbacks do not forward the prompt automatically and session.prompt starts a turn. Live human approval through the host prompt launched the read-only task via approved-only autoStart; user confirmed clicking Allow. Test record cancelled, no agent Allow or sign-off. Live withdrawal was covered by M5.1, not repeated here.
64
+
65
+ - M5.1 review fix cycle 2: block every RPC mutation except withdraw-first cancel while plan approval is pending, including owner/status edits; preserve orchestrator-internal store writes and restore RPC edits after withdrawal.
66
+
67
+ - M5.1 review fix cycle 1: enforce withdrawal guards inside serialized approval/sign-off/manual writes and before opening prompts; token-guard approved outcomes. Block plan edits during pending approval, withdraw before cancel, preserve request-key revision, and show a sanitized named-check recovery error. Add queued-Allow, pre-prompt, late-rejection, pending-edit/cancel and old-revision regressions; document the cross-platform exit fallback.
68
+
69
+ - M5.1 live follow-up: verify CLI approval returns pending in 145.093 ms, host permission listing includes the plugin prompt, TUI withdrawal removes it without approving, and cancel the test record. Replace the failed TUI capture with command/result evidence; saved permissions and protected record hash remain unchanged.
70
+
71
+ - M5.1: non-blocking plan approval with token-bound withdrawal, GUI withdrawal action and `/relay-withdraw`; ignore late Allow after withdrawal and reject matching host prompts best-effort. Re-validate legacy checks, reject control/format characters in reason and screenshot directory, accept a validated session for unbound manual verification, and harden non-Windows process-tree termination plus exit/close fallback. Add regression tests and M5.1 verification evidence.
72
+
73
+ - M4 review fix cycle 3: reject invisible control/format characters in new check names and commands, preserve complete visible command display, and separate the 160-character addCheck input schema from the legacy-compatible 1000-character record output schema. Add store and RPC schema regressions.
74
+
75
+ - M4 review fix cycle 2: limit check commands to 160 characters in storage, RPC and GUI input, and show listed commands in full in approval metadata/messages and TUI status. Add exact 160/161 boundary and full-command visibility regressions; amend the contract and verification documentation.
76
+
77
+ - M4 review fix cycle 1: expose approved check commands/counts, abort running checks on interrupt/cancel, re-hash screenshot bytes before attachment, deny manual-verification authority in both probes, improve manual prompt context and image-recovery guidance, cap/uniquely name checks, shorten evidence titles, hide empty screenshot counts/repeated not-applicable reasons, and scroll/focus GUI errors. Add regression tests and affected M4/TUI captures; document deferred process-close/tree cleanup and unbound manual-session limitations.
78
+
79
+ - M4 milestone 2: Verification GUI/TUI check controls, evidence labels and permission-gated manual forms; 20 narrow/wide fixture captures and read-inspected live Desktop/TUI evidence. Live missing-Playwright sandbox pauses unverified; web sandbox plugin-run Edge check and screenshot review succeed, awaiting human sign-off. Document the orphaned approval workaround and retained timeout/orphan-cleanup limits.
80
+
81
+ - M4 Desktop scroll fix: constrain Relay to its host height with vertical scrolling so Tasks and plan approval remain reachable; show the policy without repeating the check name. Add constrained-height smoke assertions at 280/320/480 and preserve existing captures while regenerating M4 evidence.
82
+
83
+ - M4 milestone 1: schema-v3 draft-only verification checks, build-bound evidence, plugin-run command/Playwright adapter, verification pauses and bounded fix cycles, screenshot review attachments, permission-gated manual verification, evidence-aware sign-off, RPC schemas and shared view helpers. Panels and live verification remain milestone 2 work.
84
+
85
+ - M3 review fix cycle 3: share the 10-second host-call bound across stop interruption, failed-launch cleanup interruption and end-of-run token lookup. Add fake-timer regressions proving failed launch and missing token responses cannot indefinitely wedge the record queue; preserve existing error log patterns and omit unavailable tokens.
86
+
87
+ - M3 review fix cycle 2: assert exact worker permission arrays, bound each stop-session interrupt wait to 10 seconds with timer cleanup, cover a never-resolving host interrupt using fake timers, and capture the completed sandbox TUI with corrected owner/finding/ellipsis formatting. No live workers or record mutations.
88
+
89
+ - M3 review fix cycle 1: share contains-style `*opencode*` shell denial across workers/probes, add probe authority/delegation denies and permission-set tests, assert SDK Tool.Error through registered relay_report, fix singular findings and terminal summary punctuation/owner wrapping, align token fixture fix cycles, and document empirical matcher evidence, human sign-off attribution and interrupt-queue risk.
90
+
91
+ - M3 milestone 3: live sandbox record completed two build/review tasks using configured builder and reviewer workers, with session permission/report evidence, run tokens/durations and Desktop/TUI captures. Fixed singular builder-check wording and made exhausted-fix fixture show two fix cycles and attempt 3. Sign-off resolved through host permission; exact click attribution remains unverified. No rerun or cleanup performed.
92
+
93
+ - M3 milestone 2 verified: run-aware GUI/TUI stages, attempts, bounded summaries, findings and self-reported checks, token totals, escalation guidance, running edit locks and sign-off pending/denied feedback. Added relay-signoff, 167 GUI smoke captures, read-only Desktop/TUI evidence and complete screenshot manifest; 74 tests pass.
94
+
95
+ - M3 ordering fix: listRuns resolves equal startedAt timestamps by attempt, build-before-review stage, then id, keeping orchestrator and panel latest-report selection deterministic. Added an equal-timestamp ordering/latest-report regression.
96
+
97
+ - M3 milestone 2 work in progress: run-aware shared task stages, attempts, report summaries, findings/check labels and token totals; GUI sign-off pending/denied states and running task locks; TUI relay-signoff and mocked panel coverage. Verification paused on existing M1 same-timestamp run-ordering failure before completion.
98
+
99
+ - M3 milestone 1: serialized build/review orchestration, project-scoped run audit storage, session-bound relay_report, bounded findings/fix cycles and explicit interruption/resume; worker permission restrictions, token-only run snapshots, listRuns RPC and host-permission sign-off. Manual task edits are rejected while running. Existing Complete controls route through signOff pending milestone 2 panel work.
100
+
101
+ - GUI startup load retry: the automatic refresh and role validation on mount, session change or reconnect retry after 0.5 s, 1 s and 2 s before showing "Could not refresh" or "Could not validate role configuration". Manual Refresh and Validate config still report immediately. Failures are logged with console.warn including the original error. Pending retries are cancelled on session change or panel close. Smoke adds gui-panel-startup-retry-{recovered,failed}-{280,320,480}.png.
102
+
103
+ - Post-sign-off Desktop check (docs only): the Relay tab works with the { package, options } entry. Desktop 2.3.2 lists only built-in launchers in the Add tab menu; Relay opens from the command palette ("Relay status") or /relay-status. desktop-m2-b-roles.png captured. No code change.
104
+ - Milestone 5 review fix cycle 3: separate unknown-role validation from role parsing to remove a dangling else and duplicate shape errors; add exact mixed-invalid-role and valid-model-plus-unknown-key regressions. Rebuilt GUI bundle is byte-identical.
105
+ - Milestone 5 review fix cycle 2: require an exact normalized red probe answer, use invalid_op for concurrent probes, guard legacy cleanup storage failures, reject unknown role keys, gate GUI probing on reviewer validity, separate configuration feedback from record errors, improve TUI probe messages and role identity layout, and correct realistic status/token smoke fixtures.
106
+ - Milestone 5 fix cycle 1: log image probe exceptions, return non-cached host errors separately from completed vision answers, remove only the exact known stale exception cache via storage API, add retry/logging regressions and inspect Desktop GUI loader evidence without config edits or probe retries.
107
+ - Phase B milestone 5: crypto-free role options parsing, role/model validation and explicit cached image probe RPCs/panel actions; per-record reconciliation continuation and phase-specific approval confirmation. Global options use the supported { package, options } entry. The one live image check failed with zero tokens; final enableProbe omitted.
108
+ - Phase B milestone 4 fix cycle 1: isolate crypto-free model code from storage, enforce terminal edit locks/draft-only approval/nonempty completion gates, preserve v2 approval confirmation by plan revision, improve owner and interrupt controls, cap owner sessions, test reconciliation races/error logging and add realistic v2 plus live Desktop/TUI evidence.
109
+ - Phase B milestone 4 (B1/B2/B4): schema-v2 read migration, plan-scoped approval, explicit record lifecycle, owned-task scheduling and fix-cycle limits, queued startup interruption, matching GUI/TUI controls and lifecycle commands, expanded regression/smoke and real protected-record/TUI evidence.
110
+ - Phase A fix cycle 1: expose normal-action aria-busy and wait cursors without locking approval prompts, expand Unicode prompt sanitization, handle task titles without count/revision metadata, remove the unused GUI error import, separate error banners from adjacent controls, and correct Desktop prompt evidence.
111
+ - Phase A milestone 2 (A2/A3/A5): retain action errors across live refreshes with separate reconnect feedback; keep the panel interactive during approval; include sanitized bounded task titles in prompts; follow host appearance with contrasting fallback and disabled palettes; advance stale mock revisions and expand GUI/real Desktop evidence.
112
+ - Phase A milestone 1 (A1/A4): normalize string, Error and RPC failures to readable messages with a generic unknown-error fallback; silence and assert expected server fault logs; add sectioned terminal status with ordered counts and a 12-task cap, plus reactive refresh and toast regressions.
113
+ - Fix cycle 11, round 2: restrict duplicate-error suppression to requestApproval and matching visible stale/rejected outcomes; preserve stale mutation banners even with an approval result visible, add zero/four-history cap coverage, and qualify historical terminal-only prompt claims.
114
+ - Cycle 11 contrast follow-up: use existing host text-strong for primary text and unmixed text-base for secondary text, retaining mocked-host fallbacks. Verify both Desktop themes with non-persistent media emulation, revision-18 approval, single stale outcomes in Desktop/terminal, capped approvals and Desktop-to-terminal live refresh.
115
+ - Fix cycle 11: share stale/rejected error suppression after snapshot refresh, cap approval history at three plus earlier count, and derive panel muted/border/control/focus colors from host light/dark tokens.
116
+ - Correction to cycle 8's generic-host-rendering claim below: this limitation is terminal-only. Desktop renders the hook message and revision-bound resource. Live Allow always created no saved rows and the next revision prompted again in OpenCode 2.3.2.
117
+ - Fix cycle 10: bind pending markers and stale outcome feedback to the current revision, protect original errors during settlement refresh, gate Escape by focused active panel and clear focus on relay-close.
118
+ - Key outcome history per record, hide outcome text during current approval waits, remove the agent-added unused terminal wait flag and verify live stale approval and refreshed terminal captures.
119
+ - Fix cycle 9: map the real-host Permission.DeclinedError plain rejection to typed approval_denied, publish rejected feedback without changing approvals, add a regression and verify the actual terminal Reject path.
120
+ - Fix cycle 8: scope terminal Escape to focused Relay content with pass-through otherwise, suppress old/duplicate result toasts, expire result lines by revision, show pending revision explicitly and disable duplicate desktop approval.
121
+ - Check revision before marking a request pending; document generic host permission rendering (terminal only) and unsettled-prompt workaround; add focus, rejected-result and result-line regressions plus six desktop outcome captures.
122
+ - Fix cycle 7: add panel-scoped Escape and relay-close recovery, non-focusable terminal content, authoritative host approval settlement after client disconnect and reconnect-visible pending/results.
123
+ - Show approval/rejection/stale feedback in terminal toasts and desktop status; add abort/revision/pending regressions and real-terminal focus and recovered-approval evidence.
124
+ - Rename to Relay Orchestration: opencode-relay-orchestration package/plugin/RPC identity, relay commands and permission/storage/UI namespaces; leave prior host test data untouched.
125
+ - Fix cycle 6: return explicit terminal cleanup, own and dispose the setup watcher, test ownerless setup/disposal, document palette discovery and require the verified registerHooks-compatible Node engine range.
126
+ - Fix cycle 5: register terminal commands once from the app slot in global mode, expose all four commands in the palette, retain the status panel/dialog fallback and dispose both slot claims.
127
+ - Add a mocked actual-TUI-setup regression for registration, repeat renders, fallback and cleanup; consistently name this plugin's records orchestrator records.
128
+ - Rename the uninstalled package and its runtime, permission, storage, UI and command identifiers to OpenCode Orchestrator before the first real-host installation.
129
+ - Fix cycle 3: clear record/task drafts on session changes, verify approval deduplication survives abort until the host prompt settles, measure limits after trimming, and align the smoke approval source with permission-assert.
130
+ - Add aborted-prompt and trimmed-limit regressions; regenerate and visually inspect all 17 GUI captures.
131
+ - Fix cycle 2: isolate pending GUI operations across session switches, validate creation sessions, sanitize Unicode prompt text safely, preserve created probe markers and validate optional variants.
132
+ - Add record/task limits, post-prompt abort coverage, real shared-format assertions, visible TUI creation errors, portable smoke browser fallback and pending-status spacing; regenerate and inspect all 17 captures.
133
+ - Implement revisioned project-scoped records, a serialized storage queue, closed task mutations and post-persist RPC events.
134
+ - Add scoped permission evaluation for explicit revision-bound plan approval and an unprompted pinned-model reviewer compatibility probe.
135
+ - Add shared terminal/text/desktop views, explicit commands and snapshot refresh on matching live events and reconnect.
136
+ - Add store/server/view tests and built-bundle Playwright evidence at 320 and 480 pixels.
137
+ - Document unresolved OpenTUI Node engine compatibility, production dependency audit findings and real-host verification boundaries.
138
+ - Scaffold the Milestone 1 package manifest and install the pinned OpenCode 2.3.2 SDK for compatibility inspection.
139
+ - Deliver scoped permission-assert approval with record-session validation, sanitized prompts, in-flight deduplication and cancellation checks; preserve unexpected errors as internal failures.
140
+ - Harden default-off reviewer probes with parent/model validation; move Solid to peer/development dependencies.
141
+ - Repair form success/error handling, pending/disconnected presentation and human-readable dates; add approval validity, pagination, consistency and event-failure tests, plus 17 reviewed GUI captures.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nandoblanco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,315 @@
1
- # Temporary Holding Version
1
+ # opencode-relay-orchestration
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Multi-model brainstorm, plan, build, verify, and review orchestration plugin for OpenCode**: coordinates dedicated `planner`, `builder`, `reviewer`, and read-only `explorer` models with brainstorm-first alignment, revision-bound human plan approvals, structural file-scope gates, automated command and Playwright verification, and redacted Markdown audit reports in both the TUI and OpenCode Desktop.
4
+
5
+ | OpenCode Desktop | OpenCode TUI |
6
+ | :---: | :---: |
7
+ | [![opencode-relay-orchestration Desktop preview](./assets/screenshot.png)](./assets/screenshot.png) | [![opencode-relay-orchestration TUI preview](./assets/screenshot-tui.png)](./assets/screenshot-tui.png) |
8
+ | [View full size](./assets/screenshot.png) | [View full size](./assets/screenshot-tui.png) |
9
+
10
+ *Note: Previews were rendered in headless Chromium via Playwright from the plugin's actual Desktop (`dist/gui-experimental.cjs`) and TUI (`src/tui.ts`) UI code using synthetic fixture data and a simulated host frame, rather than captured from a live OpenCode window or terminal.*
11
+
12
+ ## OpenCode Desktop Support
13
+
14
+ **Available in OpenCode Desktop as well as the TUI.** Inspect active Relay records, tasks, verification checks, evidence, approvals, role validation, and redacted audit summaries in a persistent `Relay` side panel (`opencode-relay-orchestration:relay-status`), or trigger `/relay-status` from the slash menu and command palette without spending a model turn.
15
+
16
+ One global OpenCode V2 plugin entry loads the server hooks, agent tools, TUI panel, and Desktop side panel together. Installing the plugin does not start tasks, prompt models, or create records until you invoke `/relay`, `/relay-configure`, or create a record explicitly; see [Installation](#installation) for setup.
17
+
18
+ ## Background
19
+
20
+ Multi-model coding workflows often start as custom slash prompts or `AGENTS.md` checklists asking one chat session to plan, spawn subagents, run tests, and review its own work. In daily use, that prompt-only approach hits three recurring limitations:
21
+
22
+ 1. **Weak separation of duties**: Prompt rules alone cannot stop a builder from editing out-of-scope files, self-approving a plan, or skipping Playwright screenshots when context grows long.
23
+ 2. **Unverified claims and lost state**: Verification output, fix-cycle counters, screenshot hashes, and token totals live only as transient chat text that disappears or drifts across compactions.
24
+ 3. **Manual model juggling**: Switching between a planning model, a fast builder, a read-only explorer, and a vision-capable reviewer requires repetitive manual configuration and offers no structured audit trail.
25
+
26
+ `opencode-relay-orchestration` moves that workflow into OpenCode's plugin runtime:
27
+
28
+ 1. **Revision-bound human gates (`relay.approve`, `relay.signoff`, `relay.verify`, `relay.configure`)**: Plans, manual verifications, configuration saves, and final sign-offs are enforced through OpenCode's native permission hooks pinned to exact record revisions.
29
+ 2. **Isolated role workers & structural enforcement**: Builders run in isolated child sessions with optional `allowedPaths` file-scope guards in `ctx.permission.hook('evaluate')`, automated checks run in the plugin runtime (`command` and `playwright` adapters), and read-only reviewers inspect every attached screenshot by exact filename.
30
+ 3. **Zero-token TUI & Desktop inspection**: Status, checks, approvals, role validation, audit summaries, and redacted Markdown report exports run over typed `RelayRpc` calls without an LLM turn.
31
+
32
+ ## Features
33
+
34
+ | Feature | Details |
35
+ | :--- | :--- |
36
+ | Role-based multi-model routing | Assign distinct models and optional variants to `planner`, `builder`, `reviewer` (image-input required), and optional read-only `explorer` |
37
+ | Interactive setup (`/relay-configure`) | Queries enabled OpenCode models and image capabilities, asks all 10 setup questions in one batched `question` prompt (4 roles + 6 settings), and saves to plugin storage (`relay/config`) behind a `relay.configure` permission gate |
38
+ | Brainstorm-first planning (`/relay <task>`) | Enabled by default (`brainstormFirst: true`): forces Phase 1 read-only exploration, 2-3 approaches with tradeoffs/risks/non-goals, and `question` alignment before any `relay_plan_add` or `relay_plan_submit` calls (with a fast-track skip option or `relay_plan_cancel`) |
39
+ | Revision-bound plan approvals | Plans (`tasks`, `allowedPaths`, `checks`) are approved at a specific `planRevision` through OpenCode's native `relay.approve` permission prompt and can be withdrawn cleanly while pending |
40
+ | Automated build, verify, review, fix cycles | Isolated builder sessions execute tasks, plugin-run verification checks execute `command` or `playwright` suites, and read-only reviewer sessions report `approve` or `changes` up to `maxFixCycles` |
41
+ | Per-task & final-gate checks | Checks default to `scope: "task"` (run after each task build) or set `scope: "final"` to defer until the final task review; sign-off enforces freshness against every task's latest build |
42
+ | Structural builder file-scope gate (`allowedPaths`) | Up to 20 repo-relative paths or globs per task structurally deny `edit`, `write`, `patch`, `apply_patch`, and `multiedit` calls outside scope via `ctx.permission.hook('evaluate')` |
43
+ | Screenshot hashing & attachment caps | Playwright checks collect fresh PNGs under `screenshotDir` (default `.screenshots`), SHA-256 hash them, fail loudly above 8 files or 12 MiB per check, and escalate reviews above 12 files or 16 MiB combined |
44
+ | Redacted Audit & Markdown export | Inspect related records, worker token totals, planner session token delta, evidence, and reviews in TUI (`/relay-audit`, `/relay-export`) or Desktop (`Export Markdown` / `Copy Markdown`), with local path redaction |
45
+ | OpenCode TUI & Desktop GUI parity | Native OpenTUI panel (`src/tui.ts`) and Desktop side panel (`src/gui.tsx`, bundled to `dist/gui-experimental.cjs`) backed by `RelayRpc` (`src/rpc.ts`) |
46
+
47
+ ## Installation
48
+
49
+ ### Option 1: OpenCode Plugin CLI (Recommended)
50
+
51
+ Install with OpenCode's native plugin CLI. OpenCode downloads the package from npm (or GitHub) into its own cache automatically and adds one entry to `~/.config/opencode/opencode.jsonc` that loads the server hooks, planner/worker tools, TUI panel, and Desktop side panel together:
52
+
53
+ ```sh
54
+ opencode plugin add @nandoblanco/opencode-relay-orchestration
55
+ # Auto-update on startup and every 24 hours:
56
+ opencode plugin add @nandoblanco/opencode-relay-orchestration@latest
57
+ # Or install directly from GitHub:
58
+ opencode plugin add github:nandoblanco/opencode-relay-orchestration
59
+ ```
60
+
61
+ ### Option 2: Manual Configuration
62
+
63
+ Add `@nandoblanco/opencode-relay-orchestration` to `"plugins"` in the global `~/.config/opencode/opencode.jsonc` (or project `./opencode.jsonc` / `./.opencode/opencode.jsonc`). Static `options` act as defaults and can be overridden at any time by `/relay-configure` in plugin storage (`relay/config`):
64
+
65
+ ```jsonc
66
+ {
67
+ "plugins": [
68
+ {
69
+ "package": "@nandoblanco/opencode-relay-orchestration",
70
+ "options": {
71
+ "limits": {
72
+ "maxRunningTasks": 1,
73
+ "maxFixCycles": 2
74
+ },
75
+ "widths": [1280, 390],
76
+ "autoStart": true,
77
+ "explorer": true,
78
+ "brainstormFirst": true,
79
+ "enableProbe": false
80
+ }
81
+ }
82
+ ]
83
+ }
84
+ ```
85
+
86
+ ### Option 3: From a Local Directory
87
+
88
+ Use Node.js `^22.15.0 || >=23.5.0`. Clone this repository, install dependencies, and run `npm run build` to build `dist/gui-experimental.cjs` for OpenCode Desktop, then reference the directory in `opencode.jsonc`:
89
+
90
+ ```sh
91
+ npm ci
92
+ npm run build
93
+ ```
94
+
95
+ ```json
96
+ {
97
+ "plugins": ["file:///path/to/opencode-relay-orchestration"]
98
+ }
99
+ ```
100
+
101
+ ## Usage
102
+
103
+ ### Interactive Setup (`/relay-configure`)
104
+
105
+ Relay ships with no hardcoded default models. Configure at least `builder` and `reviewer` before running `/relay` (either with `/relay-configure` or static `options.roles` in `opencode.jsonc`). Leaving `planner` unset runs planning on your current session model; leaving `explorer` unset omits `relay_explore`.
106
+
107
+ Run `/relay-configure` inside an OpenCode session. Relay queries your currently enabled models and presents one batched `question` prompt containing 10 questions (4 role assignments + 6 settings):
108
+
109
+ 1. **Roles**: `planner`, `builder`, `reviewer` (image-capable models only), and `explorer`, each offering top 3 recommended candidates plus write-in support and optional variants.
110
+ 2. **Settings**: fix cycle limit (`0` to `5`), Playwright screenshot widths (`1` to `4` integers from `320` to `3840`), `autoStart` (`true`/`false`), parallel tasks (`1` to `4`), `explorer` (`true`/`false`), and `brainstormFirst` (`true`/`false`).
111
+
112
+ Confirmed settings are validated by `validateSettings()` and persisted to plugin storage (`relay/config`) behind the `relay.configure` permission prompt.
113
+
114
+ ### Orchestration Workflow (`/relay <task>`)
115
+
116
+ 1. **Brainstorm first (`/relay <task>`)**: Relay first verifies that `builder` and `reviewer` models are configured; if either is missing, `/relay` fails fast before creating a draft record, switching models, or starting a model turn and directs you to `/relay-configure`. Otherwise it creates a `draft` record bound to the current session, temporarily switches the session model to `roles.planner` when configured (keeping the current session model if `planner` is unset, and restoring the previous model on submission, cancellation, or closure), and enters **Phase 1: Brainstorm first** (when `brainstormFirst` is `true`, the default). The planner explores read-only (including via `relay_explore`), surfaces assumptions, presents 2-3 approaches with tradeoffs, risks, and non-goals, and aligns with you via `question` before calling any plan tools (with a fast-track option to draft immediately, or `relay_plan_cancel` if you decide not to build).
117
+ 2. **Draft plan**: Once you confirm direction (or immediately when `brainstormFirst` is `false` and requirements are clear), the planner adds tasks (strings or `{ title, allowedPaths }`) and verification checks with `relay_plan_add`.
118
+ 3. **Approve plan**: Calling `relay_plan_submit` opens OpenCode's native `relay.approve` permission prompt pinned to the exact `planRevision`. Unneeded drafts can be closed with `relay_plan_cancel`, and pending requests can be withdrawn via `/relay-withdraw` or the GUI.
119
+ 4. **Build, verify, review**:
120
+ - Builders run in isolated child sessions with `subagent`, `question`, `relay.*`, and `*opencode*` shell commands denied. Tasks with `allowedPaths` also block out-of-scope edits structurally.
121
+ - Applicable checks run after each build (`scope: "task"` per task, `scope: "final"` on the final task review). Playwright checks collect fresh PNGs under `screenshotDir` (default `.screenshots`), SHA-256 hash them, and attach them to the reviewer prompt.
122
+ - Reviewers run read-only (`edit`, `write`, `shell`, `subagent`, `question`, `relay.*` denied), inspect every attached screenshot by exact filename, and verify required widths (`[1280, 390]` by default) on UI changes.
123
+ - `changes` verdicts increment `fixCycles` and re-queue the builder up to `maxFixCycles`; exceeding the cap or receiving a `blocked` build interrupts the record for human intervention.
124
+ 5. **Sign off**: Once all tasks are `completed` and every applicable check has fresh `passed` or authorized `manually verified` evidence included in an approving review, sign off via the Desktop **Sign off** button or TUI `/relay-signoff` (`relay.signoff` permission prompt).
125
+
126
+ ### Zero-Token TUI & Desktop GUI Commands
127
+
128
+ 1. **Interactive `/relay-status` panel**: Run `/relay-status` to open the Relay panel in the TUI (`opencode-relay-orchestration:status`) or focus the persistent `Relay` side panel in OpenCode Desktop (`opencode-relay-orchestration:relay-status`).
129
+ 2. **Audit & report export**: Run `/relay-audit` to view summaries for related records, or `/relay-export` to write `<project>/.relay/reports/relay-<id8>.md`. In Desktop, expand the **Audit** section to inspect summaries or click **Export Markdown** / **Copy Markdown**.
130
+ 3. **Command palette**: Press `Ctrl+P` (`Cmd+K` / `Ctrl+K` in Desktop) and search `Relay` to access status, validation, plan actions, approvals, and export commands without starting a model turn.
131
+
132
+ ## Commands Reference
133
+
134
+ ### Server Slash Commands (LLM-Guided)
135
+
136
+ | Command | Description |
137
+ | :--- | :--- |
138
+ | `/relay <task>` | Verify `builder` and `reviewer` models are configured (failing fast to `/relay-configure` if missing), create a `draft` Relay record, switch to `roles.planner` when set, brainstorm first (when `brainstormFirst` is enabled), and draft/submit a plan for human approval |
139
+ | `/relay-configure` | Discover enabled OpenCode models and image capabilities, run the 10-question batched setup prompt, and save validated settings via `relay_config_set` |
140
+
141
+ ### TUI & Desktop Panel Commands (Zero-Token)
142
+
143
+ | Command | UI Availability | Description |
144
+ | :--- | :--- | :--- |
145
+ | `/relay-status` | TUI & Desktop | Open the Relay status panel showing active record, tasks, checks, evidence, approvals, and role validation |
146
+ | `/relay-audit` | TUI *(GUI Audit section)* | Show related records, run counts, token totals, and latest review verdicts |
147
+ | `/relay-export` | TUI *(GUI Export/Copy)* | Write a redacted Markdown audit report to `<project>/.relay/reports/relay-<id8>.md` |
148
+ | `/relay-validate-config` | TUI *(GUI Validate button)* | Validate configured role models, variants, tools, and image capabilities without prompting a model |
149
+ | `/relay-probe-image` | TUI *(GUI Probe button)* | Explicitly run a one-pixel vision probe against the configured `reviewer` model (only when `enableProbe: true`) |
150
+ | `/relay-new` | TUI *(GUI New record)* | Create a new `draft` Relay record without starting work |
151
+ | `/relay-add-task` | TUI *(GUI Draft form)* | Add a task (with optional comma-separated `allowedPaths`) to the active draft |
152
+ | `/relay-assign-task` | TUI *(GUI Task owner)* | Assign an owner role (`planner`, `builder`, `reviewer`) and optional session ID to a non-running task |
153
+ | `/relay-add-check` / `/relay-remove-check` | TUI *(GUI Verification form)* | Add or remove a `command` or `playwright` verification check (`automated-required`, `manual-allowed`, or `not-applicable`; scope `task` or `final`) in `draft` |
154
+ | `/relay-approve` / `/relay-withdraw` | TUI *(GUI Approvals)* | Request revision-bound `relay.approve` plan approval or withdraw a pending approval request |
155
+ | `/relay-start` / `/relay-interrupt` / `/relay-resume` | TUI *(GUI Phase actions)* | Explicitly start an approved record, interrupt a running record with a reason, or resume an interrupted record |
156
+ | `/relay-manual-verify` | TUI *(GUI Evidence action)* | Request `relay.verify` permission to record a manual verification note for an `unverified` `manual-allowed` check |
157
+ | `/relay-signoff` / `/relay-complete` | TUI *(GUI Sign off button)* | Request `relay.signoff` permission to complete the record after all tasks and checks satisfy sign-off freshness |
158
+ | `/relay-cancel` / `/relay-close` | TUI *(GUI Cancel / close tab)* | Cancel the active Relay record or close the TUI panel and return focus to the composer |
159
+
160
+ ## Keyboard Shortcuts
161
+
162
+ | Key | Scope | Action |
163
+ | :--- | :--- | :--- |
164
+ | `Ctrl+P` | OpenCode TUI | Open command palette and run any `Relay` command |
165
+ | `Esc` | Focused TUI Relay panel | Close `opencode-relay-orchestration:status` panel and return to the composer (`relay-panel-escape`) |
166
+ | `Cmd+K` / `Ctrl+K` | OpenCode Desktop | Open command palette and run `Relay status` |
167
+
168
+ ## How It Works (Architecture & Internals)
169
+
170
+ ### 1. Configuration Resolution & Role Validation (`parseConfig`, `effectiveConfig`, `validateSettings`)
171
+
172
+ `src/config.ts` resolves effective settings by merging static plugin options from `opencode.jsonc` (`parseConfig`) with persisted settings stored in OpenCode plugin storage under `relay/config` (`effectiveConfig`):
173
+
174
+ 1. Static options (`roles`, `limits`, `widths`, `autoStart`, `explorer`, `brainstormFirst`, `enableProbe`) supply defaults (`maxRunningTasks: 1`, `maxFixCycles: 2`, `widths: [1280, 390]`, `autoStart: true`, `explorer: true`, `brainstormFirst: true`, `enableProbe: false`).
175
+ 2. Saved `relay/config` values override static options. Setting `explorer: false` strips `models.explorer` from the effective configuration.
176
+ 3. `candidates()` filters enabled OpenCode models that support `tools`, are not `deprecated`, and (for `reviewer`) declare `image` input. `validateSettings()` validates every role model, variant, limit (`maxFixCycles` `0..5`, `maxRunningTasks` `1..4`), width (`1..4` integers in `320..3840`), and boolean toggle before `relay.configure` approval.
177
+ 4. Optional reviewer vision probes (`probeImage`) cache results in plugin storage under `relay/image-probes/<encodedModel>` (`probeKey()`).
178
+
179
+ ### 2. Two-Phase Planner Flow & Session Model Switching (`registerPlanner`)
180
+
181
+ `src/planner.ts` registers `/relay`, `/relay-configure`, and the six planner tools (`relay_plan_add`, `relay_plan_submit`, `relay_plan_cancel`, `relay_status`, `relay_explore`, `relay_config_set`):
182
+
183
+ - When `/relay <task>` runs, Relay first checks effective configuration for `models.builder` and `models.reviewer` and fails fast with a `/relay-configure` message if either is missing (before creating a draft record, switching models, or prompting). When configured, it creates a `draft` record bound to `input.sessionID`, records the session's starting token totals (`tokensAtStart`), switches the session model to `roles.planner` if configured (otherwise keeping the current session model), and restores `previousModel` (recording `tokensAtEnd`) when the plan is submitted, cancelled, or closed.
184
+ - When `brainstormFirst !== false`, the prompt enforces **Phase 1: Brainstorm first** (prohibiting `relay_plan_add` and `relay_plan_submit` until read-only exploration, 2-3 approaches with tradeoffs/risks/non-goals, and `question` alignment complete) followed by **Phase 2: Draft and submit plan**. When `brainstormFirst === false`, the planner clarifies only when requirements are ambiguous, conflicting, or high-risk.
185
+ - `relay_explore` launches a read-only child session using `roles.explorer` with `edit`, `write`, `shell`, `subagent`, `question`, `relay.*`, and all planner/worker tools denied.
186
+
187
+ ### 3. Revision-Bound Storage, Concurrency & Permission Gates (`createStore`, `evaluateApproval`, `lockdown`)
188
+
189
+ `src/store.ts` and `src/server.ts` persist records, runs, and evidence in OpenCode plugin storage using a single serialized write queue (`serialize()`) and optimistic revision checks (`expectedRevision`):
190
+
191
+ - Storage keys are namespaced per project: `relay/records/<projectID>/<recordID>`, `relay/runs/<projectID>/<recordID>/<runID>`, and `relay/evidence/<projectID>/<recordID>/<evidenceID>`. `migrate()` upgrades older schema versions automatically to `schemaVersion: 3`.
192
+ - `ctx.permission.hook('evaluate')` intercepts `relay.approve`, `relay.signoff`, `relay.verify`, and `relay.configure`, forces `effect = 'ask'` (unless already denied), and builds concise human-readable approval prompts (`evaluateApproval()`).
193
+ - While a session has an active Relay record or `/relay-configure` in progress, `lockdown()` adds a temporary `{ action: 'shell', resource: '*opencode*', effect: 'deny' }` rule (tracked under `relay/lockdown/<sessionID>`) so models cannot invoke the OpenCode CLI to self-approve prompts, and removes only plugin-owned rules when done.
194
+
195
+ ### 4. Isolated Worker Orchestration & Structural File Scope (`createOrchestrator`, `validateAllowedPaths`, `checkScopeViolation`)
196
+
197
+ `src/orchestrator.ts` schedules up to `maxRunningTasks` concurrent tasks and alternates `builder` and `reviewer` child sessions:
198
+
199
+ - **Builder isolation**: Denies `subagent`, `question`, `relay.*`, all planner tools, and `*opencode*` shell commands. When a task defines `allowedPaths`, `validateAllowedPaths()` (`src/scope.ts`) normalizes up to 20 repo-relative paths or globs (rejecting absolute paths, drive prefixes, UNC paths, `..` traversal, and control characters). During the builder run, `ctx.permission.hook('evaluate')` calls `checkScopeViolation()` to structurally deny `edit`, `write`, `patch`, `apply_patch`, and `multiedit` calls outside `allowedPaths`.
200
+ - **Reviewer isolation**: Denies `edit`, `write`, `shell`, `subagent`, `question`, `relay.*`, and all planner tools. Reviews receive verified plugin-run evidence, self-reported builder notes labeled as unverified data, and every collected screenshot attachment. Missing any exact attachment filename in `inspected` escalates the task.
201
+ - **Fix loop**: A reviewer `changes` verdict increments `task.fixCycles` and re-queues the builder while `fixCycles <= maxFixCycles`; exceeding `maxFixCycles` or a builder `blocked` outcome marks the task `blocked` and interrupts the record.
202
+
203
+ ### 5. Verification Checks, Check Scopes & Screenshot Caps (`preflight`, `runCheck`)
204
+
205
+ `src/verify.ts` executes verification checks in the record directory with plugin privileges after each task build:
206
+
207
+ - **Check scopes**: `scope: "task"` (default) runs after every task build; `scope: "final"` defers on intermediate tasks and runs once on the final task review. Sign-off verifies that the approving final review started on or after every task's latest build so a subsequent rebuild cannot bypass final-gate checks.
208
+ - **Check policies**: `automated-required` must pass automatically; `manual-allowed` interrupts the record when `unverified` so a user can authorize a manual note via `relay.verify`; `not-applicable` requires a non-empty `reason` and is skipped.
209
+ - **Playwright screenshot caps**: `preflight()` verifies `child_process` and `playwright` / `@playwright/test` availability. `runCheck()` spawns the check with a default 300s timeout (`timeoutMs` max `1800000` ms), captures the last 4,000 characters of output, collects fresh PNGs written under `screenshotDir` (default `.screenshots`), hashes them with SHA-256, and enforces `MAX_SCREENSHOT_COUNT = 8` / `MAX_SCREENSHOT_BYTES = 12 MiB` per check and `MAX_REVIEW_SCREENSHOTS = 12` / `MAX_REVIEW_SCREENSHOT_BYTES = 16 MiB` per review.
210
+
211
+ ### 6. Interactive OpenTUI & OpenCode Desktop Panel Architecture (`src/tui.ts`, `src/gui.tsx`, `src/rpc.ts`)
212
+
213
+ - **Typed RPC Bridge (`src/rpc.ts`)**: `RelayRpc` (`id: 'opencode-relay-orchestration'`) exposes `listRecords`, `getSnapshot`, `createRecord`, `mutate`, `requestApproval`, `withdrawApproval`, `listRuns`, `listEvidence`, `recordManual`, `signOff`, `validateConfig`, `probeImage`, and `exportReport`, plus the `changed` live-update event stream.
214
+ - **OpenTUI Panel (`src/tui.ts`)**: Renders structured OpenTUI `box`/`scrollbox` cards using live `ctx.theme` tokens for the active record hero, task list, verification evidence, pending approvals, and bottom role validation rows, with `Esc` focus handling and 20 slash/palette commands.
215
+ - **OpenCode Desktop Side Panel (`src/gui.tsx`, `src/gui.css`)**: Bundled to `dist/gui-experimental.cjs` via Vite (`npm run build`). Registers the `Relay` side panel (`relay-status`) and `/relay-status` command, supports draft task/check forms, revision-bound approvals, manual verification notes, role validation/probing, expandable Audit summaries, and `Export Markdown` / `Copy Markdown` actions.
216
+ - **Redacted Markdown Export (`src/report.ts`)**: `auditMarkdown()` escapes Markdown/HTML metacharacters, redacts local absolute, home (`~/`), UNC, and `file://` paths as `[path]` while preserving `http(s)://` URLs and closing HTML tags, and shortens repeated task titles in Evidence and Reviews.
217
+
218
+ ### 7. Agent Tools Registered by the Server Plugin
219
+
220
+ | Tool Name | Required Inputs | Optional Inputs | Behavior |
221
+ | :--- | :--- | :--- | :--- |
222
+ | `relay_explore` | `question` | *(none)* | Runs a read-only exploration child session with `roles.explorer` (when enabled) and returns its findings without altering the draft |
223
+ | `relay_plan_add` | *(at least one of `tasks` or `checks`)* | `tasks` (strings or `{ title, allowedPaths }`), `checks` (`name`, `command`, `adapter`, `policy`, `scope`, `reason`, `screenshotDir`) | Adds validated tasks (max 200) and verification checks (max 20) to the active session's `draft` record |
224
+ | `relay_plan_submit` | *(none)* | *(none)* | Submits the active `draft` plan for revision-bound `relay.approve` human approval and restores the session's previous model |
225
+ | `relay_plan_cancel` | `reason` (max 500 chars) | *(none)* | Cancels the active `draft` plan when exploration shows no work is needed or the user declines to proceed |
226
+ | `relay_status` | *(none)* | *(none)* | Returns effective Relay config summary, configured role models, record phase/tasks/checks/evidence, and approval state |
227
+ | `relay_config_set` | *(none)* | `roles`, `limits`, `widths`, `autoStart`, `explorer`, `brainstormFirst` | Validates settings against enabled OpenCode models (`validateSettings`) and requests `relay.configure` permission before saving to `relay/config` |
228
+ | `relay_report` | Builder: `outcome`, `summary`, `checks`; Reviewer: `verdict`, `summary`, `findings` | Reviewer: `inspected` (exact attached screenshot filenames) | Worker-only reporting tool called once by active builder or reviewer child sessions; never approves plans or signs off records |
229
+
230
+ ### 8. Token Usage Breakdown
231
+
232
+ Inspection, approval, verification, and audit actions run outside the LLM; model tokens are spent only during interactive planning and worker execution:
233
+
234
+ | Operation | Token Cost | Why |
235
+ | :--- | :--- | :--- |
236
+ | Idle installation (before `/relay` or `/relay-configure`) | **Schema tokens only (0 turns)** | Registers the 7 `relay_*` tool schemas; never prompts models, runs checks, or creates records automatically |
237
+ | `/relay-status`, `/relay-audit`, `/relay-export`, `/relay-validate-config`, TUI/GUI panel actions | **0 tokens** | Runs over `RelayRpc` against plugin storage and local files without invoking a model |
238
+ | Automated verification checks (`command` and `playwright` adapters) | **0 tokens** | Spawned directly by `src/verify.ts` in Node.js; only concise evidence summaries and fresh PNGs pass to the reviewer |
239
+ | `/relay-probe-image` (when `enableProbe: true`) | **Minimal 1-turn vision probe (cached)** | Sends a 1-pixel image check to `roles.reviewer` and caches the result under `relay/image-probes/` |
240
+ | `/relay` brainstorming/planning, `relay_explore`, `builder`, and `reviewer` runs | **Model turn tokens (tracked per run)** | Runs configured role models; Relay records per-run input/output/reasoning/cache tokens plus planner session token deltas in the panel and Audit export |
241
+
242
+ ## Directory & Storage Structure
243
+
244
+ Relay keeps orchestration state in OpenCode's plugin storage and writes only exported audit reports and Playwright screenshots to the project directory:
245
+
246
+ ```text
247
+ <opencode plugin storage>/
248
+ ├── relay/config # Saved roles, limits, widths, autoStart, explorer, brainstormFirst
249
+ ├── relay/records/<projectID>/<recordID> # Schema v3 record (phase, revision, planRevision, tasks, checks, approvals)
250
+ ├── relay/runs/<projectID>/<recordID>/<runID> # Builder/reviewer run records, reports, durations, token counts
251
+ ├── relay/evidence/<projectID>/<recordID>/<id> # Adapter/manual check results, truncated output, screenshot SHA-256 hashes
252
+ ├── relay/lockdown/<sessionID> # Tracks plugin-owned *opencode* shell deny rules while active
253
+ └── relay/image-probes/<encodedModel> # Cached optional reviewer vision probe results
254
+
255
+ <project-root>/
256
+ ├── .screenshots/ # Default Playwright screenshotDir collected by verify.ts
257
+ └── .relay/
258
+ └── reports/
259
+ └── relay-<id8>.md # Redacted Markdown audit report written by /relay-export
260
+ ```
261
+
262
+ ## Configuration Options
263
+
264
+ Configure defaults under `"options"` in `~/.config/opencode/opencode.jsonc`, or manage them interactively via `/relay-configure` (which writes overrides to plugin storage under `relay/config`):
265
+
266
+ ```jsonc
267
+ {
268
+ "roles": {
269
+ "planner": { "providerID": "anthropic", "id": "claude-sonnet-4-5" },
270
+ "builder": { "providerID": "openai", "id": "gpt-5-codex" },
271
+ "reviewer": { "providerID": "anthropic", "id": "claude-sonnet-4-5" },
272
+ "explorer": { "providerID": "google", "id": "gemini-2.5-flash" }
273
+ },
274
+ "limits": {
275
+ "maxRunningTasks": 1,
276
+ "maxFixCycles": 2
277
+ },
278
+ "widths": [1280, 390],
279
+ "autoStart": true,
280
+ "explorer": true,
281
+ "brainstormFirst": true,
282
+ "enableProbe": false
283
+ }
284
+ ```
285
+
286
+ | Option | Env Variable | Default | Description |
287
+ | :--- | :--- | :--- | :--- |
288
+ | `roles.<role>` | *(none)* | *(unset)* | `{ providerID, id, variant? }` assignment. No default models are shipped: `builder` and `reviewer` (must support `image` input) are required before `/relay` starts; `planner` is optional (uses the current session model if unset) and `explorer` is optional (omits `relay_explore` if unset) |
289
+ | `limits.maxRunningTasks` | *(none)* | `1` | Maximum concurrent tasks (`1` to `4` via `/relay-configure`) |
290
+ | `limits.maxFixCycles` | *(none)* | `2` | Maximum builder fix retries per task after reviewer `changes` verdicts (`0` to `5` via `/relay-configure`) |
291
+ | `widths` | *(none)* | `[1280, 390]` | `1` to `4` integer viewport widths (`320` to `3840`) required for Playwright UI checks and reviewer visual checks |
292
+ | `autoStart` | *(none)* | `true` | Automatically start task execution immediately after `relay.approve` plan approval (`false` requires `/relay-start` or GUI Start) |
293
+ | `explorer` | *(none)* | `true` | Enable the read-only `relay_explore` child session tool (`false` disables `relay_explore` and omits `models.explorer`) |
294
+ | `brainstormFirst` | *(none)* | `true` | Require Phase 1 brainstorming (2-3 approaches, tradeoffs, risks, non-goals, and `question` alignment) before drafting tasks in `/relay` (`false` clarifies only when ambiguous) |
295
+ | `enableProbe` | *(none)* | `false` | Enable the explicit `/relay-probe-image` command and Desktop **Probe image** button for testing reviewer vision input |
296
+
297
+ ## Development Checks
298
+
299
+ Requires Node.js `^22.15.0 || >=23.5.0` and `@opencode/plugin` `2.3.2`. Run the verification suite from the repository root:
300
+
301
+ ```sh
302
+ npm test
303
+ npm run typecheck
304
+ npm run build
305
+ npm run test:gui
306
+ ```
307
+
308
+ - `npm test` runs unit and integration tests (`test/*.test.ts`) using Node's native test runner with `--experimental-strip-types`.
309
+ - `npm run typecheck` runs `tsc --noEmit`.
310
+ - `npm run build` bundles `src/gui.tsx` and `src/gui.css` into `dist/gui-experimental.cjs`.
311
+ - `npm run test:gui` runs Playwright smoke and layout checks across mocked OpenCode Desktop widths via `test/gui-smoke.mjs`.
312
+
313
+ ## License
314
+
315
+ MIT
Binary file
Binary file