English | 中文
An observation console for a fleet of OpenCode servers, plus a native dsh subagent backend.
The plugin connects to one or more remote opencode serve instances and answers three questions
OpenCode's own clients cannot: which sessions are running across all servers, which are waiting
for you, and what failed — then delegates work into them and registers each server as a native
dsh subagent provider (opencode-<serverId>).
Positioning (0.6.0): session access is a means, not the goal. Chatting inside a session belongs to OpenCode's TUI/Web (we deep-link into it); this plugin owns the cross-server board, the attention feed, and the agent-facing backend.
Two tracks, one core (2026-11-27):
[observe]— the human-facing console (board, attention, cost governance) — is the current priority and is being finished first;[delegate]— the agent-facing tools and native subagent provider — follows in later releases. Both share one transport and version-probing core. SeeTODO.md§1/§2/§7 for the per-track roadmap, the HTTP decisions and the archive log.2.3.0 write surface: the only new remote write is reversible archiving —
PATCH /session/{id} {archived:true|false}for sessions this plugin created by delegation (no deletion, no message/history change). Archiving is a visibility toggle for the default views; the automatic sweep that uses it is opt-in and off by default.
Compatibility: OpenCode 2.x only (/api/* + HTTP Basic auth). The v1 API (OpenCode
1.18.x) was frozen in 0.7.2 and removed in 1.0.0 — a v1 server now fails with a clear
"requires OpenCode 2.x" error. apiVersion: auto|2 is accepted;
auto probes /api/info through @opencode/client (client.server.info()) and records why a probe failed.
The upstream base a release targets is declared in package.json (opencode.client / opencode.server)
rather than in the version number; the release gate keeps opencode.client equal to the pinned
@opencode/client. See Compatibility & versioning.
Primary role: register each OpenCode server as a native dsh subagent provider (
opencode-<serverId>,lib/provider.js) and expose remote sessions/workspaces as tools (opencode_prompt, shell/git/read/find, catalogs). The per-server one-shot tool row is named by the profile'stoolName(the examples below useopencode_subagent_<server>), not by the provider itself. The embedded OpenCode Web UI is an optional convenience for full-fidelity work, not a replacement for the OpenCode client.
Board — one page across every server: attention, 7/30-day insights, a 30-day activity calendar, and the idle fleet below.
Insights — cards, daily steps and the activity heatmap share one top row.
- Screenshots · Quick start · Architecture · Features
- Install (profile) · Configuration · Subagent seam
- Documentation · Ecosystem · Compatibility & versioning · Notes
# 1. install the plugin into the web profile (bundle selection is composed at restart)
# a local checkout works too: dsh plugin --profile web add /path/to/dsh-opencode-client
dsh plugin --profile web add dsh-opencode-client
# 2. configure at least one server (full schema in Configuration)
# OpenCode 2.x also needs the server password:
# config.servers: [{ id: server-a, url: "http://server-a:4096", password: "<OPENCODE_SERVER_PASSWORD>" }]
# 3. restart dsh web
dsh webVerify:
- Settings → Plugins → OpenCode Client shows the server / workspace / session section
(
GET /api/opencode-client/boardanswers with the configured servers). - Ask the agent to call
opencode_sessions— it lists remote sessions, so the HTTP path toopencode serveworks end to end. - Optional: expose the server as a native subagent (
opencode_subagent_<server>) — see Subagent seam.
Full live acceptance run (needs a real OpenCode 2 opencode serve):
OPC_LIVE_URL=http://server-a:4096 \
OPC_LIVE_PASSWORD='<OPENCODE_SERVER_PASSWORD>' \
OPC_LIVE_DIR=/home/user/workspace \
node scripts/e2e-live.mjs # or: npm run e2e; OPC_LIVE_INTERACTIONS=1 also exercises approval/question bridgingOPC_LIVE_PASSWORD is required (OpenCode 2 always uses HTTP Basic auth). Offline checks:
npm test (unit + transport tests) or npm run check (smoke checks + tests).
Prerequisite: opencode serve must be reachable from the dsh host. It binds 127.0.0.1 by
default — bind 0.0.0.0 or put it behind an SSH tunnel. OpenCode 2 always requires
OPENCODE_SERVER_PASSWORD on the serve process plus the same value in the plugin's server
password.
OpenCode's own architecture: opencode serve exposes an OpenAPI HTTP server "that an opencode
client can use"; the TUI / Web / SDK are clients of it. This plugin is another client, hosted in
dsh.
flowchart LR
BROWSER["browser<br/>dsh Web UI"] -->|"same-origin HTTP"| DSH["dsh web<br/>host process"]
subgraph PLUGIN["dsh-opencode-client plugin"]
direction TB
CLIENT["client bundle<br/>board page · settings section"]
ROUTES["routes<br/>/api/opencode-client/*"]
TOOLS["tools<br/>30 × opencode_*"]
PROVIDER["provider<br/>opencode-<serverId>"]
SSE["sse<br/>v2 /api/event"]
end
DSH --> CLIENT
DSH --> ROUTES
DSH --> TOOLS
DSH --> PROVIDER
ROUTES -->|"v2 HTTP API"| SERVER_A["opencode serve · server-a"]
TOOLS -->|"v2 HTTP API"| SERVER_A
PROVIDER -->|"v2 HTTP API"| SERVER_A
ROUTES -->|"v2 HTTP API"| SERVER_B["opencode serve · server-b"]
TOOLS -->|"v2 HTTP API"| SERVER_B
PROVIDER -->|"v2 HTTP API"| SERVER_B
SERVER_A -.->|"SSE"| SSE
SERVER_B -.->|"SSE"| SSE
CLIENT -.->|"iframe: native OpenCode UI"| SERVER_A
The browser only talks to the dsh origin — lib/client.js renders the board/plugin page and
embeds the native OpenCode UI in an iframe when a session is opened. lib/routes.js
(/api/opencode-client/*) and the model-facing opencode_* tools (lib/tools.js) make
deterministic calls through @opencode/client (pinned 2.4.2, one client per server);
lib/provider.js (opencode-<serverId>) and lib/session-run.js drive delegated runs;
lib/sse.js subscribes to each server's /api/event stream with Basic auth and reconnect for
live progress, completion and permission/question bridging. lib/http.js probes
/api/info once per server through a minimal @opencode/client instance (client.server.info()),
adds HTTP Basic auth and rejects v1 with an actionable error;
lib/oc-client.js owns the client instance and error mapping.
More: ARCHITECTURE.md · docs/ARCHITECTURE.zh.md.
30 model-facing opencode_* tools, host routes, one native subagent provider per server — the
same tool names. OpenCode 2 is the only supported generation: v1 was frozen in 0.7.2 and
removed in 1.0.0; a v1 server is rejected at the transport with an actionable error (policy).
OpenCode 2 removed a few v1 endpoints. Two capabilities (share links, tool-id listing) have no v2 replacement and were removed as tools in 1.5.0 (the host routes keep an explicit error); two are restored with v2-native calls, and two are v2-only:
| Capability | OpenCode 2 behaviour |
|---|---|
opencode_find with kind=text |
restored via fallback: no content-search endpoint, so the plugin runs a workspace grep through the async shell (literal substring, first 100 matches) |
todo list in opencode_session_info |
restored via fallback: /session/{id}/todo was removed, so todos are derived from the last todowrite tool call |
opencode_usage |
OpenCode 2 only: GET /experimental/session/stats aggregates sessions/steps/tokens/cost/tool success rate, plus per-model attribution and (host route ?group=directory) per-directory cost |
| background jobs (board/progress) | OpenCode 2 only, experimental: GET /experimental/job lists work that outlives the turn (e.g. a shell script still running after the session went idle); shown as the background status |
On OpenCode 2 the plugin also normalizes these API differences for you:
- Sessions carry
location.directory; session/message/diff results are normalized to one shape. - Prompts are
{text, files};agentandmodelare session state (POST /api/session/{id}/agent|model). - Completion is detected from
session.execution.succeeded|failed|interruptedevents. - Permission approvals use
once|always|reject; questions arrive as forms with typed fields (string / number / integer / boolean / multiselect). opencode_shellruns asynchronously in the session workspace (submit, poll, read output); output pages are followed via cursor (up to 1 MiB) and truncation is reported explicitly with exit/signal.opencode_summarizemaps tocompact(the session's own model is used, somodelis optional);opencode_initruns the built-ininitcommand;opencode_git_diffmapsgit→working;opencode_findretries a glob query as a plain substring (the endpoint does not understand*/?).
- Native subagent — provider
opencode-<serverId>; pair with@deepseek-ai/dsh-tool-subagentto expose one-shotopencode_subagent_<server>tools. - Async delegation (recommended) — tool
opencode_delegatestarts the remote agent as a native dsh subagent and returns immediately: the child runs in the background, dsh delivers the completion notice (waking an idle session), and several calls in one message run concurrently. Pick the machine per call withserver=— one tool, any number of remotes, no auto-routing and no per-server tool rows. It takesschema=(validated resultStructured result:in the completion notice) and the remoteagent=/model=/title=selection; attachments are not supported yet. It is one-shot;opencode_prompt(session=...)continues the remote session later. Attachments are not supported on the async path: put the files in the remote workspace and let the remote read them. The blocking tool andPOST /delegatewere removed in 2.0. A completed delegation is marked read on the remote as soon as dsh consumes its result (the board's "finished, not looked at" section is reserved for failed/aborted runs); a server'sautoSeenDelegations: falsekeeps completed delegations unread. The tool result and the completion notice carry an OpenCode web-UI deep link (/server/<base64url>/session/<id>) — the dsh subagent list rendersmode: externalrows as unclickable (no local dsh session), so the link and the plugin board are the ways to open the remote session;sessionLink: falseremoves the provenance line from notices. - Turn-by-turn continuation —
opencode_promptsends one message to an existing remote session (fire-and-forget by default,wait=trueto block); read the reply withopencode_messages/opencode_progressand send the next message. This keeps a remote worker session alive across dsh turns. A fire-and-forgetdelivery=steer|queueresult carries the newinboxId(OpenCode 2.4 answers with theSessionInboxUserit appended), so the message can be steered/queued/cancelled withopencode_inboxwithout listing the inbox first;wait=trueis unchanged and returns no inbox id. - Completion wait —
prompt_async+ SSE event-driven (returns immediately when the remote finishes), 5 s polling fallback, then a blocking wait. Completion is detected fromsession.execution.succeeded|failed|interrupted. A completed waited turn is likewise marked read on the remote once dsh consumes it (autoSeenDelegations: falseopts out per server). - Live progress —
opencode_progress(current tool/step, elapsed, output tail) fed by SSE tool events; delegation completes on the SSE completion event. - Abort —
opencode_abortstops a running remote session (session.interrupt); a waiting delegation returns an abort error instead of hanging. Call it from another dsh session/agent: tool calls inside one turn are serialized, so it cannot preempt a blockingopencode_prompt(wait=true)in the same turn. - Attachments — async delegation does not support attachments; put the files in the remote workspace (or a path the remote can read) and reference them from the task.
- Server configuration —
servers: [{ id, label?, url, password?, directory? }], with optional per-server defaultagentandmodel.urlacceptshttp://andhttps://; the scheme picks the transport (httpsis real TLS, default port 443, never a plaintext fallback). - Discovery —
GET /api/opencode-client/list(per-server health / version, running count, active tool, and sessions grouped by directory; the directory comes fromlocation.directory)./listis part of the 1.x compatibility promise, so it is kept until 3.0.0. - Board — tool
opencode_board(needs-you / running / background / idle partitions plus thehealth:line: probe state, current SSE state and last error); the Web board reads the same data fromGET /api/opencode-client/board. The per-server listing is aggregated across cursor pages up toSESSION_MAX_SESSIONS1500 rows (a full 500-row page reaches it in three requests; the walk makes at most 12 requests); a server above that cap is reported astruncatedon its card and inopencode_boardinstead of silently losing sessions. A short page is not trusted blindly: a short page with a non-emptycursor.nextis followed once, because a 2.4.x build/proxy can clamplimit=500to a smaller page size — an empty probe proves the cursor was phantom and the listing complete (cached per server for 10 minutes, after which polls cost one request again), while a probe page with rows means the smaller page size is real and the walk continues to the 1500-row cap. A short page with no cursor, or a short page on a server already known to hand out phantom cursors, still costs exactly one listing request. The default-visible listing passesarchived: false(on OpenCode 2.4.2 an omitted flag also returns archived sessions), but the filter is caller-scoped:/usage, insights and skills keep the include-archived listing so their totals still reconcile with the server-side stats. A 2.0–2.3 server or a strict proxy that rejects the flag gets one retry without it, a cached per-server capability, and a labelled fallback (archivedFilter: 'unsupported'), so the board never degrades offline over a filter. The same capability bit coversarchived=true(archive count / state partitions): once the server is known unsupported the plugin stops asking, reports the archived count as unsupported and shows the archive state asunknownrather than trusting the unfiltered fallback. A completed delegation clears OpenCode's own read marker when dsh consumes it, so it does not linger in "finished, not looked at"; failed and aborted runs stay there until you open them. - Session listing — tool
opencode_sessions; rows include the model (with#variant), agent, outcome and cost when the server reports them.archived=truelists archived sessions. Listing is natural paging: each call serves one server page oflimitrows (default 50, cap 200) andcursor/nextCursorcontinues right after the last row shown (row 51 of alimit=50call), so consecutive pages have no gap and no duplicates. A cursor addresses one server: with several servers passserver=first (a single-server profile needs noserver=). The board keeps its own bounded aggregation (~1500 sessions per server) and reports that cap separately on the board card/page. - Session messages — tool
opencode_messages(text, tool and file parts;content[]text/reasoning/tool parts are normalized). Tool lines include the call input summary and the first output line;type=filters one message kind (server-side). Useful to decide whether a session is the right one to continue. - Session info — tool
opencode_session_info(title/summary/todos/diff; the todo list is derived from the lasttodowritecall, and outcome/cost/tokens plus the changed-file diff are reported). - Session context — tool
opencode_session_context(read-only, requires OpenCode ≥ 2.4; an older server gets a version hint instead of a bare 404): the model context the remote session is actually carrying — total messages, counts by message type, earliest/latest time, cost, the newest few ids and two token views: per-step sums measure consumption, not the current window (cached context repeats, so they over-count), whilewindowapproximates the current window from the last assistant step'sinput + cache.read. Message text and tool output are deliberately not returned (the endpoint answers with the whole window); use it to judge how full a session is before continuing it. - Session management —
opencode_fork,opencode_children,opencode_summarize(mutating; v2 maps it tocompact, where the session's own model is used andmodelis optional),opencode_init(writes AGENTS.md, requiresconfirm=true; runs the built-ininitcommand). - Session archive (reversible) — tool
opencode_session_archive:action=listshows at most 50 sessions this plugin created by delegation (server/session/title/createdAt/stopReason/archive state; never message bodies; both archive partitions are paged up to ~1500 rows and saytruncatedwhen capped), andaction=archive|unarchivehides/restores one throughPATCH /session/{id}{archived:true|false}(OpenCode ≥ 2.4; the installed client forwards the field). A delegation whose run is still in progress (stopReasonempty) is refused with the reason and no request is sent;force=trueis the explicit override. A settled delegation is also refused when the remote is still busy — a fresh board observation row or asession.getread withtime.busy > time.idle(the user continued it) — and only falls back to the ledger check when no live state can be read. A successful archive/unarchive drops both cached listings, so the board swaps the row immediately instead of after its 10 s snapshot. On a pre-2.4 server or a strict proxy that rejects thearchivedlist filter,action=listreportsarchived=unknown(neveractive) and says why: the stripped fallback cannot tell the partitions apart. A delegation whose owning process died before it settled is loaded asaborted (stale)after 24 h, so it converges instead of readingrunningforever and can be archived withoutforce=truewhen its live state is readable/idle (if that liveness read fails,force=trueis required so a possibly-active session is not hidden; the sweep ignores stale rows entirely: it only touches completed rows). Archived rows are retained in the durable registry past the 2000 live-row cap (up to 5000 tombstones), so a restored session stays recognised for a long time instead of being evicted after ~18 days. Eligibility comes from a small durable registry persisted through the host'sstorageDomain(minimal server/session/timestamps/reason fields, no prompts or credentials; one writer per domain — one profile, one dsh process); a session created by hand is refused with the reason and no request is sent, and deleting a session is not supported. Confirmation follows the automatic sweep:session.get404 after the PATCH only recordsarchiveHandledAt(neverarchivedAt), and an unconfirmed read records no permanent marker (a retry for the sweep, plus a host log line). A profile withoutstorage-domainkeeps the registry in memory and the list says so — sessions delegated before the restart stay unknown instead of being guessed. It only covers delegations this plugin created after this version: the durable registry does not exist in ≤ 2.2.1, so pre-upgrade sessions are never auto-archived (nothing is guessed).action=unarchiveclearsarchivedAtbut keepsarchiveHandledAt, so the sweep never re-archives a session you restored; the one migration exception (a session manually unarchived before upgrading has noarchiveHandledAtand may be archived once by the first sweep) is documented in COMPATIBILITY.md (scope D upgrade notes).opencode_searchandopencode_childrenstill return archived sessions: archiving only affects the default views. - Session search & diagnostics —
opencode_search(session search through the list endpoint'ssearchfilter),opencode_mcp(MCP server status). - Delegation ledger — every delegated run (native
opencode-<id>provider and the native provider) leaves one in-process row: server, task, directory, duration, outcome, failure identity (errorName/errorCode), that session's tokens/cost and the parent session. Read it withopencode_delegationsorGET /api/opencode-client/delegations(DELETEclears it); the settings page shows the latest five. A run whose session could not even be created still gets a row, which is usually the failure you want to see first. - Multiple servers — configured as an array and aggregated by the client (opencode itself has no server-side federation).
- Agent catalog — tool
opencode_agents(primary/subagent, native/custom); call it beforeopencode_delegateto pick an agent name. - Catalogs —
opencode_models(providers/models, credentials stripped),opencode_commands,opencode_skills,opencode_references. - Command execution —
opencode_commandruns a remote command (e.g.init) inside a session and returns its final text.
- Workspace ops —
opencode_shell,opencode_git_status,opencode_git_diff,opencode_read_file,opencode_find(kind=filesearches paths,kind=dirdirectories;kind=textruns a workspace grep fallback). - These are deterministic direct calls (no remote model involved): verify what a remote agent changed, read a file, run a command, or search the workspace.
opencode_shellis asynchronous (submit, poll, read output) in the session workspace;opencode_git_diffacceptscommitted/branch/working(withgitmapped toworking), plusuntracked=files|foldersandbase=<ref>.
- Permission approval —
permission: ask(default) turns remote permission requests into dsh approval cards (once/always/rejectare your call);allowis the explicit auto-approve bypass andrejectrefuses everything (unattended deployments). Withaskthe outcome depends on the caller: a delegated run (agent in scope) shows the host approval card; a session dsh did not start keeps the request pending in the board's "needs you" row until you answer in the session; when no approval service is available the request is auto-answeredalwayswith a warn in the plugin log. Every request is counted as a permission diagnostic — the/boardserver object carriespermissions(asked / user-approved / auto-approved / rejected / pending plus the last 20 action+resources) and the board card shows "权限 N · 自动 M" (warning tone when anything was auto-approved), so "the remote never asked" and "it asked and was answered silently" are no longer indistinguishable. - Question bridging — remote questions are forwarded to dsh's user-question UI for
tool-initiated runs that have a dsh agent. A run with no agent in scope (the HTTP
/delegatepath) or a session dsh did not start (for example one you opened in the OpenCode TUI/Web) keeps its question pending by default: it shows up in the board's "needs you" row, triggers the attention notification, and waits for you to answer in the session;question: rejectopts an unattended deployment into dismissing it. Questions are forms with typed fields (string / number / integer / boolean / multiselect). When several clients share the same OpenCode server, the first client that sees a form answers it: keepquestionidentical everywhere — a client still onquestion: reject(or an older build) dismisses the form before the "needs you" card can appear. - Live events — per-server SSE subscription (
/api/event) with reconnect; fast permission/question handling and live state (the board reads it throughGET /api/opencode-client/board; the/eventsand/statusmirror routes were trimmed in 2.1.0). - Polling fallback — permission/question requests are answered while a delegated run is active: SSE events are handled immediately, with a 15 s polling fallback when the stream is unavailable.
- Observation console (main panel, 0.6.0) — the left-rail
OpenCodeentry opens a card board, not an embedded page: "needs you / running / error" sit on top across every remote, idle sessions are grouped per remote and directory, a remote filter chip keeps its selection, and a card opens that session in an overlay (Esc or the top bar closes; the overlay keeps a "new tab" escape). Backed byGET /api/opencode-client/board, polled every 5 s and paused while the page is hidden. Delegated sessions carry a委派chip (kind / model / status / duration / parent on hover), and a "委派台账" panel lists this process's delegation history (latest 5, expandable; process-local — a dsh restart clears it). The chip joins the board snapshot withGET /api/opencode-client/delegations; the panel is an independent recent-50 list filtered by the remote chip. - Plugin page — "OpenCode Client" section: servers/workspaces/sessions, session ids, active tool, messages, create session.
- Embedded OpenCode UI — a server row's "打开" button opens the real OpenCode Web UI in a fullscreen overlay; a board card opens that session in an in-panel view with a "← 返回" action and an "↗ 新标签" escape (embedded frame without its own chrome: the top bar is the panel's). No reimplementation — the embedded page keeps streaming, tool cards, diffs and permissions.
- Usage & attribution (0.7.1 / 0.8.0) — per-server cards show today's tokens/cost, the board has a
"finished, not looked at" zone, and the settings page shows a 7-day per-model / per-directory split
(
reconciledmarks a mismatch with the stats total). - Background work (0.8.0) — a session whose turn ended but whose shell job is still running shows
as "background" with the command and elapsed time, instead of looking idle. When the SSE stream
connects mid-run, the current tool is read once from
session/active+ the latest message so a running card is not blank until the next event. - Insights (0.9.0) — the top of the board page shows a 7/30-day window: session counts, tokens,
cost, cache hit rate, a daily steps chart, plus a separate 30-day activity heatmap
(GitHub-style week columns with month labels; switch between sessions / tokens).
It sits in the top row next to the six cards and the steps chart, like the context-insight
plugin. The heatmap uses one bounded per-day stats call per server, cached for 10 minutes. Top
models/projects, MCP/custom tool usage grouped by server (builtin shell/read/write are not
shown) and per-skill load counts stay on the 7/30-day window. The heatmap itself is fixed at
30 days; the footnote states what OpenCode cannot provide (daily cost, token composition,
duration breakdown). Skill names come from a lazy message scan (
/insights/skills); the activity heatmap is served by/insights/activity(30 days, sessions/tokens). - Plugin identity (name / version / repository) — static About block — the settings section ends
with an About block that only shows the plugin name, the installed version the Host reports for this
bundle, and the repository link. It runs no release check of its own: the old About update check
(latest / update-available / 重新检查) was removed in 2.3.0 because it could disagree with the
Host's plugin manager, which already lists versions and runs updates. Version updates therefore live
in the plugin manager's version area; the
/aboutand/upgradeHTTP routes stay for compatibility with external scripts, but the bundled UI no longer calls them. Both are deprecated and planned for removal in 3.0.0. - Fleet health (0.8.0, reworked in 1.2.1) — the board and settings page show API-version drift and probe failure reasons, plus the event stream's current state (reconnecting / stopped, with the last error). Lifetime reconnect counts are diagnostics only: a stream that recovered once is healthy and shows no warning.
- Entry points — the left sidebar
OpenCodeentry opens the board; server rows and board cards open the embedded UI. There is no session-header button or right-sidebar tab anymore.
Installing on another machine (Windows / DSH Desktop, multiple servers, troubleshooting): see docs/INSTALL.zh.md (Chinese).
# A. dsh plugin manager — published release (recommended: no checkout, no git clone)
dsh plugin --profile web add dsh-opencode-client
# B. dsh plugin manager — a local checkout or an explicit git spec (development)
dsh plugin --profile web add /path/to/dsh-opencode-client
# C. helper script: symlink + dependency + bundle selection + a starter server row
bash scripts/install-into-profile.sh http://server-a:4096 server-aor add it manually to the profile and select it as a bundle:
{
"dependencies": { "dsh-opencode-client": "^1.2.0" },
"dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app", "dsh-opencode-client"] } }
}A local checkout uses "file:/path/to/dsh-opencode-client" as the dependency value instead.
Restart dsh web afterwards: the bundle selection is composed at startup.
- id: opencode-client
name: dsh-opencode-client
config:
servers:
# OpenCode 2.x: start the server with OPENCODE_SERVER_PASSWORD=<secret> and repeat
# the same value in `password` (HTTP Basic auth, user "opencode").
- id: server-a
label: server-a opencode 2.x
url: http://server-a:4096
apiVersion: auto # auto (probe GET /api/info) | 2 (v1 is rejected)
password: "<OPENCODE_SERVER_PASSWORD>"
# directory: /home/user/workspace # default remote dir when the caller does not give one
# agent: plan # default OpenCode agent for delegation
# model: deepseek/deepseek-chat # default model "provider/model"; v2 also "provider/model#variant"
# allowedModels: ["token-plan/deepseek-v4.1-flash#high"] # optional: models delegation may use here ([] opts out of the fleet list)
# autoSeenDelegations: true # mark a completed run/turn read once dsh consumes it (default on)
permission: ask # ask (default, dsh approval card) | allow | reject
question: ignore # ignore (default: keep pending on the board + notify) | reject (dismiss, unattended)
pathMap: # only when local and remote path layouts differ
- { from: /home/user, to: /home/user }
sessionLink: true # provenance line (server + remote session + web link) in completion notices (default on)
routing: # multi-server subagent dispatch (default: on when servers > 1)
providerName: opencode-auto
policy: [directory, sticky, least-busy, round-robin]
sticky: true # keep one parent agent on the server that accepted its first child
failover: true # try the next candidate when a start fails before publication
delegate: # delegation lifecycle, fleet-wide
autoArchiveAfterHours: 0 # 0 = off (default); 72 = archive completed delegated sessions 3 days after they finished
waitMs: 900000 # how long one awaited turn may take (ms, default 15 min); 0 = no deadline
# allowedModels: # optional allowlist for delegation; commented out = unrestricted
# - "token-plan/deepseek-v4.1-flash#high"
# - "xai/grok-4.7#*"delegate.waitMs (default 900000, i.e. 15 minutes; a YAML number — the quoted string "0" falls
back to the default instead of meaning "no deadline") is the budget for one awaited
turn: opencode_delegate, opencode_prompt(wait=true), opencode_command and opencode_init. 0
means no deadline, for runs that legitimately outlive it (CI, pipelines). Expiry only stops
waiting and returns opencode: timeout: the plugin no longer interrupts the remote turn (dsh
disposes every settled activation; dispose() now calls POST /interrupt only while the run is
still unsettled, i.e. on a real cancel). The turn keeps running remotely — read it with
opencode_progress, continue with opencode_prompt(session=), or use opencode_abort to stop it.
A timed-out settlement also releases the interaction bridge, the ledger row and the read marker, so
the remote turn keeps running unattended (permissions/questions are no longer routed); read or
stop it promptly. Read it with the default opencode_prompt(session=...) (wait=false) plus
opencode_progress; while the turn is still running, do not use wait=true to track it — that
tracks the session's next completion, which may be the still-running turn.
delegate.autoArchiveAfterHours (default 0 = off) enables the automatic sweep: at most once an
hour the plugin reversibly archives delegated sessions whose run completed more than N hours
ago. The value must be a YAML number (an unquoted 72; the string "72" falls back to 0),
values below one minute also fall back to off, and a first pass runs about 2 minutes after activation
before the hourly cadence. It only touches sessions the durable delegation registry proves this
plugin created, skips error/aborted runs and already-archived sessions, caps one pass at 50
attempts, re-reads each session first (a completed session continued after its settle time gets an
independent activityDeferredAt skip marker — it does not consume the per-pass quota and is
re-checked once a day; a vanished one is only retired), pauses a server for an hour when its archive
endpoint seems unsupported rather than hammering it, and never re-archives a session you restored
with opencode_session_archive action=unarchive. It only covers completed delegations this plugin
created after this version (the durable registry does not exist in ≤ 2.2.1), and it stays
experimental: do not enable it in production on a build that predates the deferred-row fix.
Archiving is the same reversible
PATCH /session/{id} {archived:true} (no deletion, no message/history changes) and is paused while
the profile has no storage-domain (an in-memory registry cannot identify sessions delegated before
a restart). The last pass is visible on GET /api/opencode-client/board under autoArchive
(always present, enabled:false when off; lastSweepAt, lastArchived, lastError, …) and in the
host log.
delegate.allowedModels (fleet-wide, optional) and servers[].allowedModels (per-server override)
restrict which model refs the plugin may write to a remote session. An entry is an exact ref:
provider/model allows only the default reasoning variant, provider/model#variant allows that one
(e.g. #high), provider/model#* allows every variant, and #default equals "no variant". Matching
is exact and case-sensitive. A server-level list replaces the fleet list, and an explicit
allowedModels: [] is the documented opt-out that keeps that one server unrestricted.
With a list in force, opencode_delegate must name model= (or the server must carry an allowlisted
servers[].model default), a model= switch in opencode_prompt is checked, a continuation without
model= reads the session once and refuses a session someone re-pinned outside the list, and
opencode_fork refuses to copy a session pinned outside it. Every refusal happens before any
remote write, so a rejected model never creates a session or switches an agent; the message names the
ref (marking it as the servers[].model default or the session pin when the caller did not pass it),
the list, and — when only the reasoning variant differs — the exact allowed spelling
(did you mean …#high?).
#* is a list marker, not a value: passing model="…/…,#*" is refused, because it would be
forwarded as a literal * variant. Write provider/model when you mean the default variant.
When the plugin configures an allowlist, the model tool parameter advertises the allowed refs as an
enum only if every server is restricted and no entry uses #* (an unrestricted machine accepts
any model, and a wildcard cannot be enumerated, so a partial enum would make the schema reject a legal
choice). The enum lists the canonical spelling; provider/model#default is accepted by the policy but
is not advertised, and a value the schema rejects never reaches the tool, so the did you mean line is
the tool-body message, not the host schema error. opencode_models annotates the restriction (models
stay listed, never hidden).
An unparseable entry is dropped and reported on startup; if a declared per-server list has no valid
entry the fleet list still applies, and if nothing valid remains delegation is unrestricted — both are
logged at activation, along with servers[].model outside the list or written as #*. Quote entries in YAML: a space before # starts a comment, so
- token-plan/flash #high means the bare ref flash.
Scope: this is admission control over the plugin's own writes, not an ACL — a human can still switch
models in OpenCode's UI, an OpenCode agent may carry its own model config, opencode_summarize /
opencode_command / opencode_init run on the session's current model (on OpenCode 2 model= is
ignored there, so nothing is written to check), and the continuation check fails open when the
session report is unreadable or carries no model (an absent observation is not evidence of a
violation; nothing is written by that check either). dsh subagent rows bound to opencode-<id> cannot
pass a model, so give that server a servers[].model default or those rows refuse.
The fleet list is editable from the plugin's settings page (a textarea, one ref per line) and through
GET|POST /api/opencode-client/policy; the route writes via the Host config editor, so the plugin
reloads and the startup log re-reports the effective list. A POST body is
{ fleet?: string[], servers?: { [id]: string[] | null } } — fleet: [] clears the fleet list,
servers[id] = [] keeps an explicit per-server opt-out and null removes the override. Unlike the
config loader (which drops unusable entries with a warning), a write with an unparseable ref answers
400, so the UI can never accept a change that silently does nothing. Per-server overrides are
API/config-only for now; the page shows each server's effective mode (继承整机 / 本机自定义 /
本机不受限).
servers[].allowedModels is a server-level field like autoSeenDelegations: servers/update keeps it,
but POST /servers replaces the whole entry, so re-adding a server with the same id drops it.
autoSeenDelegations is a server-level field: editing a server through servers/update keeps it, but
POST /servers replaces the whole entry, so re-adding a server with the same id resets it to the
default true — re-enter autoSeenDelegations: false if you want the opt-out back.
apiVersion: auto (the default) asks /api/info once per server through client.server.info(). A 401 means the password is
missing or wrong; any other probe failure is recorded on server.versionProbe (logged once) and
surfaces as a clear error. A server that answers as v1 is rejected with
opencode.v1_unsupported. Force apiVersion: 2 to skip probing. Sanity-check with
curl -u opencode:$OPENCODE_SERVER_PASSWORD http://host:4096/api/info.
To expose an OpenCode server as a native dsh subagent, add a tool row:
- insert:
- id: tool-opencode-server-a
name: "@deepseek-ai/dsh-tool-subagent"
config:
provider: opencode-server-a # "opencode-" + server id
maxDepth: provider-managed
toolName: opencode_subagent_n100opencode-<server> providers are pinned to one server, so a tool row always dispatches to the
same machine. When more than one server is configured the plugin also registers a routed provider
opencode-auto (configurable through routing), which chooses per start:
directory— a server whosedirectorycovers the child cwd (only meaningful when servers declaredirectory);sticky— the server that accepted this parent agent's first child (one parent → one machine);least-busy— fewest running sessions (/session/active), ties rotate;round-robin— rotate through the remaining candidates.
A start that fails before the run is published (unreachable, 5xx, timeout) falls through to the
next candidate when failover: true; the chosen server is appended to the session title
(dsh subagent: <label> · <task excerpt> @server-a) and logged. Expose it as a tool row:
- insert:
- id: tool-opencode-auto
name: "@deepseek-ai/dsh-tool-subagent"
config:
provider: opencode-auto
maxDepth: provider-managed
toolName: opencode_subagent_autoSet directory per server to enable directory routing (e.g. machines with different mount roots);
without it, routing falls back to sticky / least-busy / round-robin. Continuation is not routed —
a remote session id belongs to one server — so keep using the pinned tools or pass server to
opencode_prompt when resuming.
The native opencode_subagent_<server> tools plug into dsh's ctx.subagents provider seam.
See docs/subagent-seam.md for the contract, our capability
mapping, and the applied optimizations (parent-agent attribution, event-driven wait,
idempotent dispose). Both delegation entry points (native provider and async activation) share one
session-run lifecycle (lib/session-run.js): same session creation, interaction
tracking, async prompt + SSE completion wait and abort handling. Native subagent sessions are
titled dsh subagent: <label> · <task excerpt> so they are identifiable in the plugin page (which now
also shows session ids and the active tool of running servers). The provider reports
stopReason faithfully — only an explicit normal finish (stop / tool-calls) settles as
completed; finish=length becomes max-tokens, content-filter / safety become refusal,
error/unknown/missing stay error (with the remote error identity in the diagnostic; a
successful adapter turn that only reports rawFinish is normalized first). dsh's settlement
notice therefore says "ran out of room" / "declined the task" instead of a generic completion, and
an intercepted/unknown turn is never mistaken for a completed one (so its unread dot stays). With
multiple servers, opencode-auto routes each child (see above).
- ARCHITECTURE.md — module map, data flows, design decisions
- docs/ARCHITECTURE.zh.md — 中文架构(与 ARCHITECTURE.md 对应)
- docs/TOOLS.zh.md — 中文工具总览:30 个
opencode_*工具、参数、只读/可变 - COMPATIBILITY.md — dsh / OpenCode compatibility matrix and versioning policy
- CONTRIBUTING.md — dev setup, tests, commit/PR and release policy
- SECURITY.md — supported versions and private vulnerability reporting
- docs/opencode-v2-migration.zh.md — measured OpenCode 2.3.0 gaps and the phased migration plan, implemented across 0.2.0–0.7.1
- docs/opencode-v2-deeper-integration.zh.md — measured survey of the 100 unused OpenCode 2.3.0 endpoints and the candidate deeper-integration roadmap (inbox/steer, revert checkpoints, worktrees, stats, PTY, reverse MCP)
- docs/subagent-seam.md — dsh subagent provider contract
- docs/chat-ui-proposal.md — in-page remote-session chat proposal
- scripts/e2e-live.mjs — live acceptance run against real OpenCode 2 servers (offline checks stay
npm test/npm run check) - README.zh.md · TODO.md · CHANGELOG.md
| Project | Role |
|---|---|
| dsh-remote-hub | Hub side: one dsh Web UI for every backend — reverse proxy, managed SSH tunnels, top-bar switcher, remote subagent providers. |
| dsh-remote-agent | Remote side: runs in each backend dsh web and publishes its launch token + identity so the hub needs no manual token copy. |
| dsh-opencode-client (this repo) | Sidecar: treats remote opencode serve instances as a dsh subagent backend and client (sessions, delegation, catalogs) — independent of dsh remotes. |
See COMPATIBILITY.md for the test matrix and versioning policy.
| Component | Version | Status |
|---|---|---|
| dsh | >=0.2.1-rc.2 (verified against 0.2.2-rc.5) |
supported |
| OpenCode 2.x (v2 API) | /api/* + HTTP Basic auth (verified against 2.4.2; 2.3.0+ expected) |
supported end to end |
| OpenCode 1.x (v1 API) | any | rejected with opencode.v1_unsupported |
The plugin follows independent semantic versioning and is published to npm
(dsh plugin add dsh-opencode-client); a local checkout or a git spec still works and is the
development channel. Current release: 1.2.0 (annotated tag v1.2.0): npm becomes the primary
install channel end to end — install and update both ride the registry (1.1.3 added publishConfig
and the prepublishOnly gate, 1.1.4 moved publishing to trusted publishing/OIDC with provenance,
1.2.0 points the docs at npm and sanitizes the repository). The plugin is otherwise unchanged from
1.1.2 — the observe page and settings share one card
system, remotes are editable in the UI (label / url / password, never echoing the password), and
permission requests are observable (counts, answer source, recent actions, "权限 N · 自动 M" chip);
it also fixes the settings section going blank and the promptFailureMessage ReferenceError.
Previous line, 1.1.1: the observe page fills
in progressively instead of mounting after /insights, every poll runs on one client scheduler
(board, insights, activity, skills, usage), async blocks reserve their final height on the first
frame, and the host serves those reads through SWR + a startup warm-up (cold /insights ~9s → warm
~0.6s). It also ships the 1.1.0 version/update chip plus the question/board fixes. The 1.0.0 line removed the v1 API and moved the transport to
@opencode/client pinned to 2.4.2 (one client per
server; upgrades are deliberate, independent releases); it also included the untagged 0.8.0
(observation trust) and 0.9.0 (insights/activity) changes. The pin policy, SemVer scope and
version matrix live in COMPATIBILITY.md; historical v1→v2 migration notes
are kept in docs/opencode-v2-migration.zh.md.
- Bugs go to GitHub Issues; the bug template asks for the plugin version, the dsh version,
the OpenCode
/api/infoversion, the affected surface and logs: https://github.com/yhuan416/dsh-opencode-client/issues/new/choose - Suggestions and usage questions go to GitHub Discussions (Ideas / Q&A / Show and tell; the pinned "introduce your setup" thread is a good place to start): https://github.com/yhuan416/dsh-opencode-client/discussions
- Security issues: do not open a public issue; report privately as described in SECURITY.md.
- The settings page's About block links the same places and offers Copy diagnostics (plugin version, each server's OpenCode/API version, probe and event-stream state; no URLs or passwords) so a report is one paste. The plugin detail page is this README.
- dsh's built-in
/feedbackrecords session feedback as a local session event; it does not reach the plugin author. There is no email channel — use SECURITY.md when a report must stay private.
- The remote OpenCode server must be reachable from the dsh host;
opencode servebinds127.0.0.1by default — bind0.0.0.0or put it behind an SSH tunnel. OpenCode 2 requiresOPENCODE_SERVER_PASSWORDon the serve process and the same value in the pluginpassword; a mismatch fails the probe with a 401 hint. - Session continuation is done through the OpenCode HTTP API; native external subagents still execute once (matching Codex/Claude Code backends).
- Interactive questions asked by the remote agent are forwarded to dsh's user-question UI when the
run was started by a delegated run (an agent is in scope); without a dsh run they stay
pending on the board's "needs you" row until you answer in the session (
question: rejectdismisses them instead, for unattended deployments). The same bridge answers typed forms. - Permission cards need a tool-initiated run: approval bridging uses the calling agent; a
delegation started over the HTTP endpoint (no agent in scope) falls back to
allow/reject(once/always/reject). - Multiple servers are configured as an array and aggregated by the client (opencode itself has no server-side federation); each server must expose the OpenCode 2 API.
- A shared OpenCode server is shared state: every dsh/OpenCode client connected to it can claim
and answer a pending form or permission. If a question card flashes and disappears, another
client on that server is dismissing it (typically a
question: rejectdeployment or an older plugin/web build) — not the local plugin. - Permission/question requests are answered while a delegated run is active: SSE events are handled immediately, with a 15s polling fallback when the stream is unavailable.
- The plugin page shows
live(SSE connected) and the number of currently running sessions. - OpenCode 2 transport: requests go through
@opencode/client(2.4.2), which owns paths, Basic auth and response envelopes;lib/oc-client.jscaches one client per server. The share / tool-id tools were removed in 1.5.0 (no v2 endpoint; their host routes keep an explicit error); content search and session todos are restored with v2-native fallbacks (see Features and COMPATIBILITY.md).


