You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 1d5f5a4
Browse filesBrowse the repository at this point in the historyBrowse files
authored
feat(adapters): #449 OpenCode headless adapter (Phase C — implementation) (#485)
* feat(adapters): #449 OpenCode headless adapter (Phase C — implementation)
Adds a fourth adapter — `src/adapters/opencode/` — that drives SST
OpenCode (https://opencode.ai) as a headless local subprocess, giving
claude-tempo a multi-provider LLM story (Anthropic, OpenAI, Bedrock,
Vertex, Ollama, ~70+ providers via OpenCode's `provider/model` selector).
`OpenCodeAttachment extends SdkAttachment` mirrors the claude-api /
Copilot bridge structure: detached Node subprocess, dual-purpose entry
point (class import + `require.main === module` self-exec),
`claimAttachment` + heartbeat lifecycle inherited free.
Selected via `recruit({ agent: ''opencode'', model: ''provider/name'', ... })`.
## What's new
- `src/adapters/opencode/adapter.ts` — OpenCodeAttachment class
- `src/adapters/opencode/server-bridge.ts` — HTTP/SSE wrapper over raw
fetch (5 endpoints + `/event` SSE generator). Per design §8.3 #2,
raw fetch beats `@opencode-ai/sdk` weight here — the SDK is ESM-only
and adds OpenAPI runtime + per-endpoint typed clients for ~50 endpoints
while we hot-path only ~5.
- `src/adapters/opencode/config.ts` — `OPENCODE_CONFIG_CONTENT` synthesis
with provider env auto-detection and security-locked invariants
(loopback bind, `mdns: false`).
- `src/adapters/opencode/helpers.ts` — port probe, version match, secret
redaction, subprocess wait helpers.
- `src/utils/sdk-probe.ts` — shared `probeSdkInstall(pkgName)` helper
used by adapter + recruit pre-flight. The SDK ships ESM-only with a
strict `exports` map (no `"require"` key, no `"./package.json"`
sub-path); both `require.resolve` paths trip ERR_PACKAGE_PATH_NOT_EXPORTED
even when installed. Filesystem walk bypasses the exports gate cleanly.
- `tests/adapters/opencode/{config,server-bridge}.test.ts` — 35 unit tests
covering provider auto-detection, security invariants, MCP block,
redaction, version-match, all 5 endpoint contracts, SSE block parser
(TCP-fragmentation tolerance, malformed-block skip).
## Wire-up
- `src/types.ts` — `''opencode''` added to AGENT_TYPES tuple. Auto-extends
`AgentType` union, recruit `z.enum(AGENT_TYPES)`, CLI parser allowlist,
help-text interpolation, `cli-agent-parser` test (auto-iterates).
- `src/config.ts` — `ENV.OPENCODE_MODEL` constant.
- `src/adapters/{base.ts,index.ts}` — registry wiring + `resolveFromAgentType`.
- `src/tools/recruit.ts` — relax `model` regex to `^[a-z0-9][a-z0-9-/.:_]*$`
(accepts both bare claude-api ids and provider/model opencode shapes);
loosen the line ~136 guard to also exempt `''opencode''`; pre-flight
rejects on missing SDK or missing `opencode` binary on PATH.
- `src/spawn.ts` — `spawnOpenCodeAdapter()` mirroring `spawnClaudeApiAdapter`.
Windows uses `cmd.exe /c opencode ...` (avoids DEP0190 from `shell: true`).
- `src/activities/outbox.ts` — three branches: spawn dispatch, model
metadata persistence, restart-path agentType + adapterId resolution.
- `src/tui/index.ts` — `''opencode''` added to the TUI default-agent
filter list (CLI/MCP-only adapter, like `''claude-api''`).
## Locked architectural decisions (ADR 0015)
- **Per-player subprocess** — simpler crash recovery, isolation, matches
Copilot. Subprocess-shared deferred to Phase 2.
- **Inline `OPENCODE_CONFIG_CONTENT` env** — no filesystem cleanup risk;
secrets-redacted stderr config-log preserves debuggability.
- **`type: "local"` stdio MCP** — symmetric with claude-api''s in-process
MCP; `dist/server.js` runs as OpenCode''s child for tool dispatch. NO
`mcp-bridge.ts` analog — OpenCode owns per-provider tool translation.
- **Probed-free port at recruit** — matches `src/http/server.ts` pattern.
- **Combined `model: ''provider/name''`** — opaque pass-through to OpenCode.
- **Server-side history** — adapter sends only the new turn''s parts;
OpenCode appends. No per-turn `buildAnthropicMessages` analog.
- **Warn-only on version drift** — refuse would brick on every minor
bump given OpenCode''s daily cadence; ignore loses diagnostic signal.
- **Tilde-pin `~1.14.29`** — OpenCode ships breaking changes under
SemVer minor (`parts` data model, `userMessage.variant`).
## Q6 verify-at-impl outcome — Path A
Ran the persistence experiment (`POST /session` → kill subprocess →
restart → `GET /session/:id`): HTTP 200 + valid Session body. OpenCode
persists sessions across `opencode serve` restart. **Path A implemented**
— adapter stashes the Session.id via `updateMetadataSignal`'s existing
`sessionId` field (same field copilot uses; `updateMetadata` wire surface
unchanged). Documented in `src/adapters/opencode/README.md`.
## Security posture
- `--hostname 127.0.0.1` hardcoded in config synthesis. NOT configurable.
OpenCode v1.14.x has no Bearer auth (anomalyco/opencode#24874); loopback bind
is the operational mitigation per ADR 0015 §53.
- `mdns: false` in synthesized config — avoids leaking session presence
over Bonjour.
## Wire surface
Zero new signals/queries/updates on `claudeSessionWorkflow`. The adapter
reuses the existing `sessionId` field on `updateMetadata` to stash the
OpenCode-side Session.id. `docs/WIRE-PROTOCOL.md` updated to note OpenCode
joins Copilot/Claude-Code as a `sessionId` consumer.
## Test coverage
- 35 vitest unit tests (`tests/adapters/opencode/`)
- 1 spawn-route regression test (`tests/adapters/claude-api/spawn-route.test.ts`)
- `cli-agent-parser` auto-extends — `--agent opencode` accepted
- Manual smoke verified on Windows (boot → free port probe → config
synthesis → opencode subprocess spawn → health probe → version-drift
WARNING). DEP0190 deprecation avoided via `cmd.exe /c` Windows pattern.
## Follow-ups (out of scope, design §11)
- Cross-provider tool parity testing (Phase 2 candidate)
- Subprocess-shared `opencode serve` (memory optimization)
- Reconnect opt-in for SDK adapters (server-side persistence makes this
attractive)
- `test/adapter-opencode-lifecycle-v2.test.ts` Mocha integration test
(mirrors claude-api''s posture — neither has one yet; tracked as
follow-up)
This commit also deletes the operational sequencing scaffold
(`docs/design/449-opencode-adapter-phase-c-sequencing.md`) per its §0
DoD checklist — the design doc + ADR 0015 carry the architectural record.
Closes#449
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* test(conformance): pin opencode descriptor in registry conformance suite
Update `test/conformance/registry.test.ts` for the fourth shipped adapter:
- Add an `opencode is registered and matches the §4.3 sdk shape` case
that pins the descriptor's `adapterClass`, `blocksOnLLMTurn`, and
`heartbeatMs` shape (mirrors the claude-api case directly above).
- Update `registry.all() contains exactly the three shipped descriptors`
→ `four shipped descriptors`; expand the deep-equal assertion to
include `'opencode'`.
- Update the deliberate-break comment to "fifth production adapter
ships" (the next escalation point).
This is the inverse-tripwire pattern that conductor flagged: AGENT_TYPES
auto-propagates from a single tuple, but this hand-maintained
conformance list drifts every adapter ship. Follow-up to refactor it to
derive from `registry.all()` is a separate PR per conductor's note.
Closes#449 follow-up CI gap (PR #485 shard-2 failure).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
---------
Co-authored-by: vinceblank <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Copy file name to clipboardExpand all lines: docs/WIRE-PROTOCOL.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -32,7 +32,7 @@ Signals sent **to** a `claudeSessionWorkflow` instance.
32
32
|`setPart`|`string`| Updates the player's current "part" — a short description of what the session is working on, visible to other players via `ensemble`. |
33
33
|`markDelivered`|`string[]`| Marks one or more messages (by ID) as delivered. Resets stale-detection timer; any delivery proves the session is alive. |
34
34
|`setName`|`string`| Updates the player's human-readable ID (`ClaudeTempoPlayerId` search attribute). Called by the `set_name` MCP tool. |
35
-
|`updateMetadata`|`{ hostname?, gitBranch?, gitRoot?, terminatedBy?, enableStaleDetection?, playerType?, playerTypeDescription?, worktreePath?, sessionId? }`| Updates session metadata fields and syncs search attributes. `enableStaleDetection: true` re-arms stale detection after reconnect; `worktreePath` records the git worktree path when the session uses worktree isolation; `sessionId` stores the session UUID — used for Copilot SDK session resumption and Claude Code deterministic `--resume` on restart. Note: the former `status: 'terminated'` shim was retired in PR-H (#132); use the `destroy` update for ordered session teardown. |
35
+
|`updateMetadata`|`{ hostname?, gitBranch?, gitRoot?, terminatedBy?, enableStaleDetection?, playerType?, playerTypeDescription?, worktreePath?, sessionId? }`| Updates session metadata fields and syncs search attributes. `enableStaleDetection: true` re-arms stale detection after reconnect; `worktreePath` records the git worktree path when the session uses worktree isolation; `sessionId` stores the session UUID — used for Copilot SDK session resumption, Claude Code deterministic `--resume` on restart, and (since #449 Phase C) re-attachment to the persisted OpenCode session id across `opencode serve` restart. Note: the former `status: 'terminated'` shim was retired in PR-H (#132); use the `destroy` update for ordered session teardown. |
36
36
|`releaseHeld`|*(none)*| Releases a held session: injects the stored initial message and unlocks the outbox. Sent by the conductor (or operator) after a session has been paused at startup via the hold/pause mechanism. **Idempotent** on sessions that aren't holding (no `heldMessage`, `outboxLocked` already `false`) — safe to blanket-signal across an ensemble. Used by the `release` MCP tool, `claude-tempo release` CLI, and (since #172) by `resume_ensemble { release: true }` / `claude-tempo resume --release` which fan it out to every running session. |
37
37
|`setPaused`|`boolean`| Pauses (`true`) or resumes (`false`) the session's outbox dispatch. While paused, queued outbox entries are not processed. |
38
38
|`heartbeat`|`{ attachmentId: string; at: string }`|**v0.25.** Liveness proof from the attached adapter — renews the lease's `expiresAt` to `workflow.now() + LEASE_MS`. Ignored (last-write-wins) if `attachmentId` doesn't match the current attachment. Adapters beat at 30 s (SDK) or 60 s (interactive). |
// loopback bind); tools dispatch via OpenCode's MCP-native config
544
+
// block (it spawns dist/server.js as its own MCP child). Per-tool
545
+
// allowlists don't apply — opencode players have full file/shell/
546
+
// web access via OpenCode's built-in tool registry.
547
+
if(allowedTools&&allowedTools.length>0){
548
+
log(`Warning: allowedTools [${allowedTools.join(', ')}] specified for opencode agent "${targetName}" — opencode adapter does not gate tools per recruit, skipping`);
549
+
}
550
+
const{ pid }=spawnOpenCodeAdapter({
551
+
name: targetName,
552
+
ensemble,
553
+
temporalAddress,
554
+
temporalNamespace,
555
+
temporalApiKey,
556
+
temporalTlsCertPath,
557
+
temporalTlsKeyPath,
558
+
isConductor,
559
+
workDir,
560
+
model,
561
+
attachmentId,
562
+
attachmentRunId,
563
+
adapterId,
564
+
});
565
+
log(`Spawned opencode adapter (pid ${pid}) in ${workDir} as "${targetName}"${model ? ` (model=${model})` : ''}${attachmentId ? ` (attachmentId=${attachmentId})` : ''}`);
Headless multi-provider LLM adapter — drives [SST OpenCode](https://opencode.ai) as a local subprocess. Selected via `recruit({ agent: 'opencode', model: 'provider/name' })`.
4
+
5
+
- Class: `OpenCodeAttachment extends SdkAttachment` — pull-based delivery, blocks on LLM turn, `processingStart`/`End` paired by base class.
- Tool bridging: **MCP-native** — OpenCode spawns `dist/server.js` as its own stdio MCP child via the `OPENCODE_CONFIG_CONTENT` env. No in-process MCP bridge / no schema translation layer.
8
+
- Session state: server-side persisted by OpenCode. Adapter sends only the new turn's parts; session id stashed on workflow metadata via the existing `sessionId` field on `updateMetadata`.
9
+
10
+
Design: [`docs/design/449-opencode-adapter.md`](../../../docs/design/449-opencode-adapter.md). ADR locked at [`docs/adr/0015-opencode-adapter.md`](../../../docs/adr/0015-opencode-adapter.md).
11
+
12
+
## Operator setup
13
+
14
+
```bash
15
+
# 1. Install the OpenCode binary (multi-platform; provides `opencode serve`)
16
+
npm install -g opencode-ai
17
+
18
+
# 2. Install the OpenCode SDK as the optional-dep gate
19
+
npm install @opencode-ai/sdk
20
+
21
+
# 3. Set provider auth — the adapter auto-detects from the `model`'s prefix
22
+
export ANTHROPIC_API_KEY=sk-... # for `model: 'anthropic/claude-opus-4-7'`
23
+
export OPENAI_API_KEY=sk-... # for `model: 'openai/gpt-4o'`
24
+
# (or rely on AWS / GCP / OAuth env chains for bedrock / vertex / github-copilot)
## Q6 — session persistence across `opencode serve` restart
31
+
32
+
**Path A (re-attach to stashed session id) is implemented.**
33
+
34
+
OpenCode persists session history server-side. The adapter stashes the session id on workflow metadata at create time via `updateMetadataSignal`'s existing `sessionId` field (same field copilot uses), so a workflow restart with a still-running `opencode serve` reattaches to the same session id and OpenCode continues appending to the existing history.
35
+
36
+
If the impl-time experiment had shown OpenCode does NOT persist sessions across server restart (Path B), the `invokeSdkWithBatch` first-turn branch would walk `allMessagesQuery` + `allSentMessagesQuery` and rebuild the conversation as `parts` on the new session — same shape as `claude-api`'s `buildAnthropicMessages`. ~80 LoC delta. Path A was selected because it is simpler and forward-compatible.
37
+
38
+
## Files
39
+
40
+
-[`adapter.ts`](./adapter.ts) — `OpenCodeAttachment` class + self-exec entry point
41
+
-[`server-bridge.ts`](./server-bridge.ts) — HTTP/SSE client over raw `fetch` (5 endpoints + `/event` SSE generator)
3. SIGTERM the `opencode serve` subprocess; SIGKILL after 5s if it doesn't exit (Windows-safe — Bun-runtime SIGTERM on Windows is unreliable per ADR 0015 §84, escalation handles it)
59
+
60
+
## PID file
61
+
62
+
Two-line file at `logs/{playerId}.pid`:
63
+
64
+
```
65
+
12345 # adapter PID
66
+
67890 # opencode serve subprocess PID
67
+
```
68
+
69
+
Operators can grep / `kill -9` either independently. Cleaned up on graceful shutdown; daemon `reconcile-on-boot` validates against `process.kill(pid, 0)` for orphan detection.
Same shape family as claude-api's `[claude-tempo:claude-api] turn-usage` — operators already grep `turn-usage` for cost monitoring. Provider attribution is added (`provider=...`) since opencode is multi-provider.
80
+
81
+
Per-provider semantics differ — Anthropic exposes `cache_read` / `cache_creation`, OpenAI doesn't. The adapter logs whatever's present; cross-provider normalization is a Phase 2 candidate.
82
+
83
+
## Version drift
84
+
85
+
The adapter probes `GET /global/health` on boot and logs:
86
+
87
+
```
88
+
[claude-tempo:opencode] WARNING: opencode version 1.15.0 drift from tested ~1.14.29
89
+
```
90
+
91
+
…when the running OpenCode major.minor diverges from the tested-pinned `~1.14.29`. **Warn-only** — refusing on every minor bump would brick users given OpenCode's daily release cadence (ADR 0015 §52, §65).
92
+
93
+
## Phase 2 forward-work hooks
94
+
95
+
See [`docs/adr/0015-opencode-adapter.md`](../../../docs/adr/0015-opencode-adapter.md#forward-looking-notes) for the full list:
0 commit comments