@velum-labs/routekit-tool-opencode 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Velum Labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @velum-labs/routekit-tool-opencode
2
+
3
+ Product-neutral OpenCode launcher and canonical harness driver.
4
+
5
+ ## Architecture
6
+
7
+ This package owns the one OpenCode configuration serializer, launcher, and routed driver.
8
+
9
+ ## Usage
10
+
11
+ Register `opencodeTool` in an `@velum-labs/routekit-tools` registry.
12
+
13
+ ```ts
14
+ import { opencodeTool } from "@velum-labs/routekit-tool-opencode";
15
+ ```
16
+
17
+ ## Docs
18
+
19
+ - Product docs: https://fusionkit.velum-labs.com
20
+ - Maintainer reference: [../../docs/typescript-reference.md](../../docs/typescript-reference.md)
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ import type { DriverContext, HarnessDriver, StartSessionOptions } from "@velum-labs/routekit-harness-core";
3
+ export declare const opencodeDriverConfigSchema: z.ZodObject<{
4
+ command: z.ZodDefault<z.ZodString>;
5
+ serverUrl: z.ZodOptional<z.ZodString>;
6
+ gatewayUrl: z.ZodString;
7
+ authToken: z.ZodOptional<z.ZodString>;
8
+ model: z.ZodOptional<z.ZodString>;
9
+ providerId: z.ZodOptional<z.ZodString>;
10
+ }, z.core.$strip>;
11
+ export type OpencodeDriverConfig = z.infer<typeof opencodeDriverConfigSchema>;
12
+ /** One buffered opencode turn result, normalized from `session.prompt`. */
13
+ export type OpencodeTurnPart = {
14
+ type: "text";
15
+ text: string;
16
+ } | {
17
+ type: "reasoning";
18
+ text: string;
19
+ } | {
20
+ type: "tool";
21
+ tool: string;
22
+ callId: string;
23
+ status: "completed" | "failed" | "running";
24
+ } | {
25
+ type: "step-finish";
26
+ tokens?: {
27
+ input: number;
28
+ output: number;
29
+ reasoning: number;
30
+ };
31
+ };
32
+ export type OpencodeTurnResult = {
33
+ parts: OpencodeTurnPart[];
34
+ };
35
+ /**
36
+ * The narrow opencode surface the driver needs, isolated so the real
37
+ * `@opencode-ai/sdk` server+client wiring stays behind one seam and tests can
38
+ * inject a scripted backend without standing up a server.
39
+ */
40
+ export interface OpencodeBackend {
41
+ createSession(input: {
42
+ cwd: string;
43
+ resume?: string;
44
+ }): Promise<{
45
+ sessionId: string;
46
+ }>;
47
+ prompt(input: {
48
+ sessionId: string;
49
+ cwd: string;
50
+ prompt: string;
51
+ model?: string;
52
+ providerId?: string;
53
+ reasoning?: StartSessionOptions["reasoning"];
54
+ signal?: AbortSignal;
55
+ }): Promise<OpencodeTurnResult>;
56
+ abort(input: {
57
+ sessionId: string;
58
+ cwd: string;
59
+ }): Promise<void>;
60
+ dispose(): Promise<void>;
61
+ }
62
+ export type OpencodeBackendFactory = (config: OpencodeDriverConfig, context: DriverContext | undefined) => Promise<OpencodeBackend>;
63
+ export type OpencodeDriverOptions = {
64
+ /** Test/extension seam; defaults to the real SDK-backed server+client. */
65
+ backendFactory?: OpencodeBackendFactory;
66
+ };
67
+ export declare function createOpencodeDriver(options?: OpencodeDriverOptions): HarnessDriver<OpencodeDriverConfig>;
package/dist/driver.js ADDED
@@ -0,0 +1,330 @@
1
+ import { z } from "zod";
2
+ import { createOpencodeClient } from "@opencode-ai/sdk/client";
3
+ import { createOpencodeServer } from "@opencode-ai/sdk/server";
4
+ import { HarnessError, DEFAULT_AUTOMATION_APPROVAL_POLICY, asHarnessError, buildChildEnv, createCachedHarnessDriver, probeCliVersion, resolveDriverEnv } from "@velum-labs/routekit-harness-core";
5
+ import { opencodeProviderConfig } from "./launch.js";
6
+ const RESUME_CURSOR_VERSION = 1;
7
+ const DEFAULT_COMMAND = "opencode";
8
+ export const opencodeDriverConfigSchema = z.object({
9
+ command: z.string().default(DEFAULT_COMMAND),
10
+ /** Reuse an already-running opencode server instead of starting one. */
11
+ serverUrl: z.string().optional(),
12
+ /** OpenAI-compatible gateway root used by the routed provider. */
13
+ gatewayUrl: z.string().url(),
14
+ /** Optional bearer token forwarded as the provider API key. */
15
+ authToken: z.string().optional(),
16
+ /** Opaque `providerID/modelID` route the session should run. */
17
+ model: z.string().optional(),
18
+ providerId: z.string().optional()
19
+ });
20
+ function nowIso() {
21
+ return new Date().toISOString();
22
+ }
23
+ function itemTypeForTool(tool) {
24
+ const lower = tool.toLowerCase();
25
+ if (lower.includes("bash") || lower.includes("shell"))
26
+ return "command_execution";
27
+ if (lower.includes("edit") || lower.includes("write") || lower.includes("patch"))
28
+ return "file_change";
29
+ if (lower.includes("web") || lower.includes("fetch"))
30
+ return "web_search";
31
+ return "dynamic_tool_call";
32
+ }
33
+ class OpencodeSession {
34
+ #kind = "opencode";
35
+ #backend;
36
+ #cwd;
37
+ #model;
38
+ #providerId;
39
+ #approvalPolicy;
40
+ #reasoning;
41
+ #sessionId;
42
+ #stopped = false;
43
+ constructor(input) {
44
+ this.#backend = input.backend;
45
+ this.#sessionId = input.sessionId;
46
+ this.#cwd = input.cwd;
47
+ this.#model = input.model;
48
+ this.#providerId = input.providerId;
49
+ this.#approvalPolicy = input.approvalPolicy;
50
+ this.#reasoning = input.reasoning;
51
+ }
52
+ get sessionId() {
53
+ return this.#sessionId;
54
+ }
55
+ async *sendTurn(input) {
56
+ if (this.#stopped)
57
+ throw new HarnessError("session_closed", "opencode session is stopped");
58
+ const base = { kind: this.#kind, sessionId: this.#sessionId, at: nowIso() };
59
+ const turnId = `${this.#sessionId}:turn:${Date.now()}`;
60
+ // A function call so TS does not narrow `aborted` to a constant across the
61
+ // await below (the signal can fire mid-turn).
62
+ const isAborted = () => input.signal?.aborted === true;
63
+ yield { ...base, type: "turn.started", turnId };
64
+ if (isAborted()) {
65
+ yield { ...base, type: "turn.completed", turnId, endReason: "aborted" };
66
+ return;
67
+ }
68
+ let result;
69
+ const reasoning = input.reasoning ?? this.#reasoning;
70
+ if (reasoning !== undefined &&
71
+ reasoning.mode !== "auto" &&
72
+ reasoning.mode !== "effort") {
73
+ throw new HarnessError("invalid_config", `OpenCode variants cannot represent reasoning mode "${reasoning.mode}"`);
74
+ }
75
+ try {
76
+ result = await this.#backend.prompt({
77
+ sessionId: this.#sessionId,
78
+ cwd: this.#cwd,
79
+ prompt: input.prompt,
80
+ ...(this.#model !== undefined ? { model: this.#model } : {}),
81
+ ...(this.#providerId !== undefined ? { providerId: this.#providerId } : {}),
82
+ ...(reasoning !== undefined ? { reasoning } : {}),
83
+ ...(input.signal !== undefined ? { signal: input.signal } : {})
84
+ });
85
+ }
86
+ catch (error) {
87
+ if (isAborted()) {
88
+ yield { ...base, type: "turn.completed", turnId, endReason: "aborted" };
89
+ return;
90
+ }
91
+ const harnessError = asHarnessError(error);
92
+ yield { ...base, type: "turn.failed", turnId, errorCode: harnessError.code, message: harnessError.message };
93
+ return;
94
+ }
95
+ let usage;
96
+ for (const part of result.parts) {
97
+ const raw = { source: "opencode.sdk.part", method: part.type };
98
+ switch (part.type) {
99
+ case "text":
100
+ if (part.text.length > 0) {
101
+ yield { ...base, type: "content.delta", turnId, stream: "assistant_text", text: part.text, raw };
102
+ }
103
+ break;
104
+ case "reasoning":
105
+ if (part.text.length > 0) {
106
+ yield { ...base, type: "content.delta", turnId, stream: "reasoning_text", text: part.text, raw };
107
+ }
108
+ break;
109
+ case "tool":
110
+ yield {
111
+ ...base,
112
+ type: "item.completed",
113
+ turnId,
114
+ itemId: part.callId,
115
+ itemType: itemTypeForTool(part.tool),
116
+ status: part.status === "failed" ? "failed" : "completed",
117
+ raw
118
+ };
119
+ break;
120
+ case "step-finish":
121
+ if (part.tokens !== undefined) {
122
+ usage = {
123
+ inputTokens: part.tokens.input,
124
+ outputTokens: part.tokens.output,
125
+ reasoningOutputTokens: part.tokens.reasoning
126
+ };
127
+ }
128
+ break;
129
+ default: {
130
+ const exhausted = part;
131
+ throw new Error(`unsupported opencode part: ${String(exhausted)}`);
132
+ }
133
+ }
134
+ }
135
+ yield {
136
+ ...base,
137
+ type: "turn.completed",
138
+ turnId,
139
+ endReason: "completed",
140
+ ...(usage !== undefined ? { usage } : {})
141
+ };
142
+ }
143
+ async respondToRequest() {
144
+ // Unattended runs use an auto-approve policy applied at session
145
+ // creation, so no interactive permission requests are surfaced.
146
+ throw new HarnessError("protocol_parse", "opencode driver does not surface interactive approval requests in buffered mode");
147
+ }
148
+ async interrupt() {
149
+ await this.#backend.abort({ sessionId: this.#sessionId, cwd: this.#cwd }).catch(() => undefined);
150
+ }
151
+ resumeCursor() {
152
+ return { version: RESUME_CURSOR_VERSION, kind: this.#kind, data: { sessionId: this.#sessionId } };
153
+ }
154
+ async stop() {
155
+ if (this.#stopped)
156
+ return;
157
+ this.#stopped = true;
158
+ await this.#backend.abort({ sessionId: this.#sessionId, cwd: this.#cwd }).catch(() => undefined);
159
+ }
160
+ // Kept for symmetry with other drivers; opencode's policy is applied at
161
+ // session creation rather than per request.
162
+ get approvalPolicy() {
163
+ return this.#approvalPolicy;
164
+ }
165
+ }
166
+ function resumeSessionId(resume) {
167
+ if (resume === undefined || resume.kind !== "opencode")
168
+ return undefined;
169
+ const data = resume.data;
170
+ return typeof data.sessionId === "string" ? data.sessionId : undefined;
171
+ }
172
+ class OpencodeInstance {
173
+ kind = "opencode";
174
+ #config;
175
+ #context;
176
+ #status;
177
+ #backendFactory;
178
+ #backend;
179
+ #sessions = new Set();
180
+ constructor(input) {
181
+ this.#config = input.config;
182
+ this.#context = input.context;
183
+ this.#status = input.status;
184
+ this.#backendFactory = input.backendFactory;
185
+ }
186
+ status() {
187
+ return this.#status;
188
+ }
189
+ async #ensureBackend() {
190
+ if (this.#backend === undefined) {
191
+ this.#backend = await this.#backendFactory(this.#config, this.#context);
192
+ }
193
+ return this.#backend;
194
+ }
195
+ async startSession(options) {
196
+ const backend = await this.#ensureBackend();
197
+ const resume = resumeSessionId(options.resume);
198
+ const created = await backend.createSession({
199
+ cwd: options.cwd,
200
+ ...(resume !== undefined ? { resume } : {})
201
+ });
202
+ const session = new OpencodeSession({
203
+ backend,
204
+ sessionId: created.sessionId,
205
+ cwd: options.cwd,
206
+ approvalPolicy: options.approvalPolicy ?? DEFAULT_AUTOMATION_APPROVAL_POLICY,
207
+ ...(options.model ?? this.#config.model !== undefined
208
+ ? { model: options.model ?? this.#config.model }
209
+ : {}),
210
+ ...(this.#config.providerId !== undefined
211
+ ? { providerId: this.#config.providerId }
212
+ : {}),
213
+ ...(options.reasoning !== undefined
214
+ ? { reasoning: options.reasoning }
215
+ : {})
216
+ });
217
+ this.#sessions.add(session);
218
+ return session;
219
+ }
220
+ async dispose() {
221
+ for (const session of this.#sessions)
222
+ await session.stop();
223
+ this.#sessions.clear();
224
+ await this.#backend?.dispose().catch(() => undefined);
225
+ this.#backend = undefined;
226
+ }
227
+ }
228
+ /** The default SDK-backed backend: an in-process opencode server + client. */
229
+ const defaultBackendFactory = async (config, context) => {
230
+ let close;
231
+ let baseUrl = config.serverUrl;
232
+ if (baseUrl === undefined) {
233
+ const server = await createOpencodeServer({
234
+ hostname: "127.0.0.1",
235
+ port: 0,
236
+ config: opencodeProviderConfig({
237
+ gatewayUrl: config.gatewayUrl,
238
+ models: config.model !== undefined ? [{ id: config.model }] : [],
239
+ ...(config.authToken !== undefined ? { auth: { token: config.authToken } } : {})
240
+ })
241
+ });
242
+ baseUrl = server.url;
243
+ close = server.close;
244
+ }
245
+ const client = createOpencodeClient({ baseUrl });
246
+ const partsFrom = (parts) => {
247
+ const out = [];
248
+ for (const part of parts) {
249
+ if (part.type === "text" && typeof part.text === "string") {
250
+ out.push({ type: "text", text: part.text });
251
+ }
252
+ else if (part.type === "reasoning" && typeof part.text === "string") {
253
+ out.push({ type: "reasoning", text: part.text });
254
+ }
255
+ else if (part.type === "tool") {
256
+ const state = part.state;
257
+ out.push({
258
+ type: "tool",
259
+ tool: String(part.tool ?? "tool"),
260
+ callId: String(part.callID ?? part.id ?? "call"),
261
+ status: state?.status === "error" ? "failed" : state?.status === "completed" ? "completed" : "running"
262
+ });
263
+ }
264
+ else if (part.type === "step-finish") {
265
+ const tokens = part.tokens;
266
+ out.push({ type: "step-finish", ...(tokens !== undefined ? { tokens } : {}) });
267
+ }
268
+ }
269
+ return out;
270
+ };
271
+ return {
272
+ createSession: async ({ cwd, resume }) => {
273
+ if (resume !== undefined)
274
+ return { sessionId: resume };
275
+ const created = await client.session.create({ query: { directory: cwd }, body: {} });
276
+ const data = created.data;
277
+ if (data?.id === undefined)
278
+ throw new HarnessError("provider_error", "opencode session.create returned no id");
279
+ return { sessionId: data.id };
280
+ },
281
+ prompt: async ({ sessionId, cwd, prompt, model, providerId, reasoning, signal }) => {
282
+ const modelBody = model !== undefined && providerId !== undefined
283
+ ? { model: { providerID: providerId, modelID: model } }
284
+ : {};
285
+ const response = await client.session.prompt({
286
+ path: { id: sessionId },
287
+ query: { directory: cwd },
288
+ body: {
289
+ parts: [{ type: "text", text: prompt }],
290
+ ...modelBody,
291
+ ...(reasoning?.mode === "effort"
292
+ ? { variant: reasoning.effort }
293
+ : {})
294
+ },
295
+ ...(signal !== undefined ? { signal } : {})
296
+ });
297
+ const data = response.data;
298
+ return { parts: partsFrom(data?.parts ?? []) };
299
+ },
300
+ abort: async ({ sessionId, cwd }) => {
301
+ await client.session.abort({ path: { id: sessionId }, query: { directory: cwd } });
302
+ },
303
+ dispose: async () => {
304
+ close?.();
305
+ }
306
+ };
307
+ };
308
+ /** Probe the opencode CLI: version + semver floor. */
309
+ async function probeOpencode(config, context) {
310
+ const env = buildChildEnv({ base: resolveDriverEnv(context) });
311
+ return probeCliVersion({
312
+ kind: "opencode",
313
+ command: config.command,
314
+ cliName: "opencode",
315
+ env,
316
+ // Auth is per-provider inside opencode; the server inventory reports it.
317
+ auth: { status: "unknown" },
318
+ notInstalledMessage: `opencode CLI "${config.command}" was not found on PATH.`
319
+ });
320
+ }
321
+ export function createOpencodeDriver(options = {}) {
322
+ const backendFactory = options.backendFactory ?? defaultBackendFactory;
323
+ return createCachedHarnessDriver({
324
+ kind: "opencode",
325
+ configSchema: opencodeDriverConfigSchema,
326
+ probeConfig: () => opencodeDriverConfigSchema.parse({ gatewayUrl: "http://127.0.0.1" }),
327
+ probeStatus: probeOpencode,
328
+ createInstance: (config, context, status) => new OpencodeInstance({ config, context, status, backendFactory })
329
+ });
330
+ }
@@ -0,0 +1,5 @@
1
+ import type { ToolIntegration } from "@velum-labs/routekit-tools";
2
+ export declare const opencodeTool: ToolIntegration;
3
+ export { launchOpencode, opencodeConfig, opencodeModelArg, opencodeProviderConfig } from "./launch.js";
4
+ export { createOpencodeDriver, opencodeDriverConfigSchema } from "./driver.js";
5
+ export type { OpencodeBackend, OpencodeBackendFactory, OpencodeDriverConfig, OpencodeDriverOptions, OpencodeTurnPart, OpencodeTurnResult } from "./driver.js";
package/dist/index.js ADDED
@@ -0,0 +1,32 @@
1
+ import { createOpencodeDriver, opencodeDriverConfigSchema } from "./driver.js";
2
+ import { launchOpencode } from "./launch.js";
3
+ const driver = createOpencodeDriver();
4
+ export const opencodeTool = {
5
+ id: "opencode",
6
+ displayName: "OpenCode",
7
+ pickerHint: "OpenCode CLI",
8
+ binary: "opencode",
9
+ packageName: "@velum-labs/routekit-tool-opencode",
10
+ installHint: "install OpenCode: https://opencode.ai/docs",
11
+ authSummary: "OpenCode uses an OpenAI-compatible gateway provider.",
12
+ setupSnippet: ({ gatewayUrl, model = "gateway-model" }) => `OpenCode gateway: ${gatewayUrl} (model: ${model})`,
13
+ launch: launchOpencode,
14
+ driver: {
15
+ kind: driver.kind,
16
+ driver,
17
+ configForRoute: (route) => opencodeDriverConfigSchema.parse({
18
+ gatewayUrl: route.gatewayUrl,
19
+ model: route.model,
20
+ providerId: "routekit",
21
+ ...(route.authToken !== undefined ? { authToken: route.authToken } : {})
22
+ })
23
+ },
24
+ capabilities: {
25
+ streaming: "full",
26
+ tools: "full",
27
+ images: "full",
28
+ reasoning_controls: "full"
29
+ }
30
+ };
31
+ export { launchOpencode, opencodeConfig, opencodeModelArg, opencodeProviderConfig } from "./launch.js";
32
+ export { createOpencodeDriver, opencodeDriverConfigSchema } from "./driver.js";
@@ -0,0 +1,10 @@
1
+ import type { ServerOptions } from "@opencode-ai/sdk/server";
2
+ import type { ToolLaunchContext, ToolLaunchSpec } from "@velum-labs/routekit-tools";
3
+ type OpencodeServerConfig = NonNullable<ServerOptions["config"]>;
4
+ export declare function opencodeModelArg(model: string): string;
5
+ /** Serialize one neutral routed provider for launchers and driver instances. */
6
+ export declare function opencodeProviderConfig(spec: Pick<ToolLaunchSpec, "gatewayUrl" | "models" | "agentProfiles" | "auth" | "reasoning">): OpencodeServerConfig;
7
+ /** Serialize the neutral model catalog and profiles into OpenCode JSON. */
8
+ export declare function opencodeConfig(spec: ToolLaunchSpec): OpencodeServerConfig;
9
+ export declare function launchOpencode(ctx: ToolLaunchContext): Promise<number>;
10
+ export {};
package/dist/launch.js ADDED
@@ -0,0 +1,72 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { spawnTool, trimTrailingSlashes } from "@velum-labs/routekit-runtime";
5
+ const PROVIDER_ID = "routekit";
6
+ export function opencodeModelArg(model) {
7
+ return `${PROVIDER_ID}/${model}`;
8
+ }
9
+ /** Serialize one neutral routed provider for launchers and driver instances. */
10
+ export function opencodeProviderConfig(spec) {
11
+ const configFor = (name, reasoning) => ({
12
+ name,
13
+ ...((reasoning?.efforts?.length ?? 0) > 0
14
+ ? {
15
+ variants: Object.fromEntries((reasoning?.efforts ?? []).map((effort) => [
16
+ effort.id,
17
+ { reasoningEffort: effort.id }
18
+ ]))
19
+ }
20
+ : {})
21
+ });
22
+ const models = Object.fromEntries(spec.models.flatMap((model) => [
23
+ [model.id, configFor(model.label ?? model.id, model.reasoning)],
24
+ ...(model.aliases ?? []).map((alias) => [
25
+ alias,
26
+ configFor(alias, model.reasoning)
27
+ ])
28
+ ]));
29
+ const agent = Object.fromEntries((spec.agentProfiles ?? []).map((profile) => [
30
+ profile.id,
31
+ {
32
+ mode: "subagent",
33
+ model: opencodeModelArg(profile.model),
34
+ description: profile.description,
35
+ prompt: profile.instructions
36
+ }
37
+ ]));
38
+ return {
39
+ $schema: "https://opencode.ai/config.json",
40
+ provider: {
41
+ [PROVIDER_ID]: {
42
+ npm: "@ai-sdk/openai-compatible",
43
+ name: "RouteKit gateway",
44
+ options: {
45
+ baseURL: `${trimTrailingSlashes(spec.gatewayUrl)}/v1`,
46
+ ...(spec.auth?.token !== undefined ? { apiKey: spec.auth.token } : {})
47
+ },
48
+ models
49
+ }
50
+ },
51
+ ...(Object.keys(agent).length > 0 ? { agent } : {})
52
+ };
53
+ }
54
+ /** Serialize the neutral model catalog and profiles into OpenCode JSON. */
55
+ export function opencodeConfig(spec) {
56
+ return opencodeProviderConfig(spec);
57
+ }
58
+ export async function launchOpencode(ctx) {
59
+ const dir = mkdtempSync(join(tmpdir(), "routekit-opencode-"));
60
+ ctx.registerDisposer(() => rmSync(dir, { recursive: true, force: true }));
61
+ const configPath = join(dir, "opencode.json");
62
+ writeFileSync(configPath, JSON.stringify(opencodeConfig(ctx.spec), null, 2));
63
+ const args = ctx.spec.args.includes("--model")
64
+ ? [...ctx.spec.args]
65
+ : ["--model", opencodeModelArg(ctx.spec.defaultModel), ...ctx.spec.args];
66
+ if (ctx.spec.reasoning?.mode === "effort" &&
67
+ !args.includes("--variant")) {
68
+ args.push("--variant", ctx.spec.reasoning.effort);
69
+ }
70
+ ctx.prepareForPassthrough();
71
+ return await spawnTool("opencode", args, { OPENCODE_CONFIG: configPath }, ctx.spec.cwd);
72
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,84 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { driverContractSuite } from "@velum-labs/routekit-harness-core/testing";
4
+ import { createOpencodeDriver } from "../driver.js";
5
+ /** A scripted opencode backend: echoes the prompt, no server required. */
6
+ function fakeBackend() {
7
+ let counter = 0;
8
+ return {
9
+ createSession: async ({ resume }) => ({ sessionId: resume ?? `opencode-session-${++counter}` }),
10
+ prompt: async ({ prompt, signal }) => {
11
+ if (signal?.aborted === true)
12
+ throw new Error("aborted");
13
+ return {
14
+ parts: [
15
+ { type: "reasoning", text: "thinking" },
16
+ { type: "tool", tool: "bash", callId: "call-1", status: "completed" },
17
+ { type: "text", text: `echo: ${prompt}` },
18
+ { type: "step-finish", tokens: { input: 4, output: 2, reasoning: 1 } }
19
+ ]
20
+ };
21
+ },
22
+ abort: async () => undefined,
23
+ dispose: async () => undefined
24
+ };
25
+ }
26
+ const backendFactory = async () => fakeBackend();
27
+ const driver = createOpencodeDriver({ backendFactory });
28
+ const config = () => ({ gatewayUrl: "http://127.0.0.1:9999" });
29
+ driverContractSuite({
30
+ name: "opencode driver",
31
+ createInstance: async () => driver.createInstance(driver.configSchema.parse(config())),
32
+ startOptions: () => ({ cwd: process.cwd() }),
33
+ supportsResume: true,
34
+ turnTimeoutMs: 10_000
35
+ });
36
+ test("opencode driver maps buffered parts into canonical events", async () => {
37
+ const instance = await driver.createInstance(driver.configSchema.parse(config()));
38
+ try {
39
+ const session = await instance.startSession({ cwd: process.cwd() });
40
+ const events = [];
41
+ for await (const event of session.sendTurn({ prompt: "hello opencode" })) {
42
+ events.push(event);
43
+ }
44
+ const deltas = events.filter((event) => event.type === "content.delta");
45
+ assert.ok(deltas.some((event) => event.stream === "assistant_text" && event.text.includes("hello opencode")));
46
+ assert.ok(deltas.some((event) => event.stream === "reasoning_text"));
47
+ const toolItem = events.find((event) => event.type === "item.completed");
48
+ assert.equal(toolItem?.itemType, "command_execution");
49
+ const completed = events.find((event) => event.type === "turn.completed");
50
+ assert.equal(completed?.endReason, "completed");
51
+ assert.equal(completed?.usage?.outputTokens, 2);
52
+ assert.ok(events.every((event) => event.kind === "opencode"));
53
+ await session.stop();
54
+ }
55
+ finally {
56
+ await instance.dispose();
57
+ }
58
+ });
59
+ test("opencode driver forwards an opaque effort as the SDK variant", async () => {
60
+ let observed;
61
+ const effortDriver = createOpencodeDriver({
62
+ backendFactory: async () => ({
63
+ ...fakeBackend(),
64
+ prompt: async (input) => {
65
+ observed = input.reasoning;
66
+ return { parts: [] };
67
+ }
68
+ })
69
+ });
70
+ const instance = await effortDriver.createInstance(effortDriver.configSchema.parse(config()));
71
+ try {
72
+ const session = await instance.startSession({
73
+ cwd: process.cwd(),
74
+ reasoning: { mode: "effort", effort: "deep" }
75
+ });
76
+ for await (const _event of session.sendTurn({ prompt: "hello" })) {
77
+ // Drain.
78
+ }
79
+ assert.deepEqual(observed, { mode: "effort", effort: "deep" });
80
+ }
81
+ finally {
82
+ await instance.dispose();
83
+ }
84
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,79 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { opencodeConfig, opencodeModelArg, opencodeTool } from "../index.js";
4
+ test("opencodeConfig serializes neutral models and profiles", () => {
5
+ const config = opencodeConfig({
6
+ gatewayUrl: "http://127.0.0.1:9999",
7
+ defaultModel: "primary",
8
+ models: [
9
+ {
10
+ id: "primary",
11
+ aliases: ["primary-alias"],
12
+ reasoning: {
13
+ status: "supported",
14
+ efforts: [{ id: "quick" }, { id: "deep" }],
15
+ provenance: "provider"
16
+ }
17
+ },
18
+ { id: "secondary", label: "Secondary" }
19
+ ],
20
+ agentProfiles: [
21
+ {
22
+ id: "reviewer",
23
+ model: "secondary",
24
+ description: "Review changes.",
25
+ instructions: "Return concise findings."
26
+ }
27
+ ],
28
+ auth: { token: "gateway-token" },
29
+ args: []
30
+ });
31
+ const provider = config.provider;
32
+ const entry = provider.routekit;
33
+ assert.ok(entry);
34
+ assert.deepEqual(entry.options, {
35
+ baseURL: "http://127.0.0.1:9999/v1",
36
+ apiKey: "gateway-token"
37
+ });
38
+ assert.deepEqual(entry.models, {
39
+ primary: {
40
+ name: "primary",
41
+ variants: {
42
+ quick: { reasoningEffort: "quick" },
43
+ deep: { reasoningEffort: "deep" }
44
+ }
45
+ },
46
+ "primary-alias": {
47
+ name: "primary-alias",
48
+ variants: {
49
+ quick: { reasoningEffort: "quick" },
50
+ deep: { reasoningEffort: "deep" }
51
+ }
52
+ },
53
+ secondary: { name: "Secondary" }
54
+ });
55
+ assert.deepEqual(config.agent, {
56
+ reviewer: {
57
+ mode: "subagent",
58
+ model: "routekit/secondary",
59
+ description: "Review changes.",
60
+ prompt: "Return concise findings."
61
+ }
62
+ });
63
+ });
64
+ test("opencodeModelArg namespaces opaque model ids", () => {
65
+ assert.equal(opencodeModelArg("opaque-endpoint"), "routekit/opaque-endpoint");
66
+ });
67
+ test("OpenCode driver registration carries the gateway route", () => {
68
+ assert.deepEqual(opencodeTool.driver.configForRoute({
69
+ gatewayUrl: "http://127.0.0.1:9999",
70
+ model: "opaque-endpoint",
71
+ authToken: "gateway-token"
72
+ }), {
73
+ command: "opencode",
74
+ gatewayUrl: "http://127.0.0.1:9999",
75
+ model: "opaque-endpoint",
76
+ providerId: "routekit",
77
+ authToken: "gateway-token"
78
+ });
79
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@velum-labs/routekit-tool-opencode",
3
+ "private": false,
4
+ "version": "0.9.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/velum-labs/handoffkit.git",
8
+ "directory": "packages/tool-opencode"
9
+ },
10
+ "description": "Product-neutral OpenCode launcher, serializer, and canonical harness driver.",
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "LICENSE"
22
+ ],
23
+ "publishConfig": {
24
+ "registry": "https://registry.npmjs.org",
25
+ "access": "public",
26
+ "provenance": true
27
+ },
28
+ "dependencies": {
29
+ "@opencode-ai/sdk": "1.17.13",
30
+ "zod": "4.4.3",
31
+ "@velum-labs/routekit-runtime": "0.9.0",
32
+ "@velum-labs/routekit-tools": "0.9.0",
33
+ "@velum-labs/routekit-harness-core": "0.9.0"
34
+ },
35
+ "keywords": [
36
+ "llm",
37
+ "coding-agent",
38
+ "opencode",
39
+ "harness",
40
+ "adapter"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsc -b",
44
+ "clean": "tsc -b --clean",
45
+ "test": "node --test \"dist/test/*.test.js\""
46
+ }
47
+ }