Skip to content

Commit 1d5f5a4

Browse files
agent-tempo[bot]vinceblankclaude
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]>
1 parent 1051da8 commit 1d5f5a4

24 files changed

Lines changed: 2123 additions & 255 deletions

‎docs/WIRE-PROTOCOL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ Signals sent **to** a `claudeSessionWorkflow` instance.
3232
| `setPart` | `string` | Updates the player's current "part" — a short description of what the session is working on, visible to other players via `ensemble`. |
3333
| `markDelivered` | `string[]` | Marks one or more messages (by ID) as delivered. Resets stale-detection timer; any delivery proves the session is alive. |
3434
| `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. |
3636
| `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. |
3737
| `setPaused` | `boolean` | Pauses (`true`) or resumes (`false`) the session's outbox dispatch. While paused, queued outbox entries are not processed. |
3838
| `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). |

‎docs/design/449-opencode-adapter-phase-c-sequencing.md‎

Lines changed: 0 additions & 213 deletions
This file was deleted.

‎package-lock.json‎

Lines changed: 14 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@
7878
},
7979
"optionalDependencies": {
8080
"@github/copilot-sdk": "^0.2.0",
81-
"@anthropic-ai/sdk": "~0.91.1"
81+
"@anthropic-ai/sdk": "~0.91.1",
82+
"@opencode-ai/sdk": "~1.14.29"
8283
},
8384
"dependencies": {
8485
"@modelcontextprotocol/sdk": "~1.28.0",

‎src/activities/outbox.ts‎

Lines changed: 53 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
} from '../utils/validation';
1313
import { ENSEMBLE_SENTINEL_FLAG } from '../constants';
1414
import { getGitInfo } from '../git-info';
15-
import { spawnInTerminal, spawnCopilotBridge, spawnClaudeApiAdapter } from '../spawn';
15+
import { spawnInTerminal, spawnCopilotBridge, spawnClaudeApiAdapter, spawnOpenCodeAdapter } from '../spawn';
1616
import { ENV } from '../config';
1717
import { resolveSession } from './resolve';
1818
import { resolveAgentType } from '../ensemble/agent-types';
@@ -244,11 +244,14 @@ export interface SpawnProcessInput {
244244
mockMode?: MockMode;
245245
mockScenario?: string;
246246
/**
247-
* #131 Phase C — claude-api adapter model id (e.g. `claude-opus-4-7`).
248-
* Forwarded into the spawned subprocess as `CLAUDE_TEMPO_API_MODEL`. Only
249-
* meaningful when `agent === 'claude-api'`; ignored otherwise. Falls back
250-
* inside the adapter to `CLAUDE_TEMPO_API_MODEL` env (set by spawner) →
251-
* constants-pinned default (`claude-opus-4-7`).
247+
* #131 / #449 Phase C — model id for the headless adapters.
248+
* - `claude-api`: bare Anthropic id (e.g. `claude-opus-4-7`); forwarded
249+
* as `CLAUDE_TEMPO_API_MODEL`.
250+
* - `opencode`: combined provider/model (e.g. `anthropic/claude-opus-4-7`,
251+
* `openai/gpt-4o`); forwarded as `CLAUDE_TEMPO_OPENCODE_MODEL`.
252+
* The spawn dispatcher inspects `agent` to pick the right env var. Only
253+
* meaningful for those two adapters; ignored otherwise. Falls back inside
254+
* the adapter to its respective env var → constants-pinned default.
252255
*/
253256
model?: string;
254257
}
@@ -398,9 +401,12 @@ export function createOutboxActivities(client: Client, config: Config): OutboxAc
398401
// from the registry without falling back to the legacy agentType field.
399402
adapterId: registry.resolveFromAgentType(agent),
400403
sessionId,
401-
// #131 Phase C — persist the claude-api model on durable metadata
402-
// so restart can recover the original choice across CAN.
403-
...(agent === 'claude-api' && model ? { model } : {}),
404+
// #131 / #449 Phase C — persist the claude-api / opencode model
405+
// on durable metadata so restart can recover the original choice
406+
// across CAN. Both adapters use the same `model` metadata field
407+
// (different value shapes — bare vs `provider/model`) — the spawn
408+
// path inspects `metadata.agentType` to know which env var to set.
409+
...((agent === 'claude-api' || agent === 'opencode') && model ? { model } : {}),
404410
...(agentDefinition ? { playerType: agentDefinition } : {}),
405411
...(agentDefinitionDescription ? { playerTypeDescription: agentDefinitionDescription } : {}),
406412
recruitedBy: fromPlayerId,
@@ -530,6 +536,33 @@ export function createOutboxActivities(client: Client, config: Config): OutboxAc
530536
adapterId,
531537
});
532538
log(`Spawned claude-api adapter (pid ${pid}) in ${workDir} as "${targetName}"${model ? ` (model=${model})` : ''}${attachmentId ? ` (attachmentId=${attachmentId})` : ''}`);
539+
} else if (agent === 'opencode') {
540+
// #449 Phase C — headless multi-provider adapter via OpenCode.
541+
// No terminal, no Claude binary. The adapter manages its own
542+
// `opencode serve` subprocess (probed-free port, hardcoded
543+
// 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})` : ''}`);
533566
} else {
534567
// Resolve agent flags: --agent (native) > --system-prompt (shipped/legacy)
535568
let agentFlags: string[] = [];
@@ -770,26 +803,30 @@ export function createOutboxActivities(client: Client, config: Config): OutboxAc
770803
// Prod restart never lands here for `mock` because gate 3 in
771804
// src/tools/recruit.ts rejected the original recruit.
772805
const rawAgent = metadata.agentType as string | undefined;
773-
// #131 Phase C — claude-api joins copilot/mock as a recognized
774-
// sdk-class agent here so restart/encore/migrate of a claude-api
775-
// player resolves to the right adapterId + class. Without this
776-
// branch, restart falls through to 'claude' → 'interactive' and
777-
// the spawn path picks the terminal Claude Code path.
806+
// #131 / #449 Phase C — claude-api / opencode join copilot / mock
807+
// as recognized sdk-class agents here so restart/encore/migrate of
808+
// a headless player resolves to the right adapterId + class. Without
809+
// this branch, restart falls through to 'claude' → 'interactive'
810+
// and the spawn path picks the terminal Claude Code path.
778811
const agentType: AgentType = rawAgent === 'copilot'
779812
? 'copilot'
780813
: rawAgent === 'mock'
781814
? 'mock'
782815
: rawAgent === 'claude-api'
783816
? 'claude-api'
784-
: 'claude';
817+
: rawAgent === 'opencode'
818+
? 'opencode'
819+
: 'claude';
785820
const adapterId = metadata.adapterId
786821
|| (agentType === 'copilot'
787822
? 'copilot'
788823
: agentType === 'mock'
789824
? 'mock'
790825
: agentType === 'claude-api'
791826
? 'claude-api'
792-
: 'claude-code');
827+
: agentType === 'opencode'
828+
? 'opencode'
829+
: 'claude-code');
793830
const adapterClass: AdapterClass = agentType === 'claude' ? 'interactive' : 'sdk';
794831
const targetHost = host ?? info.preferredHost ?? metadata.hostname;
795832

‎src/adapters/base.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1362,6 +1362,9 @@ export class AdapterRegistry {
13621362
// #131 Phase C — headless Claude API adapter. Descriptor lives in
13631363
// src/adapters/claude-api; opt-in via `recruit({ agent: 'claude-api' })`.
13641364
if (agent === 'claude-api') return 'claude-api';
1365+
// #449 Phase C — headless multi-provider OpenCode adapter. Descriptor
1366+
// lives in src/adapters/opencode; opt-in via `recruit({ agent: 'opencode' })`.
1367+
if (agent === 'opencode') return 'opencode';
13651368
return 'claude-code';
13661369
}
13671370
}

‎src/adapters/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { AdapterRegistry } from './base';
1919
import { claudeCodeDescriptor } from './claude-code';
2020
import { copilotDescriptor } from './copilot';
2121
import { claudeApiDescriptor } from './claude-api';
22+
import { opencodeDescriptor } from './opencode';
2223
import { isDevMode } from '../config';
2324

2425
export const registry = new AdapterRegistry();
@@ -30,6 +31,11 @@ registry.register(copilotDescriptor);
3031
// descriptor itself has no SDK dependency, so the registry can list and
3132
// resolve it even on hosts that haven't installed the SDK).
3233
registry.register(claudeApiDescriptor);
34+
// #449 Phase C — headless multi-provider OpenCode adapter. Always-registered
35+
// for the same reason as claude-api: the optional `@opencode-ai/sdk` and the
36+
// `opencode` binary only matter at adapter spawn time. The recruit pre-flight
37+
// gates on both being available (or `force: true` to bypass).
38+
registry.register(opencodeDescriptor);
3339

3440
// ADR 0014 §7 gate 2 — import-time registration gate. The mock adapter's
3541
// descriptor only enters the registry when `isDevMode()` is true.
@@ -71,4 +77,5 @@ export { SdkAttachment } from './sdk/base';
7177
export { InteractiveAttachment } from './claude-code';
7278
export { CopilotSdkAttachment } from './copilot';
7379
export { DirectApiAttachment } from './claude-api';
80+
export { OpenCodeAttachment } from './opencode';
7481
export type { AdapterClass, AdapterDescriptor } from '../types';

‎src/adapters/opencode/README.md‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# opencode adapter
2+
3+
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.
6+
- LLM transport: HTTP/SSE via `opencode serve` subprocess (probed-free port, hardcoded `--hostname 127.0.0.1`).
7+
- 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)
25+
26+
# 4. Recruit
27+
claude-tempo recruit my-player --agent opencode --model anthropic/claude-opus-4-7
28+
```
29+
30+
## 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)
42+
- [`config.ts`](./config.ts) — `OPENCODE_CONFIG_CONTENT` synthesis + provider env detection
43+
- [`helpers.ts`](./helpers.ts) — `probeFreePort`, `waitForExit`, `redactSecrets`, `isVersionMatch`
44+
- [`index.ts`](./index.ts) — barrel re-export
45+
46+
## Cancellation chain
47+
48+
Lease revocation → `onSuperseded()`:
49+
50+
1. Abort the in-flight SSE consumer / `prompt_async` fetch via `inFlightAbortController`
51+
2. Fire-and-forget `POST /session/:id/abort` (graceful — OpenCode releases the turn)
52+
3. `processingEnd` fires in the inherited `finally` per `SdkAttachment.deliver()`
53+
54+
Graceful detach (terminal callback / SIGTERM / SIGINT):
55+
56+
1. `POST /session/:id/abort` → `DELETE /session/:id` (best-effort cleanup)
57+
2. `detachGracefully('user-stop')` → fires `adapterExited`
58+
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.
70+
71+
## Telemetry
72+
73+
Per-turn stderr log line:
74+
75+
```
76+
[claude-tempo:opencode] turn-usage provider=anthropic model=anthropic/claude-opus-4-7 input=1234 output=567 cache_read=8910 elapsed_ms=4321 player=my-player stop_reason=end_turn
77+
```
78+
79+
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:
96+
97+
- Cross-provider tool parity testing
98+
- Subprocess-shared `opencode serve` (memory optimization)
99+
- `type: "remote"` MCP transport
100+
- Per-provider quota awareness
101+
- Reconnect opt-in (server-side persistence makes this attractive)
102+
- Advisor strategy (executor + advisor on different providers, both via opencode)

0 commit comments

Comments
 (0)