@bridgebrew/harness-opencode 0.0.0-stage → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bridgebrew
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,36 @@
1
- # Temporary Holding Version
1
+ # OpenCode driver (`@bridgebrew/harness-opencode`)
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
+ Lets Bridge's Sessions talk to OpenCode 2 (2.0.18 or newer): one `opencode serve` per session.
4
+
5
+ ## Install
6
+
7
+ Installed with every new workspace.
8
+
9
+ Install OpenCode 2 with `npm install -g @opencode/cli` (it installs `opencode2` beside `opencode`), then sign in to
10
+ your providers with `opencode2 auth login`. OpenCode 1.x is not supported.
11
+
12
+ ## Use
13
+
14
+ In Settings › Harness, an OpenCode entry takes:
15
+
16
+ - **Command**: the OpenCode 2 executable, on the `PATH` or as an absolute path. Empty: `opencode2`.
17
+ - **Launch arguments**: extra `opencode serve` flags (e.g. `--log-level debug`).
18
+ - **Decision timeout (ms)**: how long a permission request waits for an answer. Empty: until the turn ends.
19
+
20
+ In a session, the agent's text and reasoning stream as they come, with its tool calls and the diffs of its edits.
21
+ Its permission requests and questions show as decisions: allow, allow for this session, or deny. In Plan, OpenCode's
22
+ `plan` agent works with every edit denied. You pick the model, send a message into a running turn, stop a turn, and
23
+ see its sub-agents' work. A session resumes where it left off.
24
+
25
+ ## Contracts
26
+
27
+ Requires `harness`.
28
+
29
+ ## Limits
30
+
31
+ Not handled yet: work OpenCode starts by itself (a background sub-agent's report), fork and rollback, compaction,
32
+ slash commands, model variants, an external OpenCode server, reconnecting a lost event stream.
33
+
34
+ ## Third-party code
35
+
36
+ Parts of this driver are adapted from MIT-licensed code: see [`THIRD_PARTY_NOTICES`](THIRD_PARTY_NOTICES).
@@ -0,0 +1,23 @@
1
+ Portions of this package are adapted from T3 Code (https://github.com/pingdotgg/t3code): its OpenCode 2 adapter, under the license below.
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2026 T3 Tools Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/api.ts ADDED
@@ -0,0 +1,163 @@
1
+ // OpenCode 2's server API as the driver uses it: JSON over HTTP with Basic auth (user `opencode`, the password the
2
+ // driver gave the server), and the global event stream `GET /api/event` (SSE). Plain `fetch`, no `@opencode/client`:
3
+ // that client fails its whole stream on the first event a newer server adds, so frames
4
+ // are decoded one by one here and an unreadable one is skipped.
5
+ import { isRecord } from './json.ts';
6
+
7
+ /** `fetch`, or a scripted one in tests. */
8
+ export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
9
+
10
+ /** One event of the stream: its `type` and `data` (the rest of the envelope is not read). */
11
+ export interface Event {
12
+ type: string;
13
+ data: unknown;
14
+ }
15
+
16
+ /** A refused request: its status and OpenCode's error (`{ _tag, message }`). */
17
+ export class ApiError extends Error {
18
+ readonly status: number;
19
+ readonly tag: string | undefined;
20
+ constructor(status: number, tag: string | undefined, message: string) {
21
+ super(message);
22
+ this.status = status;
23
+ this.tag = tag;
24
+ }
25
+ }
26
+
27
+ /** The server sends a `: heartbeat` comment every 10 to 15 s: this long without a byte means it is stuck. */
28
+ const SILENT_MS = 45_000;
29
+
30
+ export const connect = ({
31
+ url,
32
+ password,
33
+ fetch,
34
+ requestMs,
35
+ }: {
36
+ url: string;
37
+ password: string;
38
+ fetch: Fetch;
39
+ requestMs: number;
40
+ }) => {
41
+ const authorization = `Basic ${Buffer.from(`opencode:${password}`, 'utf8').toString('base64')}`;
42
+ const base = url.replace(/\/$/, '');
43
+
44
+ const request = async (method: string, path: string, body?: unknown): Promise<unknown> => {
45
+ const response = await fetch(`${base}${path}`, {
46
+ method,
47
+ headers: {
48
+ authorization,
49
+ ...(body !== undefined && { 'content-type': 'application/json' }),
50
+ },
51
+ ...(body !== undefined && { body: JSON.stringify(body) }),
52
+ signal: AbortSignal.timeout(requestMs),
53
+ });
54
+ const text = await response.text();
55
+ let json: unknown;
56
+ try {
57
+ json = text ? JSON.parse(text) : undefined;
58
+ } catch {
59
+ json = undefined;
60
+ }
61
+ if (!response.ok)
62
+ throw new ApiError(
63
+ response.status,
64
+ isRecord(json) && typeof json._tag === 'string' ? json._tag : undefined,
65
+ `OpenCode answered ${method} ${path} with ${response.status}${isRecord(json) && typeof json.message === 'string' ? `: ${json.message}` : ''}`,
66
+ );
67
+ return json;
68
+ };
69
+
70
+ /** Subscribes to the event stream: resolves once the server accepted it (events before that are not seen, so
71
+ * subscribe before acting). `onEvent` hears each event; `onEnd` once, when the stream ends, fails or goes silent
72
+ * for `SILENT_MS`, or `stop` ran (then with no error). */
73
+ const events = async (
74
+ onEvent: (event: Event) => void,
75
+ onEnd: (error?: Error) => void,
76
+ ): Promise<{ stop(): void }> => {
77
+ const abort = new AbortController();
78
+ let stopped = false;
79
+ let ended = false;
80
+ const end = (error?: Error) => {
81
+ if (ended) return;
82
+ ended = true;
83
+ clearTimeout(silence);
84
+ abort.abort();
85
+ onEnd(stopped ? undefined : error);
86
+ };
87
+ let silence: ReturnType<typeof setTimeout> | undefined;
88
+ const heard = () => {
89
+ clearTimeout(silence);
90
+ silence = setTimeout(
91
+ () => end(new Error('The OpenCode server stopped sending events.')),
92
+ SILENT_MS,
93
+ );
94
+ };
95
+ const response = await fetch(`${base}/api/event`, {
96
+ method: 'GET',
97
+ headers: { authorization, accept: 'text/event-stream' },
98
+ signal: abort.signal,
99
+ });
100
+ if (!response.ok || !response.body) {
101
+ abort.abort();
102
+ throw new ApiError(
103
+ response.status,
104
+ undefined,
105
+ `OpenCode refused its event stream (${response.status})`,
106
+ );
107
+ }
108
+ heard();
109
+ void (async () => {
110
+ const decoder = new TextDecoder();
111
+ let buffer = '';
112
+ try {
113
+ // oxlint-disable-next-line bridge/no-new-unchecked-cast -- typing: Node's fetch body is an async iterable of bytes, which its DOM type does not say
114
+ for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
115
+ heard();
116
+ buffer += decoder.decode(chunk, { stream: true }).replaceAll('\r\n', '\n');
117
+ let cut: number;
118
+ while ((cut = buffer.indexOf('\n\n')) >= 0) {
119
+ const frame = buffer.slice(0, cut);
120
+ buffer = buffer.slice(cut + 2);
121
+ const data = frame
122
+ .split('\n')
123
+ .filter((line) => line.startsWith('data:'))
124
+ .map((line) => line.slice(5).replace(/^ /, ''))
125
+ .join('\n');
126
+ if (!data) continue; // a comment (the heartbeat)
127
+ let event: unknown;
128
+ try {
129
+ event = JSON.parse(data);
130
+ } catch {
131
+ continue;
132
+ }
133
+ if (isRecord(event) && typeof event.type === 'string')
134
+ onEvent({ type: event.type, data: event.data ?? {} });
135
+ }
136
+ }
137
+ end(new Error('The OpenCode event stream ended.'));
138
+ } catch (error) {
139
+ end(error instanceof Error ? error : new Error(String(error)));
140
+ }
141
+ })().catch((error: unknown) => end(error instanceof Error ? error : new Error(String(error))));
142
+ return {
143
+ stop() {
144
+ stopped = true;
145
+ end();
146
+ },
147
+ };
148
+ };
149
+
150
+ return {
151
+ get: (path: string) => request('GET', path),
152
+ post: (path: string, body?: unknown) => request('POST', path, body ?? {}),
153
+ put: (path: string, body: unknown) => request('PUT', path, body),
154
+ patch: (path: string, body: unknown) => request('PATCH', path, body),
155
+ delete: (path: string) => request('DELETE', path),
156
+ events,
157
+ };
158
+ };
159
+ export type Api = ReturnType<typeof connect>;
160
+
161
+ /** `?location[directory]=<dir>`: how OpenCode's routes take the folder they act on. */
162
+ export const located = (directory: string) =>
163
+ `location[directory]=${encodeURIComponent(directory)}`;
package/json.ts ADDED
@@ -0,0 +1,9 @@
1
+ // A JSON value from outside, checked before its fields are read (a copy of Bridge's own helpers, which are internal to
2
+ // Bridge: a plugin installed from the registry cannot take them).
3
+
4
+ /** An object, neither `null` nor an array: what a parsed JSON value is checked to be before its fields are read. */
5
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
6
+ typeof value === 'object' && value !== null && !Array.isArray(value);
7
+
8
+ /** `value`'s items when it is an array, else none: an array from outside read without `Array.isArray`'s `any[]`. */
9
+ export const listOf = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@bridgebrew/harness-opencode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "license": "MIT",
5
+ "description": "Lets the harness run OpenCode 2, one server per session.",
6
+ "keywords": [
7
+ "bridge-plugin"
8
+ ],
9
+ "type": "module",
10
+ "files": [
11
+ "*.json",
12
+ "*.ts",
13
+ "THIRD_PARTY_NOTICES",
14
+ "!**/*.test.ts",
15
+ "!**/*.test.tsx"
16
+ ],
17
+ "bridge": {
18
+ "kind": "service",
19
+ "title": "OpenCode driver",
20
+ "icon": "plug",
21
+ "domain": "agents",
22
+ "server": "./server.ts",
23
+ "requires": {
24
+ "harness": {}
25
+ },
26
+ "driver": {
27
+ "name": "opencode",
28
+ "title": "OpenCode",
29
+ "description": "OpenCode 2 (2.0.18 or newer), through opencode serve; it uses its own logins and models (opencode2 auth login).",
30
+ "config": {
31
+ "type": "object",
32
+ "properties": {
33
+ "command": {
34
+ "type": "string",
35
+ "title": "Command",
36
+ "description": "The OpenCode 2 executable, on the PATH or as an absolute path. Empty: opencode2, the name npm install -g @opencode/cli installs beside opencode."
37
+ },
38
+ "args": {
39
+ "type": "array",
40
+ "items": {
41
+ "type": "string"
42
+ },
43
+ "title": "Launch arguments",
44
+ "description": "Extra opencode serve flags (e.g. --log-level debug)."
45
+ },
46
+ "decisionTimeoutMs": {
47
+ "type": "integer",
48
+ "minimum": 0,
49
+ "title": "Decision timeout (ms)",
50
+ "description": "How long a permission request waits for an answer; empty = until the turn ends."
51
+ }
52
+ }
53
+ }
54
+ },
55
+ "provenance": "official"
56
+ },
57
+ "peerDependencies": {
58
+ "cordis": "4.0.0-rc.11"
59
+ },
60
+ "releaseStage": "dev",
61
+ "scripts": {
62
+ "test": "bridge plugin test .",
63
+ "typecheck": "bridge plugin check ."
64
+ }
65
+ }