@ai-sdk/harness-opencode 0.0.0-d3900c59-20260626174016
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/CHANGELOG.md +53 -0
- package/LICENSE +13 -0
- package/README.md +6 -0
- package/dist/bridge/host-tool-mcp.mjs +103 -0
- package/dist/bridge/host-tool-mcp.mjs.map +1 -0
- package/dist/bridge/index.mjs +1984 -0
- package/dist/bridge/index.mjs.map +1 -0
- package/dist/bridge/package.json +13 -0
- package/dist/bridge/pnpm-lock.yaml +933 -0
- package/dist/index.d.ts +175 -0
- package/dist/index.js +1051 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
- package/src/bridge/host-tool-mcp.ts +136 -0
- package/src/bridge/index.ts +1846 -0
- package/src/bridge/opencode-events.ts +88 -0
- package/src/bridge/opencode-path.ts +17 -0
- package/src/bridge/opencode-usage.ts +156 -0
- package/src/bridge/package.json +13 -0
- package/src/bridge/pnpm-lock.yaml +933 -0
- package/src/index.ts +11 -0
- package/src/opencode-auth.ts +175 -0
- package/src/opencode-bridge-protocol.ts +29 -0
- package/src/opencode-harness.ts +1103 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
// src/opencode-harness.ts
|
|
2
|
+
import { randomBytes } from "crypto";
|
|
3
|
+
import { readFile } from "fs/promises";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
import {
|
|
7
|
+
commonTool,
|
|
8
|
+
HarnessCapabilityUnsupportedError,
|
|
9
|
+
harnessV1DiagnosticFromBridgeFrame
|
|
10
|
+
} from "@ai-sdk/harness";
|
|
11
|
+
import {
|
|
12
|
+
classifyDiskLog,
|
|
13
|
+
markBridgeStarting,
|
|
14
|
+
SandboxChannel,
|
|
15
|
+
waitForBridgeReady
|
|
16
|
+
} from "@ai-sdk/harness/utils";
|
|
17
|
+
import {
|
|
18
|
+
tool
|
|
19
|
+
} from "@ai-sdk/provider-utils";
|
|
20
|
+
import { WebSocket } from "ws";
|
|
21
|
+
import { z as z2 } from "zod/v4";
|
|
22
|
+
|
|
23
|
+
// src/opencode-auth.ts
|
|
24
|
+
import { getAiGatewayAuthFromEnv } from "@ai-sdk/harness/utils";
|
|
25
|
+
function resolveOpenCodeProvider({
|
|
26
|
+
model,
|
|
27
|
+
provider
|
|
28
|
+
}) {
|
|
29
|
+
if (provider === "anthropic" || provider === "openai") {
|
|
30
|
+
return provider;
|
|
31
|
+
}
|
|
32
|
+
if (model?.includes("/")) {
|
|
33
|
+
const [modelProvider] = model.split("/");
|
|
34
|
+
if (modelProvider === "anthropic" || modelProvider === "openai") {
|
|
35
|
+
return modelProvider;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return "anthropic";
|
|
39
|
+
}
|
|
40
|
+
function splitOpenCodeModel(model, provider) {
|
|
41
|
+
if (!model) return {};
|
|
42
|
+
if (model.includes("/")) {
|
|
43
|
+
const [providerID, ...rest] = model.split("/");
|
|
44
|
+
return {
|
|
45
|
+
providerID,
|
|
46
|
+
modelID: rest.join("/"),
|
|
47
|
+
model
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
providerID: provider,
|
|
52
|
+
modelID: model,
|
|
53
|
+
model: provider ? `${provider}/${model}` : model
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function resolveOpenCodeEnv({
|
|
57
|
+
auth,
|
|
58
|
+
model,
|
|
59
|
+
provider,
|
|
60
|
+
processEnv = process.env
|
|
61
|
+
}) {
|
|
62
|
+
const selectedProvider = resolveOpenCodeProvider({ model, provider });
|
|
63
|
+
if (auth?.openaiCompatible) {
|
|
64
|
+
return pickOpenAICompatible(auth.openaiCompatible, processEnv);
|
|
65
|
+
}
|
|
66
|
+
if (selectedProvider === "openai") {
|
|
67
|
+
if (auth?.openai) {
|
|
68
|
+
return pickOpenAI({ explicit: auth.openai, processEnv });
|
|
69
|
+
}
|
|
70
|
+
} else if (auth?.anthropic) {
|
|
71
|
+
return pickAnthropic({ explicit: auth.anthropic, processEnv });
|
|
72
|
+
}
|
|
73
|
+
const gatewayAuthFromEnv = getAiGatewayAuthFromEnv({ env: processEnv });
|
|
74
|
+
if (auth?.gateway) {
|
|
75
|
+
return pickGateway({ explicit: auth.gateway, gatewayAuthFromEnv });
|
|
76
|
+
}
|
|
77
|
+
if (gatewayAuthFromEnv.apiKey) {
|
|
78
|
+
return pickGateway({ explicit: {}, gatewayAuthFromEnv });
|
|
79
|
+
}
|
|
80
|
+
return selectedProvider === "openai" ? pickOpenAI({ processEnv }) : pickAnthropic({ processEnv });
|
|
81
|
+
}
|
|
82
|
+
function pickOpenAICompatible(explicit, processEnv) {
|
|
83
|
+
const env = {};
|
|
84
|
+
const apiKey = explicit.apiKey ?? processEnv.OPENAI_API_KEY;
|
|
85
|
+
if (apiKey) env.OPENAI_API_KEY = apiKey;
|
|
86
|
+
const baseUrl = explicit.baseUrl ?? processEnv.OPENAI_BASE_URL;
|
|
87
|
+
if (baseUrl) env.OPENAI_BASE_URL = baseUrl;
|
|
88
|
+
const name = explicit.name ?? processEnv.OPENAI_NAME;
|
|
89
|
+
if (name) env.OPENAI_NAME = name;
|
|
90
|
+
if (explicit.queryParams && Object.keys(explicit.queryParams).length > 0) {
|
|
91
|
+
env.OPENAI_QUERY_PARAMS_JSON = JSON.stringify(explicit.queryParams);
|
|
92
|
+
} else if (processEnv.OPENAI_QUERY_PARAMS_JSON) {
|
|
93
|
+
env.OPENAI_QUERY_PARAMS_JSON = processEnv.OPENAI_QUERY_PARAMS_JSON;
|
|
94
|
+
}
|
|
95
|
+
return env;
|
|
96
|
+
}
|
|
97
|
+
function pickOpenAI({
|
|
98
|
+
explicit,
|
|
99
|
+
processEnv
|
|
100
|
+
}) {
|
|
101
|
+
const env = {};
|
|
102
|
+
const apiKey = explicit?.apiKey ?? processEnv.OPENAI_API_KEY;
|
|
103
|
+
if (apiKey) env.OPENAI_API_KEY = apiKey;
|
|
104
|
+
const baseUrl = explicit?.baseUrl ?? processEnv.OPENAI_BASE_URL;
|
|
105
|
+
if (baseUrl) env.OPENAI_BASE_URL = baseUrl;
|
|
106
|
+
const organization = explicit?.organization ?? processEnv.OPENAI_ORGANIZATION;
|
|
107
|
+
if (organization) env.OPENAI_ORGANIZATION = organization;
|
|
108
|
+
const project = explicit?.project ?? processEnv.OPENAI_PROJECT;
|
|
109
|
+
if (project) env.OPENAI_PROJECT = project;
|
|
110
|
+
return env;
|
|
111
|
+
}
|
|
112
|
+
function pickAnthropic({
|
|
113
|
+
explicit,
|
|
114
|
+
processEnv
|
|
115
|
+
}) {
|
|
116
|
+
const env = {};
|
|
117
|
+
const apiKey = explicit?.apiKey ?? processEnv.ANTHROPIC_API_KEY;
|
|
118
|
+
if (apiKey) env.ANTHROPIC_API_KEY = apiKey;
|
|
119
|
+
const authToken = explicit?.authToken ?? processEnv.ANTHROPIC_AUTH_TOKEN;
|
|
120
|
+
if (authToken) env.ANTHROPIC_AUTH_TOKEN = authToken;
|
|
121
|
+
const baseUrl = explicit?.baseUrl ?? processEnv.ANTHROPIC_BASE_URL;
|
|
122
|
+
if (baseUrl) env.ANTHROPIC_BASE_URL = baseUrl;
|
|
123
|
+
return env;
|
|
124
|
+
}
|
|
125
|
+
function pickGateway({
|
|
126
|
+
explicit,
|
|
127
|
+
gatewayAuthFromEnv
|
|
128
|
+
}) {
|
|
129
|
+
const env = {};
|
|
130
|
+
const apiKey = explicit.apiKey ?? gatewayAuthFromEnv.apiKey;
|
|
131
|
+
if (apiKey) env.AI_GATEWAY_API_KEY = apiKey;
|
|
132
|
+
env.AI_GATEWAY_BASE_URL = toOpenCodeGatewayBaseUrl(
|
|
133
|
+
explicit.baseUrl ?? gatewayAuthFromEnv.baseUrl
|
|
134
|
+
);
|
|
135
|
+
return env;
|
|
136
|
+
}
|
|
137
|
+
function toOpenCodeGatewayBaseUrl(baseUrl) {
|
|
138
|
+
const trimmed = baseUrl.replace(/\/+$/, "");
|
|
139
|
+
return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/opencode-bridge-protocol.ts
|
|
143
|
+
import {
|
|
144
|
+
harnessV1BridgeInboundCommandSchemas,
|
|
145
|
+
harnessV1BridgeOutboundMessageSchema,
|
|
146
|
+
harnessV1BridgeReadySchema,
|
|
147
|
+
harnessV1BridgeStartBaseSchema
|
|
148
|
+
} from "@ai-sdk/harness";
|
|
149
|
+
import { z } from "zod/v4";
|
|
150
|
+
var outboundMessageSchema = harnessV1BridgeOutboundMessageSchema;
|
|
151
|
+
var startMessageSchema = harnessV1BridgeStartBaseSchema.extend({
|
|
152
|
+
operation: z.enum(["prompt", "compact"]).optional(),
|
|
153
|
+
provider: z.string().optional(),
|
|
154
|
+
variant: z.string().optional(),
|
|
155
|
+
instructions: z.string().optional(),
|
|
156
|
+
resumeSessionId: z.string().optional()
|
|
157
|
+
});
|
|
158
|
+
var inboundMessageSchema = z.discriminatedUnion("type", [
|
|
159
|
+
startMessageSchema,
|
|
160
|
+
...harnessV1BridgeInboundCommandSchemas
|
|
161
|
+
]);
|
|
162
|
+
|
|
163
|
+
// src/opencode-harness.ts
|
|
164
|
+
var optionalStringRecord = z2.record(z2.string(), z2.unknown()).optional();
|
|
165
|
+
var OPENCODE_BUILTIN_TOOLS = {
|
|
166
|
+
read: commonTool("read", {
|
|
167
|
+
nativeName: "view",
|
|
168
|
+
toolUseKind: "readonly",
|
|
169
|
+
description: "Read file contents",
|
|
170
|
+
inputSchema: z2.object({
|
|
171
|
+
file_path: z2.string().optional(),
|
|
172
|
+
path: z2.string().optional()
|
|
173
|
+
}).passthrough()
|
|
174
|
+
}),
|
|
175
|
+
write: commonTool("write", {
|
|
176
|
+
nativeName: "write",
|
|
177
|
+
toolUseKind: "edit",
|
|
178
|
+
description: "Write content to a file",
|
|
179
|
+
inputSchema: z2.object({
|
|
180
|
+
file_path: z2.string().optional(),
|
|
181
|
+
path: z2.string().optional(),
|
|
182
|
+
content: z2.string().optional()
|
|
183
|
+
}).passthrough()
|
|
184
|
+
}),
|
|
185
|
+
edit: commonTool("edit", {
|
|
186
|
+
nativeName: "edit",
|
|
187
|
+
toolUseKind: "edit",
|
|
188
|
+
description: "Edit a file by replacing text",
|
|
189
|
+
inputSchema: z2.object({
|
|
190
|
+
file_path: z2.string().optional(),
|
|
191
|
+
path: z2.string().optional(),
|
|
192
|
+
old_string: z2.string().optional(),
|
|
193
|
+
new_string: z2.string().optional()
|
|
194
|
+
}).passthrough()
|
|
195
|
+
}),
|
|
196
|
+
bash: commonTool("bash", {
|
|
197
|
+
nativeName: "bash",
|
|
198
|
+
toolUseKind: "bash",
|
|
199
|
+
description: "Execute a shell command",
|
|
200
|
+
inputSchema: z2.object({
|
|
201
|
+
command: z2.string().optional()
|
|
202
|
+
}).passthrough()
|
|
203
|
+
}),
|
|
204
|
+
glob: commonTool("glob", {
|
|
205
|
+
nativeName: "glob",
|
|
206
|
+
toolUseKind: "readonly",
|
|
207
|
+
description: "Find files matching a glob pattern",
|
|
208
|
+
inputSchema: z2.object({
|
|
209
|
+
pattern: z2.string().optional(),
|
|
210
|
+
path: z2.string().optional()
|
|
211
|
+
}).passthrough()
|
|
212
|
+
}),
|
|
213
|
+
grep: commonTool("grep", {
|
|
214
|
+
nativeName: "grep",
|
|
215
|
+
toolUseKind: "readonly",
|
|
216
|
+
description: "Search file contents with regex",
|
|
217
|
+
inputSchema: z2.object({
|
|
218
|
+
pattern: z2.string().optional(),
|
|
219
|
+
path: z2.string().optional()
|
|
220
|
+
}).passthrough()
|
|
221
|
+
}),
|
|
222
|
+
ls: tool({
|
|
223
|
+
description: "List directory contents",
|
|
224
|
+
inputSchema: z2.object({
|
|
225
|
+
path: z2.string().optional()
|
|
226
|
+
}).passthrough()
|
|
227
|
+
}),
|
|
228
|
+
webfetch: tool({
|
|
229
|
+
description: "Fetch a URL",
|
|
230
|
+
inputSchema: z2.object({
|
|
231
|
+
url: z2.string().optional(),
|
|
232
|
+
prompt: z2.string().optional()
|
|
233
|
+
}).passthrough()
|
|
234
|
+
}),
|
|
235
|
+
skill: tool({
|
|
236
|
+
description: "Load an OpenCode skill by name",
|
|
237
|
+
inputSchema: z2.object({
|
|
238
|
+
name: z2.string().optional()
|
|
239
|
+
}).passthrough()
|
|
240
|
+
}),
|
|
241
|
+
todowrite: tool({
|
|
242
|
+
description: "Replace the OpenCode session todo list",
|
|
243
|
+
inputSchema: z2.object({
|
|
244
|
+
todos: z2.array(
|
|
245
|
+
z2.object({
|
|
246
|
+
content: z2.string().optional(),
|
|
247
|
+
status: z2.string().optional(),
|
|
248
|
+
priority: z2.string().optional()
|
|
249
|
+
}).passthrough()
|
|
250
|
+
).optional()
|
|
251
|
+
}).passthrough()
|
|
252
|
+
}),
|
|
253
|
+
agent: tool({
|
|
254
|
+
description: "Run an OpenCode subagent",
|
|
255
|
+
inputSchema: z2.object({
|
|
256
|
+
agent: z2.string().optional(),
|
|
257
|
+
prompt: z2.string().optional(),
|
|
258
|
+
description: z2.string().optional(),
|
|
259
|
+
metadata: optionalStringRecord
|
|
260
|
+
}).passthrough()
|
|
261
|
+
})
|
|
262
|
+
};
|
|
263
|
+
var BOOTSTRAP_DIR = "/tmp/harness/opencode";
|
|
264
|
+
var openCodeBridgeCoordsSchema = z2.object({
|
|
265
|
+
port: z2.number(),
|
|
266
|
+
token: z2.string(),
|
|
267
|
+
lastSeenEventId: z2.number(),
|
|
268
|
+
sandboxId: z2.string().optional()
|
|
269
|
+
});
|
|
270
|
+
var openCodeResumeStateSchema = z2.object({
|
|
271
|
+
openCodeSessionId: z2.string().optional(),
|
|
272
|
+
bridge: openCodeBridgeCoordsSchema.optional()
|
|
273
|
+
});
|
|
274
|
+
function createOpenCode(settings = {}) {
|
|
275
|
+
let cachedBootstrap;
|
|
276
|
+
return {
|
|
277
|
+
specificationVersion: "harness-v1",
|
|
278
|
+
harnessId: "opencode",
|
|
279
|
+
builtinTools: OPENCODE_BUILTIN_TOOLS,
|
|
280
|
+
supportsBuiltinToolApprovals: true,
|
|
281
|
+
lifecycleStateSchema: openCodeResumeStateSchema,
|
|
282
|
+
getBootstrap: async () => {
|
|
283
|
+
if (cachedBootstrap != null) return cachedBootstrap;
|
|
284
|
+
const [pkg, lock, bridge, hostToolMcp] = await Promise.all([
|
|
285
|
+
readBridgeAsset("package.json"),
|
|
286
|
+
readBridgeAsset("pnpm-lock.yaml"),
|
|
287
|
+
readBridgeAsset("index.mjs"),
|
|
288
|
+
readBridgeAsset("host-tool-mcp.mjs")
|
|
289
|
+
]);
|
|
290
|
+
cachedBootstrap = {
|
|
291
|
+
harnessId: "opencode",
|
|
292
|
+
bootstrapDir: BOOTSTRAP_DIR,
|
|
293
|
+
files: [
|
|
294
|
+
{ path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
|
|
295
|
+
{ path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
|
|
296
|
+
{ path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge },
|
|
297
|
+
{
|
|
298
|
+
path: `${BOOTSTRAP_DIR}/host-tool-mcp.mjs`,
|
|
299
|
+
content: hostToolMcp
|
|
300
|
+
}
|
|
301
|
+
],
|
|
302
|
+
commands: [
|
|
303
|
+
{ command: `mkdir -p ${BOOTSTRAP_DIR}` },
|
|
304
|
+
{
|
|
305
|
+
command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
command: `cd ${BOOTSTRAP_DIR} && node node_modules/opencode-ai/postinstall.mjs && ./node_modules/.bin/opencode --version`
|
|
309
|
+
}
|
|
310
|
+
]
|
|
311
|
+
};
|
|
312
|
+
return cachedBootstrap;
|
|
313
|
+
},
|
|
314
|
+
doStart: async (startOpts) => {
|
|
315
|
+
const sandboxSession = startOpts.sandboxSession;
|
|
316
|
+
const session = sandboxSession.restricted();
|
|
317
|
+
const sandboxId = sandboxSession.id;
|
|
318
|
+
const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
|
|
319
|
+
const isResume = lifecycleState != null;
|
|
320
|
+
const isContinue = startOpts.continueFrom != null;
|
|
321
|
+
const resumeData = isResume && typeof lifecycleState?.data === "object" ? lifecycleState.data : void 0;
|
|
322
|
+
const resumeSessionId = typeof resumeData?.openCodeSessionId === "string" && resumeData.openCodeSessionId.length > 0 ? resumeData.openCodeSessionId : void 0;
|
|
323
|
+
const coords = resumeData?.bridge;
|
|
324
|
+
const workDir = startOpts.sessionWorkDir;
|
|
325
|
+
const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
|
|
326
|
+
const bridgeStateDir = `${sessionDataDir}/bridge`;
|
|
327
|
+
const timeoutMs = settings.startupTimeoutMs ?? 12e4;
|
|
328
|
+
const model = splitOpenCodeModel(settings.model, settings.provider).model;
|
|
329
|
+
const report = startOpts.observability?.report;
|
|
330
|
+
const onDiagnostic = report ? (frame) => report(
|
|
331
|
+
harnessV1DiagnosticFromBridgeFrame(frame, {
|
|
332
|
+
sessionId: startOpts.sessionId,
|
|
333
|
+
timestamp: Date.now()
|
|
334
|
+
})
|
|
335
|
+
) : void 0;
|
|
336
|
+
if (coords) {
|
|
337
|
+
try {
|
|
338
|
+
const attachUrl = await sandboxSession.getPortUrl({
|
|
339
|
+
port: coords.port,
|
|
340
|
+
protocol: "ws"
|
|
341
|
+
}) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
|
|
342
|
+
const attachChannel = new SandboxChannel({
|
|
343
|
+
connect: () => openWebSocket(attachUrl),
|
|
344
|
+
outboundSchema: outboundMessageSchema,
|
|
345
|
+
initialLastSeenEventId: coords.lastSeenEventId,
|
|
346
|
+
onDiagnostic
|
|
347
|
+
});
|
|
348
|
+
await attachChannel.open(isContinue ? { resume: true } : void 0);
|
|
349
|
+
return createSession({
|
|
350
|
+
sessionId: startOpts.sessionId,
|
|
351
|
+
channel: attachChannel,
|
|
352
|
+
proc: void 0,
|
|
353
|
+
model,
|
|
354
|
+
provider: settings.provider,
|
|
355
|
+
reasoningVariant: settings.reasoningVariant,
|
|
356
|
+
openCodeSessionId: resumeSessionId,
|
|
357
|
+
isResume: true,
|
|
358
|
+
seedResumeSessionOnFirstPrompt: false,
|
|
359
|
+
rerunContinue: false,
|
|
360
|
+
bridgePort: coords.port,
|
|
361
|
+
bridgeToken: coords.token,
|
|
362
|
+
sandboxId,
|
|
363
|
+
debug: startOpts.observability?.debug,
|
|
364
|
+
permissionMode: startOpts.permissionMode
|
|
365
|
+
});
|
|
366
|
+
} catch {
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
let respawnStrategy = isResume ? "rerun" : void 0;
|
|
370
|
+
if (coords && isContinue) {
|
|
371
|
+
const logRaw = await Promise.resolve(
|
|
372
|
+
session.readTextFile({
|
|
373
|
+
path: `${bridgeStateDir}/event-log.ndjson`,
|
|
374
|
+
abortSignal: startOpts.abortSignal
|
|
375
|
+
})
|
|
376
|
+
).catch(() => null);
|
|
377
|
+
if (await classifyDiskLog(logRaw) === "replay") {
|
|
378
|
+
respawnStrategy = "replay";
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const port = resolveBridgePort(sandboxSession, settings.port);
|
|
382
|
+
const token = randomBytes(32).toString("hex");
|
|
383
|
+
const sandboxHomeDir = await resolveSandboxHomeDir({
|
|
384
|
+
sandbox: session,
|
|
385
|
+
abortSignal: startOpts.abortSignal
|
|
386
|
+
});
|
|
387
|
+
const xdgConfigHome = `${sandboxHomeDir}/.config`;
|
|
388
|
+
const xdgCacheHome = `${sandboxHomeDir}/.cache`;
|
|
389
|
+
const xdgDataHome = `${sandboxHomeDir}/.local/share`;
|
|
390
|
+
const xdgStateHome = `${sandboxHomeDir}/.local/state`;
|
|
391
|
+
const skillSetup = startOpts.skills && startOpts.skills.length > 0 ? await writeSkills({
|
|
392
|
+
sandbox: session,
|
|
393
|
+
skills: startOpts.skills,
|
|
394
|
+
homeDir: sandboxHomeDir,
|
|
395
|
+
abortSignal: startOpts.abortSignal
|
|
396
|
+
}) : void 0;
|
|
397
|
+
const env = {
|
|
398
|
+
...resolveOpenCodeEnv({
|
|
399
|
+
auth: settings.auth,
|
|
400
|
+
model: settings.model,
|
|
401
|
+
provider: settings.provider
|
|
402
|
+
}),
|
|
403
|
+
BRIDGE_CHANNEL_TOKEN: token,
|
|
404
|
+
BRIDGE_WS_PORT: String(port),
|
|
405
|
+
HOME: sandboxHomeDir,
|
|
406
|
+
USERPROFILE: sandboxHomeDir,
|
|
407
|
+
XDG_CONFIG_HOME: xdgConfigHome,
|
|
408
|
+
XDG_CACHE_HOME: xdgCacheHome,
|
|
409
|
+
XDG_DATA_HOME: xdgDataHome,
|
|
410
|
+
XDG_STATE_HOME: xdgStateHome,
|
|
411
|
+
...respawnStrategy === "replay" ? { BRIDGE_REPLAY_FROM_DISK: "1" } : {}
|
|
412
|
+
};
|
|
413
|
+
if (respawnStrategy === void 0) {
|
|
414
|
+
await session.run({
|
|
415
|
+
command: `mkdir -p ${shellQuote(workDir)} ${shellQuote(bridgeStateDir)} ${shellQuote(xdgConfigHome)} ${shellQuote(xdgCacheHome)} ${shellQuote(xdgDataHome)} ${shellQuote(xdgStateHome)}`,
|
|
416
|
+
abortSignal: startOpts.abortSignal
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
await markBridgeStarting({
|
|
420
|
+
sandbox: session,
|
|
421
|
+
bridgeStateDir,
|
|
422
|
+
bridgeType: "opencode",
|
|
423
|
+
abortSignal: startOpts.abortSignal
|
|
424
|
+
});
|
|
425
|
+
const proc = await session.spawn({
|
|
426
|
+
command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)} --bootstrap-dir ${shellQuote(BOOTSTRAP_DIR)}${skillSetup ? ` --skills-dir ${shellQuote(skillSetup.skillsDir)}` : ""}`,
|
|
427
|
+
env,
|
|
428
|
+
abortSignal: startOpts.abortSignal
|
|
429
|
+
});
|
|
430
|
+
const { port: boundPort } = await waitForBridgeReady({
|
|
431
|
+
proc,
|
|
432
|
+
sandbox: session,
|
|
433
|
+
bridgeStateDir,
|
|
434
|
+
bridgeType: "opencode",
|
|
435
|
+
timeoutMs,
|
|
436
|
+
abortSignal: startOpts.abortSignal,
|
|
437
|
+
createTimeoutError: () => new Error("opencode bridge did not become ready in time."),
|
|
438
|
+
createExitError: () => new Error("opencode bridge exited before becoming ready.")
|
|
439
|
+
});
|
|
440
|
+
void drainRest(proc.stdout);
|
|
441
|
+
void forwardBridgeStderr(proc.stderr);
|
|
442
|
+
const wsUrl = await sandboxSession.getPortUrl({
|
|
443
|
+
port: boundPort,
|
|
444
|
+
protocol: "ws"
|
|
445
|
+
}) + `?agent_bridge_token=${encodeURIComponent(token)}`;
|
|
446
|
+
const channel = new SandboxChannel({
|
|
447
|
+
connect: () => openWebSocket(wsUrl),
|
|
448
|
+
outboundSchema: outboundMessageSchema,
|
|
449
|
+
onDiagnostic,
|
|
450
|
+
...respawnStrategy === "replay" ? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 } : {}
|
|
451
|
+
});
|
|
452
|
+
await channel.open(
|
|
453
|
+
respawnStrategy === "replay" ? { resume: true } : void 0
|
|
454
|
+
);
|
|
455
|
+
return createSession({
|
|
456
|
+
sessionId: startOpts.sessionId,
|
|
457
|
+
channel,
|
|
458
|
+
proc,
|
|
459
|
+
model,
|
|
460
|
+
provider: settings.provider,
|
|
461
|
+
reasoningVariant: settings.reasoningVariant,
|
|
462
|
+
openCodeSessionId: resumeSessionId,
|
|
463
|
+
isResume: respawnStrategy !== void 0,
|
|
464
|
+
seedResumeSessionOnFirstPrompt: respawnStrategy !== void 0,
|
|
465
|
+
rerunContinue: respawnStrategy === "rerun",
|
|
466
|
+
bridgePort: boundPort,
|
|
467
|
+
bridgeToken: token,
|
|
468
|
+
sandboxId,
|
|
469
|
+
debug: startOpts.observability?.debug,
|
|
470
|
+
permissionMode: startOpts.permissionMode
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
function resolveBridgePort(sandboxSession, override) {
|
|
476
|
+
if (override !== void 0) return override;
|
|
477
|
+
if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
|
|
478
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
479
|
+
harnessId: "opencode",
|
|
480
|
+
message: "The opencode harness needs a TCP port exposed by the sandbox. Create the sandbox with `ports: [<port>]` or pass `createOpenCode({ port })`."
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
async function readBridgeAsset(name) {
|
|
484
|
+
const candidates = [
|
|
485
|
+
new URL(`./bridge/${name}`, import.meta.url),
|
|
486
|
+
new URL(`../bridge/${name}`, import.meta.url)
|
|
487
|
+
];
|
|
488
|
+
let lastErr;
|
|
489
|
+
for (const url of candidates) {
|
|
490
|
+
try {
|
|
491
|
+
return await readFile(fileURLToPath(url), "utf8");
|
|
492
|
+
} catch (err) {
|
|
493
|
+
const code = err.code;
|
|
494
|
+
if (code !== "ENOENT") throw err;
|
|
495
|
+
lastErr = err;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
throw lastErr ?? new Error(`bridge asset not found: ${name}`);
|
|
499
|
+
}
|
|
500
|
+
async function writeSkills({
|
|
501
|
+
sandbox,
|
|
502
|
+
skills,
|
|
503
|
+
homeDir,
|
|
504
|
+
abortSignal
|
|
505
|
+
}) {
|
|
506
|
+
for (const skill of skills) {
|
|
507
|
+
safeOpenCodeSkillName(skill.name);
|
|
508
|
+
for (const file of skill.files ?? []) {
|
|
509
|
+
safeOpenCodeSkillFilePath({ skillName: skill.name, filePath: file.path });
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const skillsDir = path.posix.join(homeDir, ".agents", "skills");
|
|
513
|
+
await sandbox.run({
|
|
514
|
+
command: `mkdir -p ${shellQuote(skillsDir)}`,
|
|
515
|
+
abortSignal
|
|
516
|
+
});
|
|
517
|
+
for (const skill of skills) {
|
|
518
|
+
const name = safeOpenCodeSkillName(skill.name);
|
|
519
|
+
const skillDir = path.posix.join(skillsDir, name);
|
|
520
|
+
const content = `---
|
|
521
|
+
name: ${skill.name}
|
|
522
|
+
description: ${skill.description}
|
|
523
|
+
---
|
|
524
|
+
|
|
525
|
+
${skill.content}`;
|
|
526
|
+
await sandbox.writeTextFile({
|
|
527
|
+
path: path.posix.join(skillDir, "SKILL.md"),
|
|
528
|
+
content,
|
|
529
|
+
abortSignal
|
|
530
|
+
});
|
|
531
|
+
for (const file of skill.files ?? []) {
|
|
532
|
+
const filePath = safeOpenCodeSkillFilePath({
|
|
533
|
+
skillName: skill.name,
|
|
534
|
+
filePath: file.path
|
|
535
|
+
});
|
|
536
|
+
await sandbox.writeTextFile({
|
|
537
|
+
path: path.posix.join(skillDir, filePath),
|
|
538
|
+
content: file.content,
|
|
539
|
+
abortSignal
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return { skillsDir };
|
|
544
|
+
}
|
|
545
|
+
async function resolveSandboxHomeDir({
|
|
546
|
+
sandbox,
|
|
547
|
+
abortSignal
|
|
548
|
+
}) {
|
|
549
|
+
const result = await sandbox.run({
|
|
550
|
+
command: 'printf "%s" "$HOME"',
|
|
551
|
+
abortSignal
|
|
552
|
+
});
|
|
553
|
+
const homeDir = result.stdout.trim();
|
|
554
|
+
if (result.exitCode !== 0 || !homeDir || !path.posix.isAbsolute(homeDir)) {
|
|
555
|
+
throw new Error(
|
|
556
|
+
`Unable to resolve sandbox HOME directory: ${result.stderr || result.stdout}`
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
return homeDir;
|
|
560
|
+
}
|
|
561
|
+
function safeOpenCodeSkillName(name) {
|
|
562
|
+
if (!/^[A-Za-z0-9._-]+$/.test(name) || name === "." || name === "..") {
|
|
563
|
+
throw new Error(`Invalid OpenCode skill name: ${name}`);
|
|
564
|
+
}
|
|
565
|
+
return name;
|
|
566
|
+
}
|
|
567
|
+
function safeOpenCodeSkillFilePath({
|
|
568
|
+
skillName,
|
|
569
|
+
filePath
|
|
570
|
+
}) {
|
|
571
|
+
const normalized = path.posix.normalize(filePath);
|
|
572
|
+
if (normalized === "." || normalized.startsWith("../") || path.posix.isAbsolute(normalized)) {
|
|
573
|
+
throw new Error(
|
|
574
|
+
`Invalid OpenCode skill file path for ${skillName}: ${filePath}`
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
return normalized;
|
|
578
|
+
}
|
|
579
|
+
function shellQuote(value) {
|
|
580
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
581
|
+
}
|
|
582
|
+
async function forwardBridgeStderr(stream) {
|
|
583
|
+
try {
|
|
584
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
|
|
585
|
+
while (true) {
|
|
586
|
+
const { value, done } = await reader.read();
|
|
587
|
+
if (done) return;
|
|
588
|
+
if (value) {
|
|
589
|
+
const trimmed = value.endsWith("\n") ? value.slice(0, -1) : value;
|
|
590
|
+
if (trimmed.length > 0) {
|
|
591
|
+
console.log(`[bridge stderr] ${trimmed}`);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
} catch {
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
async function drainRest(stream) {
|
|
599
|
+
try {
|
|
600
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
|
|
601
|
+
while (true) {
|
|
602
|
+
const { done } = await reader.read();
|
|
603
|
+
if (done) return;
|
|
604
|
+
}
|
|
605
|
+
} catch {
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
function openWebSocket(url) {
|
|
609
|
+
return new Promise((resolve, reject) => {
|
|
610
|
+
const ws = new WebSocket(url);
|
|
611
|
+
const onOpen = () => {
|
|
612
|
+
ws.off("error", onError);
|
|
613
|
+
resolve(ws);
|
|
614
|
+
};
|
|
615
|
+
const onError = (err) => {
|
|
616
|
+
ws.off("open", onOpen);
|
|
617
|
+
reject(err);
|
|
618
|
+
};
|
|
619
|
+
ws.once("open", onOpen);
|
|
620
|
+
ws.once("error", onError);
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
function createSession({
|
|
624
|
+
sessionId,
|
|
625
|
+
channel,
|
|
626
|
+
proc,
|
|
627
|
+
model,
|
|
628
|
+
provider,
|
|
629
|
+
reasoningVariant,
|
|
630
|
+
openCodeSessionId,
|
|
631
|
+
isResume,
|
|
632
|
+
seedResumeSessionOnFirstPrompt,
|
|
633
|
+
rerunContinue,
|
|
634
|
+
bridgePort,
|
|
635
|
+
bridgeToken,
|
|
636
|
+
sandboxId,
|
|
637
|
+
debug,
|
|
638
|
+
permissionMode
|
|
639
|
+
}) {
|
|
640
|
+
let stopped = false;
|
|
641
|
+
let stopPromise;
|
|
642
|
+
let latestOpenCodeSessionId = openCodeSessionId;
|
|
643
|
+
let pendingResumeSessionId = seedResumeSessionOnFirstPrompt ? openCodeSessionId : void 0;
|
|
644
|
+
let instructionsApplied = isResume;
|
|
645
|
+
let activeTurn = false;
|
|
646
|
+
const pendingCompactionParts = [];
|
|
647
|
+
channel.on("bridge-thread", (msg) => {
|
|
648
|
+
latestOpenCodeSessionId = msg.threadId;
|
|
649
|
+
});
|
|
650
|
+
const wireTurn = (turnOpts) => {
|
|
651
|
+
activeTurn = true;
|
|
652
|
+
let pendingResolve;
|
|
653
|
+
let pendingReject;
|
|
654
|
+
const done = new Promise((resolve, reject) => {
|
|
655
|
+
pendingResolve = resolve;
|
|
656
|
+
pendingReject = reject;
|
|
657
|
+
});
|
|
658
|
+
const unsubs = [];
|
|
659
|
+
const forward = (event) => {
|
|
660
|
+
try {
|
|
661
|
+
turnOpts.emit(event);
|
|
662
|
+
} catch {
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
const eventTypes = [
|
|
666
|
+
"stream-start",
|
|
667
|
+
"text-start",
|
|
668
|
+
"text-delta",
|
|
669
|
+
"text-end",
|
|
670
|
+
"reasoning-start",
|
|
671
|
+
"reasoning-delta",
|
|
672
|
+
"reasoning-end",
|
|
673
|
+
"tool-call",
|
|
674
|
+
"tool-approval-request",
|
|
675
|
+
"tool-result",
|
|
676
|
+
"file-change",
|
|
677
|
+
"finish-step",
|
|
678
|
+
"compaction",
|
|
679
|
+
"raw"
|
|
680
|
+
];
|
|
681
|
+
let isSettled = false;
|
|
682
|
+
const settleSuccess = () => {
|
|
683
|
+
if (isSettled) return;
|
|
684
|
+
isSettled = true;
|
|
685
|
+
activeTurn = false;
|
|
686
|
+
for (const u of unsubs) u();
|
|
687
|
+
pendingResolve();
|
|
688
|
+
};
|
|
689
|
+
const settleError = (err) => {
|
|
690
|
+
if (isSettled) return;
|
|
691
|
+
isSettled = true;
|
|
692
|
+
activeTurn = false;
|
|
693
|
+
for (const u of unsubs) u();
|
|
694
|
+
pendingReject(err);
|
|
695
|
+
};
|
|
696
|
+
for (const type of eventTypes) {
|
|
697
|
+
unsubs.push(
|
|
698
|
+
channel.on(type, (msg) => {
|
|
699
|
+
forward(msg);
|
|
700
|
+
})
|
|
701
|
+
);
|
|
702
|
+
}
|
|
703
|
+
unsubs.push(
|
|
704
|
+
channel.on("finish", (msg) => {
|
|
705
|
+
forward(msg);
|
|
706
|
+
settleSuccess();
|
|
707
|
+
})
|
|
708
|
+
);
|
|
709
|
+
unsubs.push(
|
|
710
|
+
channel.on("error", (msg) => {
|
|
711
|
+
forward(msg);
|
|
712
|
+
settleError(msg.error);
|
|
713
|
+
})
|
|
714
|
+
);
|
|
715
|
+
const onClose = (_code, reason) => {
|
|
716
|
+
if (isSettled) return;
|
|
717
|
+
if (reason === "suspended") {
|
|
718
|
+
settleSuccess();
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
settleError(
|
|
722
|
+
new Error("opencode bridge closed before the turn finished.")
|
|
723
|
+
);
|
|
724
|
+
};
|
|
725
|
+
channel.onClose(onClose);
|
|
726
|
+
const onAbort = () => {
|
|
727
|
+
if (isSettled) return;
|
|
728
|
+
try {
|
|
729
|
+
channel.send({ type: "abort" });
|
|
730
|
+
} catch {
|
|
731
|
+
}
|
|
732
|
+
settleError(
|
|
733
|
+
turnOpts.abortSignal?.reason ?? new DOMException("Aborted", "AbortError")
|
|
734
|
+
);
|
|
735
|
+
};
|
|
736
|
+
if (turnOpts.abortSignal) {
|
|
737
|
+
if (turnOpts.abortSignal.aborted) {
|
|
738
|
+
onAbort();
|
|
739
|
+
} else {
|
|
740
|
+
turnOpts.abortSignal.addEventListener("abort", onAbort, {
|
|
741
|
+
once: true
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
while (pendingCompactionParts.length > 0) {
|
|
746
|
+
forward(pendingCompactionParts.shift());
|
|
747
|
+
}
|
|
748
|
+
return {
|
|
749
|
+
submitToolResult: async (input) => {
|
|
750
|
+
channel.send({
|
|
751
|
+
type: "tool-result",
|
|
752
|
+
toolCallId: input.toolCallId,
|
|
753
|
+
output: input.output,
|
|
754
|
+
isError: input.isError
|
|
755
|
+
});
|
|
756
|
+
},
|
|
757
|
+
submitToolApproval: async (input) => {
|
|
758
|
+
channel.send({
|
|
759
|
+
type: "tool-approval-response",
|
|
760
|
+
approvalId: input.approvalId,
|
|
761
|
+
approved: input.approved,
|
|
762
|
+
reason: input.reason
|
|
763
|
+
});
|
|
764
|
+
},
|
|
765
|
+
submitUserMessage: async (text) => {
|
|
766
|
+
channel.send({ type: "user-message", text });
|
|
767
|
+
},
|
|
768
|
+
done
|
|
769
|
+
};
|
|
770
|
+
};
|
|
771
|
+
const startBase = () => ({
|
|
772
|
+
model,
|
|
773
|
+
provider,
|
|
774
|
+
...reasoningVariant ? { variant: reasoningVariant } : {},
|
|
775
|
+
...permissionMode ? { permissionMode } : {},
|
|
776
|
+
...pendingResumeSessionId ? { resumeSessionId: pendingResumeSessionId } : latestOpenCodeSessionId ? { resumeSessionId: latestOpenCodeSessionId } : {},
|
|
777
|
+
...debug ? { debug } : {}
|
|
778
|
+
});
|
|
779
|
+
return {
|
|
780
|
+
sessionId,
|
|
781
|
+
isResume,
|
|
782
|
+
modelId: model,
|
|
783
|
+
doPromptTurn: async (promptOpts) => {
|
|
784
|
+
const control = wireTurn({
|
|
785
|
+
emit: promptOpts.emit,
|
|
786
|
+
abortSignal: promptOpts.abortSignal
|
|
787
|
+
});
|
|
788
|
+
const applyInstructions = !instructionsApplied && !!promptOpts.instructions;
|
|
789
|
+
instructionsApplied = true;
|
|
790
|
+
channel.send({
|
|
791
|
+
type: "start",
|
|
792
|
+
operation: "prompt",
|
|
793
|
+
prompt: extractUserText(promptOpts.prompt),
|
|
794
|
+
tools: (promptOpts.tools ?? []).map((t) => ({
|
|
795
|
+
name: t.name,
|
|
796
|
+
description: t.description,
|
|
797
|
+
inputSchema: t.inputSchema
|
|
798
|
+
})),
|
|
799
|
+
...applyInstructions ? { instructions: promptOpts.instructions } : {},
|
|
800
|
+
...startBase()
|
|
801
|
+
});
|
|
802
|
+
pendingResumeSessionId = void 0;
|
|
803
|
+
return control;
|
|
804
|
+
},
|
|
805
|
+
doContinueTurn: async (continueOpts) => {
|
|
806
|
+
const control = wireTurn({
|
|
807
|
+
emit: continueOpts.emit,
|
|
808
|
+
abortSignal: continueOpts.abortSignal
|
|
809
|
+
});
|
|
810
|
+
if (rerunContinue) {
|
|
811
|
+
channel.send({
|
|
812
|
+
type: "start",
|
|
813
|
+
operation: "prompt",
|
|
814
|
+
prompt: "Continue.",
|
|
815
|
+
tools: (continueOpts.tools ?? []).map((t) => ({
|
|
816
|
+
name: t.name,
|
|
817
|
+
description: t.description,
|
|
818
|
+
inputSchema: t.inputSchema
|
|
819
|
+
})),
|
|
820
|
+
...startBase()
|
|
821
|
+
});
|
|
822
|
+
pendingResumeSessionId = void 0;
|
|
823
|
+
}
|
|
824
|
+
return control;
|
|
825
|
+
},
|
|
826
|
+
doCompact: async (customInstructions) => {
|
|
827
|
+
if (customInstructions?.trim()) {
|
|
828
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
829
|
+
harnessId: "opencode",
|
|
830
|
+
message: "Harness 'opencode' supports native manual compaction, but OpenCode does not expose custom compaction instructions through the supported API."
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
if (activeTurn) {
|
|
834
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
835
|
+
harnessId: "opencode",
|
|
836
|
+
message: "Harness 'opencode' supports manual compaction between turns; compacting during an active turn is not supported by the bridge transport."
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
await runCompactOperation({
|
|
840
|
+
channel,
|
|
841
|
+
model,
|
|
842
|
+
provider,
|
|
843
|
+
permissionMode,
|
|
844
|
+
debug,
|
|
845
|
+
resumeSessionId: latestOpenCodeSessionId,
|
|
846
|
+
onCompaction: (part) => pendingCompactionParts.push(part)
|
|
847
|
+
});
|
|
848
|
+
},
|
|
849
|
+
doDetach: async () => {
|
|
850
|
+
if (stopped) {
|
|
851
|
+
throw new Error(
|
|
852
|
+
`opencode session ${sessionId} is already stopped; cannot detach.`
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
stopped = true;
|
|
856
|
+
const lastSeenEventId = await channel.suspend();
|
|
857
|
+
return {
|
|
858
|
+
type: "resume-session",
|
|
859
|
+
harnessId: "opencode",
|
|
860
|
+
specificationVersion: "harness-v1",
|
|
861
|
+
data: {
|
|
862
|
+
...latestOpenCodeSessionId ? { openCodeSessionId: latestOpenCodeSessionId } : {},
|
|
863
|
+
bridge: {
|
|
864
|
+
port: bridgePort,
|
|
865
|
+
token: bridgeToken,
|
|
866
|
+
lastSeenEventId,
|
|
867
|
+
sandboxId
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
},
|
|
872
|
+
doDestroy: async () => {
|
|
873
|
+
if (stopped) return stopPromise;
|
|
874
|
+
stopped = true;
|
|
875
|
+
stopPromise = (async () => {
|
|
876
|
+
channel.beginClose();
|
|
877
|
+
try {
|
|
878
|
+
if (!channel.isClosed()) {
|
|
879
|
+
channel.send({ type: "shutdown" });
|
|
880
|
+
}
|
|
881
|
+
} catch {
|
|
882
|
+
}
|
|
883
|
+
let stopTimer;
|
|
884
|
+
try {
|
|
885
|
+
if (proc) {
|
|
886
|
+
await Promise.race([
|
|
887
|
+
proc.wait(),
|
|
888
|
+
new Promise((resolve) => {
|
|
889
|
+
stopTimer = setTimeout(resolve, 5e3);
|
|
890
|
+
stopTimer.unref?.();
|
|
891
|
+
})
|
|
892
|
+
]);
|
|
893
|
+
}
|
|
894
|
+
} finally {
|
|
895
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
896
|
+
try {
|
|
897
|
+
await proc?.kill();
|
|
898
|
+
} catch {
|
|
899
|
+
}
|
|
900
|
+
channel.close();
|
|
901
|
+
}
|
|
902
|
+
})();
|
|
903
|
+
return stopPromise;
|
|
904
|
+
},
|
|
905
|
+
doStop: async () => {
|
|
906
|
+
if (stopped) {
|
|
907
|
+
throw new Error(
|
|
908
|
+
`opencode session ${sessionId} is already stopped; cannot stop.`
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
stopped = true;
|
|
912
|
+
channel.beginClose();
|
|
913
|
+
const data = channel.isClosed() ? {} : await new Promise((resolve, reject) => {
|
|
914
|
+
const timer = setTimeout(() => {
|
|
915
|
+
unsub();
|
|
916
|
+
reject(
|
|
917
|
+
new Error(
|
|
918
|
+
`opencode session ${sessionId} did not reply to detach within 5s.`
|
|
919
|
+
)
|
|
920
|
+
);
|
|
921
|
+
}, 5e3);
|
|
922
|
+
timer.unref?.();
|
|
923
|
+
const unsub = channel.on("bridge-detach", (msg) => {
|
|
924
|
+
clearTimeout(timer);
|
|
925
|
+
unsub();
|
|
926
|
+
resolve(msg.data);
|
|
927
|
+
});
|
|
928
|
+
try {
|
|
929
|
+
channel.send({ type: "detach" });
|
|
930
|
+
} catch (err) {
|
|
931
|
+
clearTimeout(timer);
|
|
932
|
+
unsub();
|
|
933
|
+
reject(err);
|
|
934
|
+
}
|
|
935
|
+
});
|
|
936
|
+
let stopTimer;
|
|
937
|
+
try {
|
|
938
|
+
if (proc) {
|
|
939
|
+
await Promise.race([
|
|
940
|
+
proc.wait(),
|
|
941
|
+
new Promise((resolve) => {
|
|
942
|
+
stopTimer = setTimeout(resolve, 5e3);
|
|
943
|
+
stopTimer.unref?.();
|
|
944
|
+
})
|
|
945
|
+
]);
|
|
946
|
+
}
|
|
947
|
+
} finally {
|
|
948
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
949
|
+
try {
|
|
950
|
+
await proc?.kill();
|
|
951
|
+
} catch {
|
|
952
|
+
}
|
|
953
|
+
channel.close();
|
|
954
|
+
}
|
|
955
|
+
const payload = {
|
|
956
|
+
type: "resume-session",
|
|
957
|
+
harnessId: "opencode",
|
|
958
|
+
specificationVersion: "harness-v1",
|
|
959
|
+
data: data ?? {}
|
|
960
|
+
};
|
|
961
|
+
return payload;
|
|
962
|
+
},
|
|
963
|
+
doSuspendTurn: async () => {
|
|
964
|
+
if (stopped) {
|
|
965
|
+
throw new Error(
|
|
966
|
+
`opencode session ${sessionId} is stopped; cannot suspend.`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
stopped = true;
|
|
970
|
+
const lastSeenEventId = await channel.suspend();
|
|
971
|
+
const payload = {
|
|
972
|
+
type: "continue-turn",
|
|
973
|
+
harnessId: "opencode",
|
|
974
|
+
specificationVersion: "harness-v1",
|
|
975
|
+
data: {
|
|
976
|
+
...latestOpenCodeSessionId ? { openCodeSessionId: latestOpenCodeSessionId } : {},
|
|
977
|
+
bridge: {
|
|
978
|
+
port: bridgePort,
|
|
979
|
+
token: bridgeToken,
|
|
980
|
+
lastSeenEventId,
|
|
981
|
+
sandboxId
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
return payload;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
async function runCompactOperation({
|
|
990
|
+
channel,
|
|
991
|
+
model,
|
|
992
|
+
provider,
|
|
993
|
+
permissionMode,
|
|
994
|
+
debug,
|
|
995
|
+
resumeSessionId,
|
|
996
|
+
onCompaction
|
|
997
|
+
}) {
|
|
998
|
+
let pendingResolve;
|
|
999
|
+
let pendingReject;
|
|
1000
|
+
const done = new Promise((resolve, reject) => {
|
|
1001
|
+
pendingResolve = resolve;
|
|
1002
|
+
pendingReject = reject;
|
|
1003
|
+
});
|
|
1004
|
+
const unsubs = [
|
|
1005
|
+
channel.on("compaction", (msg) => onCompaction(msg)),
|
|
1006
|
+
channel.on("finish", () => {
|
|
1007
|
+
for (const u of unsubs) u();
|
|
1008
|
+
pendingResolve();
|
|
1009
|
+
}),
|
|
1010
|
+
channel.on("error", (msg) => {
|
|
1011
|
+
for (const u of unsubs) u();
|
|
1012
|
+
pendingReject(msg.error);
|
|
1013
|
+
})
|
|
1014
|
+
];
|
|
1015
|
+
channel.send({
|
|
1016
|
+
type: "start",
|
|
1017
|
+
operation: "compact",
|
|
1018
|
+
prompt: "",
|
|
1019
|
+
tools: [],
|
|
1020
|
+
model,
|
|
1021
|
+
provider,
|
|
1022
|
+
...permissionMode ? { permissionMode } : {},
|
|
1023
|
+
...resumeSessionId ? { resumeSessionId } : {},
|
|
1024
|
+
...debug ? { debug } : {}
|
|
1025
|
+
});
|
|
1026
|
+
await done;
|
|
1027
|
+
}
|
|
1028
|
+
function extractUserText(prompt) {
|
|
1029
|
+
if (typeof prompt === "string") return prompt;
|
|
1030
|
+
const { content } = prompt;
|
|
1031
|
+
if (typeof content === "string") return content;
|
|
1032
|
+
const parts = [];
|
|
1033
|
+
for (const part of content) {
|
|
1034
|
+
if (part.type !== "text") {
|
|
1035
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
1036
|
+
harnessId: "opencode",
|
|
1037
|
+
message: `The opencode harness does not yet support user message parts of type '${part.type}'. Pass a string or a user message whose content contains only text parts.`
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
parts.push(part.text);
|
|
1041
|
+
}
|
|
1042
|
+
return parts.join("\n\n");
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// src/index.ts
|
|
1046
|
+
var openCode = createOpenCode();
|
|
1047
|
+
export {
|
|
1048
|
+
createOpenCode,
|
|
1049
|
+
openCode
|
|
1050
|
+
};
|
|
1051
|
+
//# sourceMappingURL=index.js.map
|