@ai-sdk/harness-opencode 0.0.0-6b196531-20260710185421

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.
@@ -0,0 +1,2345 @@
1
+ // ../harness/dist/bridge/index.js
2
+ import { appendFile, mkdir, writeFile } from "fs/promises";
3
+ import { existsSync, readFileSync } from "fs";
4
+ import { env as procEnv, pid, stdout } from "process";
5
+ import { WebSocketServer } from "ws";
6
+ var DEBUG_LEVEL_WEIGHT = {
7
+ error: 0,
8
+ warn: 1,
9
+ info: 2,
10
+ debug: 3,
11
+ trace: 4
12
+ };
13
+ function subsystemMatches(filters, subsystem) {
14
+ if (!filters || filters.length === 0) return true;
15
+ return filters.some(
16
+ (filter) => subsystem === filter || subsystem.startsWith(`${filter}.`)
17
+ );
18
+ }
19
+ function formatBridgeError(err) {
20
+ if (err instanceof Error) {
21
+ return { name: err.name, message: err.message, stack: err.stack };
22
+ }
23
+ if (typeof err === "string") {
24
+ return { message: err };
25
+ }
26
+ if (err !== null && typeof err === "object") {
27
+ try {
28
+ return { message: JSON.stringify(err) };
29
+ } catch {
30
+ }
31
+ }
32
+ return { message: String(err) };
33
+ }
34
+ function parseEnvList(value) {
35
+ if (!value) return void 0;
36
+ const items = value.split(",").map((item) => item.trim()).filter(Boolean);
37
+ return items.length > 0 ? items : void 0;
38
+ }
39
+ var ENV_TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
40
+ var WS_OPEN = 1;
41
+ async function runBridge(options) {
42
+ const { bridgeType, bridgeStateDir: bridgeStateDir2, onStart, onDetach } = options;
43
+ const expectedToken = options.token ?? procEnv.BRIDGE_CHANNEL_TOKEN ?? "";
44
+ const bridgeWsPort = options.port ?? parseInt(procEnv.BRIDGE_WS_PORT ?? "0", 10);
45
+ const bridgeMetaPath = `${bridgeStateDir2}/bridge-meta.json`;
46
+ const startConfigPath = `${bridgeStateDir2}/start-config.json`;
47
+ const rerunStartConfigPath = `${bridgeStateDir2}/rerun-start-config.json`;
48
+ const eventLogPath = `${bridgeStateDir2}/event-log.ndjson`;
49
+ try {
50
+ await mkdir(bridgeStateDir2, { recursive: true });
51
+ } catch {
52
+ }
53
+ let currentBoundPort = 0;
54
+ let currentTurnState = "init";
55
+ let activeSocket;
56
+ let isFirstTurn = true;
57
+ let turnAbort;
58
+ let currentUserMessages;
59
+ let currentInterruptHandler;
60
+ let debugConfig;
61
+ let consoleCaptureInstalled = false;
62
+ const envDebugEnabled = ENV_TRUTHY.has(
63
+ (procEnv.HARNESS_DEBUG ?? "").toLowerCase()
64
+ );
65
+ let seqCounter = 0;
66
+ let eventLog = [];
67
+ let diskBuffer = "";
68
+ let flushPromise = null;
69
+ const flushEventsToDisk = async () => {
70
+ while (diskBuffer.length > 0) {
71
+ const buf = diskBuffer;
72
+ diskBuffer = "";
73
+ await appendFile(eventLogPath, buf).catch(() => {
74
+ });
75
+ }
76
+ };
77
+ const scheduleEventFlush = () => {
78
+ if (flushPromise) return;
79
+ flushPromise = new Promise((resolve) => {
80
+ setImmediate(() => {
81
+ void flushEventsToDisk().finally(resolve);
82
+ });
83
+ }).finally(() => {
84
+ flushPromise = null;
85
+ if (diskBuffer.length > 0) {
86
+ scheduleEventFlush();
87
+ }
88
+ });
89
+ };
90
+ const flushPendingEventsToDisk = async () => {
91
+ if (diskBuffer.length > 0 && !flushPromise) {
92
+ scheduleEventFlush();
93
+ }
94
+ let inFlight = flushPromise;
95
+ while (inFlight) {
96
+ await inFlight;
97
+ inFlight = flushPromise;
98
+ }
99
+ };
100
+ const replayFromDisk = procEnv.BRIDGE_REPLAY_FROM_DISK === "1";
101
+ if (replayFromDisk && existsSync(eventLogPath)) {
102
+ try {
103
+ const lines = readFileSync(eventLogPath, "utf8").split("\n").map((line) => line.trim()).filter(Boolean);
104
+ eventLog = lines.map((line) => ({
105
+ seq: JSON.parse(line).seq,
106
+ line
107
+ }));
108
+ seqCounter = eventLog.at(-1)?.seq ?? 0;
109
+ } catch {
110
+ eventLog = [];
111
+ seqCounter = 0;
112
+ }
113
+ }
114
+ const pendingToolResults = /* @__PURE__ */ new Map();
115
+ const pendingToolApprovals = /* @__PURE__ */ new Map();
116
+ const writeBridgeMeta = async (state) => {
117
+ try {
118
+ await writeFile(
119
+ bridgeMetaPath,
120
+ JSON.stringify({
121
+ type: bridgeType,
122
+ port: currentBoundPort,
123
+ state,
124
+ pid
125
+ })
126
+ );
127
+ } catch {
128
+ }
129
+ };
130
+ const writeStartConfig = async (start) => {
131
+ try {
132
+ const serialized = JSON.stringify(start);
133
+ await writeFile(startConfigPath, serialized);
134
+ if (!existsSync(rerunStartConfigPath)) {
135
+ await writeFile(rerunStartConfigPath, serialized);
136
+ }
137
+ } catch {
138
+ }
139
+ };
140
+ const sendControl = (msg) => {
141
+ if (activeSocket?.readyState === WS_OPEN) {
142
+ try {
143
+ activeSocket.send(JSON.stringify(msg));
144
+ } catch {
145
+ }
146
+ }
147
+ };
148
+ const emit = (event) => {
149
+ const seq = ++seqCounter;
150
+ const line = JSON.stringify({ ...event, seq });
151
+ eventLog.push({ seq, line });
152
+ diskBuffer += `${line}
153
+ `;
154
+ scheduleEventFlush();
155
+ if (activeSocket?.readyState === WS_OPEN) {
156
+ try {
157
+ activeSocket.send(line);
158
+ } catch {
159
+ }
160
+ }
161
+ };
162
+ const replay = (ws, afterSeq) => {
163
+ for (const entry of eventLog) {
164
+ if (entry.seq > afterSeq && ws.readyState === WS_OPEN) {
165
+ ws.send(entry.line);
166
+ }
167
+ }
168
+ };
169
+ const shouldEmitDebugEvent = (level, subsystem) => {
170
+ if (!debugConfig?.enabled) return false;
171
+ const threshold = debugConfig.level ?? "debug";
172
+ if (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;
173
+ return subsystemMatches(debugConfig.subsystems, subsystem);
174
+ };
175
+ const rawStdoutWrite = process.stdout.write.bind(process.stdout);
176
+ const rawStderrWrite = process.stderr.write.bind(process.stderr);
177
+ const writeErrorToStderr = (input) => {
178
+ try {
179
+ const formatted = formatBridgeError(input.error);
180
+ rawStderrWrite(
181
+ `[harness:${bridgeType}:error] ${input.message}: ${formatted.message}
182
+ `
183
+ );
184
+ if (formatted.stack) {
185
+ rawStderrWrite(`${formatted.stack}
186
+ `);
187
+ }
188
+ } catch {
189
+ }
190
+ };
191
+ const emitWarning = (input) => {
192
+ try {
193
+ for (const line of input.message.split("\n")) {
194
+ if (line.trim().length > 0) {
195
+ rawStderrWrite(`[harness:${bridgeType}:warn] ${line}
196
+ `);
197
+ }
198
+ }
199
+ } catch {
200
+ }
201
+ };
202
+ const emitError = (input) => {
203
+ writeErrorToStderr({
204
+ message: input.message ?? "bridge error",
205
+ error: input.error
206
+ });
207
+ emit({ type: "error", error: serialiseError(input.error) });
208
+ };
209
+ const installConsoleCapture = () => {
210
+ if (consoleCaptureInstalled) return;
211
+ consoleCaptureInstalled = true;
212
+ const buffers = {
213
+ stdout: "",
214
+ stderr: ""
215
+ };
216
+ const patch = (stream, raw) => (chunk, encoding, cb) => {
217
+ if (debugConfig?.enabled) {
218
+ try {
219
+ const enc = typeof encoding === "string" ? encoding : "utf8";
220
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString(
221
+ enc
222
+ );
223
+ const combined = buffers[stream] + text.replace(/\r\n/g, "\n");
224
+ const parts = combined.split("\n");
225
+ buffers[stream] = parts.pop() ?? "";
226
+ for (const line of parts) {
227
+ const trimmed = line.replace(/\s+$/, "");
228
+ if (trimmed) {
229
+ emit({
230
+ type: "sandbox-log",
231
+ source: bridgeType,
232
+ stream,
233
+ line: trimmed
234
+ });
235
+ }
236
+ }
237
+ } catch {
238
+ }
239
+ }
240
+ return raw(
241
+ chunk,
242
+ encoding,
243
+ cb
244
+ );
245
+ };
246
+ process.stdout.write = patch(
247
+ "stdout",
248
+ rawStdoutWrite
249
+ );
250
+ process.stderr.write = patch(
251
+ "stderr",
252
+ rawStderrWrite
253
+ );
254
+ };
255
+ const handleInbound = async (msg, ws) => {
256
+ switch (msg.type) {
257
+ case "start": {
258
+ const firstTurn = isFirstTurn;
259
+ isFirstTurn = false;
260
+ eventLog = [];
261
+ diskBuffer = "";
262
+ void writeFile(eventLogPath, "").catch(() => {
263
+ });
264
+ turnAbort = new AbortController();
265
+ currentTurnState = "running";
266
+ currentInterruptHandler = void 0;
267
+ void writeStartConfig(msg);
268
+ void writeBridgeMeta("running");
269
+ const startDebug = msg.debug;
270
+ debugConfig = {
271
+ enabled: startDebug?.enabled ?? envDebugEnabled,
272
+ level: startDebug?.level ?? procEnv.HARNESS_DEBUG_LEVEL,
273
+ subsystems: startDebug?.subsystems ?? parseEnvList(procEnv.HARNESS_DEBUG_SUBSYSTEMS)
274
+ };
275
+ if (debugConfig.enabled) {
276
+ installConsoleCapture();
277
+ }
278
+ const turn = {
279
+ emit,
280
+ requestToolResult: (toolCallId) => new Promise((resolve) => {
281
+ pendingToolResults.set(toolCallId, resolve);
282
+ }),
283
+ requestToolApproval: (approvalId) => new Promise((resolve) => {
284
+ pendingToolApprovals.set(approvalId, resolve);
285
+ }),
286
+ pendingUserMessages: [],
287
+ abortSignal: turnAbort.signal,
288
+ onInterrupt: (handler) => {
289
+ currentInterruptHandler = handler;
290
+ },
291
+ firstTurn,
292
+ bridgeLog: (input) => {
293
+ const level = input.level ?? "debug";
294
+ if (!shouldEmitDebugEvent(level, input.subsystem)) return;
295
+ emit({
296
+ type: "debug-event",
297
+ level,
298
+ subsystem: input.subsystem,
299
+ message: input.message,
300
+ ...input.attrs ? { attrs: input.attrs } : {},
301
+ ...input.error !== void 0 ? { error: formatBridgeError(input.error) } : {}
302
+ });
303
+ },
304
+ emitWarning,
305
+ emitError
306
+ };
307
+ currentUserMessages = turn.pendingUserMessages;
308
+ try {
309
+ await onStart(msg, turn);
310
+ } catch (err) {
311
+ emitError({ error: err, message: "bridge turn failed" });
312
+ } finally {
313
+ currentInterruptHandler = void 0;
314
+ currentTurnState = "waiting";
315
+ void writeBridgeMeta("waiting");
316
+ }
317
+ return;
318
+ }
319
+ case "tool-result": {
320
+ const resolver = pendingToolResults.get(msg.toolCallId);
321
+ if (resolver) {
322
+ pendingToolResults.delete(msg.toolCallId);
323
+ resolver({ output: msg.output, isError: msg.isError });
324
+ }
325
+ return;
326
+ }
327
+ case "tool-approval-response": {
328
+ const resolver = pendingToolApprovals.get(msg.approvalId);
329
+ if (resolver) {
330
+ pendingToolApprovals.delete(msg.approvalId);
331
+ resolver({ approved: msg.approved, reason: msg.reason });
332
+ }
333
+ return;
334
+ }
335
+ case "user-message":
336
+ currentUserMessages?.push(msg.text);
337
+ return;
338
+ case "abort":
339
+ turnAbort?.abort();
340
+ return;
341
+ case "interrupt":
342
+ try {
343
+ if (pendingToolResults.size === 0 && pendingToolApprovals.size === 0) {
344
+ if (currentInterruptHandler) {
345
+ await currentInterruptHandler();
346
+ } else {
347
+ turnAbort?.abort();
348
+ }
349
+ }
350
+ sendControl({ type: "bridge-interrupted", ok: true });
351
+ } catch (err) {
352
+ sendControl({
353
+ type: "bridge-interrupted",
354
+ ok: false,
355
+ error: serialiseError(err)
356
+ });
357
+ }
358
+ return;
359
+ case "resume":
360
+ replay(ws, msg.lastSeenEventId);
361
+ return;
362
+ case "shutdown":
363
+ currentTurnState = "done";
364
+ void writeBridgeMeta("done");
365
+ drainThenExit(ws, 1e3, "shutdown");
366
+ return;
367
+ case "detach": {
368
+ currentTurnState = "done";
369
+ void writeBridgeMeta("done");
370
+ const data = await onDetach?.() ?? {};
371
+ sendControl({ type: "bridge-detach", data });
372
+ drainThenExit(ws, 1e3, "detach");
373
+ return;
374
+ }
375
+ }
376
+ };
377
+ void writeBridgeMeta("init");
378
+ const wss = new WebSocketServer({ port: bridgeWsPort, host: "0.0.0.0" });
379
+ const exit = () => {
380
+ if (options.onExit) {
381
+ options.onExit();
382
+ return;
383
+ }
384
+ wss.close(() => process.exit(0));
385
+ setTimeout(() => process.exit(0), 1e3).unref();
386
+ };
387
+ const drainThenExit = (ws, code, reason) => {
388
+ const start = Date.now();
389
+ const tick = () => {
390
+ const drained = ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN;
391
+ if (drained || Date.now() - start >= 5e3) {
392
+ void flushPendingEventsToDisk().finally(() => {
393
+ try {
394
+ ws.close(code, reason);
395
+ } finally {
396
+ exit();
397
+ }
398
+ });
399
+ return;
400
+ }
401
+ setTimeout(tick, 10).unref();
402
+ };
403
+ tick();
404
+ };
405
+ wss.on("listening", () => {
406
+ const addr = wss.address();
407
+ currentBoundPort = typeof addr === "object" && addr ? addr.port : 0;
408
+ currentTurnState = "waiting";
409
+ void writeBridgeMeta("waiting");
410
+ stdout.write(
411
+ JSON.stringify({
412
+ type: "bridge-ready",
413
+ port: currentBoundPort
414
+ }) + "\n"
415
+ );
416
+ options.onListening?.(currentBoundPort);
417
+ });
418
+ wss.on("connection", (ws, req) => {
419
+ const url = new URL(req.url ?? "/", "http://localhost");
420
+ if (url.searchParams.get("agent_bridge_token") !== expectedToken) {
421
+ ws.close(1008, "unauthorized");
422
+ return;
423
+ }
424
+ activeSocket = ws;
425
+ sendControl({
426
+ type: "bridge-hello",
427
+ state: currentTurnState,
428
+ lastSeq: seqCounter
429
+ });
430
+ ws.on("message", (raw) => {
431
+ let parsed;
432
+ try {
433
+ const text = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf8");
434
+ parsed = JSON.parse(text);
435
+ } catch (err) {
436
+ sendControl({
437
+ type: "error",
438
+ error: `protocol parse error: ${err.message}`
439
+ });
440
+ return;
441
+ }
442
+ void handleInbound(parsed, ws);
443
+ });
444
+ ws.on("close", () => {
445
+ if (activeSocket === ws) {
446
+ activeSocket = void 0;
447
+ }
448
+ });
449
+ ws.on("error", () => {
450
+ });
451
+ });
452
+ process.on("uncaughtException", (err) => {
453
+ emitError({ error: err, message: "uncaught exception" });
454
+ });
455
+ process.on("unhandledRejection", (err) => {
456
+ emitError({ error: err, message: "unhandled rejection" });
457
+ });
458
+ await new Promise((resolve, reject) => {
459
+ if (wss.address() != null) {
460
+ resolve();
461
+ return;
462
+ }
463
+ wss.once("listening", resolve);
464
+ wss.once("error", reject);
465
+ });
466
+ return {
467
+ port: currentBoundPort,
468
+ close: () => new Promise((resolve) => {
469
+ wss.close(() => resolve());
470
+ })
471
+ };
472
+ }
473
+ function serialiseError(err) {
474
+ if (err instanceof Error) {
475
+ return { name: err.name, message: err.message, stack: err.stack };
476
+ }
477
+ return err;
478
+ }
479
+
480
+ // src/bridge/index.ts
481
+ import { randomUUID } from "crypto";
482
+ import { mkdirSync } from "fs";
483
+ import { createServer } from "http";
484
+ import path2 from "path";
485
+ import { argv, env as procEnv2 } from "process";
486
+ import {
487
+ createOpencodeClient,
488
+ createOpencodeServer
489
+ } from "@opencode-ai/sdk/v2";
490
+
491
+ // src/bridge/opencode-events.ts
492
+ function unwrapOpenCodeEvent(rawEvent) {
493
+ if (!rawEvent || typeof rawEvent !== "object") return void 0;
494
+ const raw = rawEvent;
495
+ if (raw.type === "sync" && raw.syncEvent) {
496
+ const sync = raw.syncEvent;
497
+ return {
498
+ id: String(sync.id ?? raw.id ?? ""),
499
+ type: stripSyncVersion(String(sync.type ?? "")),
500
+ properties: asRecord(sync.data) ?? {}
501
+ };
502
+ }
503
+ return {
504
+ id: typeof raw.id === "string" ? raw.id : void 0,
505
+ type: typeof raw.type === "string" ? stripSyncVersion(raw.type) : void 0,
506
+ properties: asRecord(raw.properties) ?? asRecord(raw.data) ?? {}
507
+ };
508
+ }
509
+ function getOpenCodeEventSessionId(event) {
510
+ const props = event.properties;
511
+ if (!props) return void 0;
512
+ if (typeof props.sessionID === "string") return props.sessionID;
513
+ if (typeof props.sessionId === "string") return props.sessionId;
514
+ if (event.type?.startsWith("session.") && typeof props.id === "string") {
515
+ return props.id;
516
+ }
517
+ const part = props.part;
518
+ if (part && typeof part === "object" && !Array.isArray(part) && typeof part.sessionID === "string") {
519
+ return part.sessionID;
520
+ }
521
+ return void 0;
522
+ }
523
+ function isStepSettlementEvent(event) {
524
+ return event.type === "session.next.step.ended" || event.type === "session.next.step.failed" || event.type === "session.error";
525
+ }
526
+ function emitMissingFinalDelta({
527
+ id,
528
+ fullText,
529
+ emittedText,
530
+ emit,
531
+ type
532
+ }) {
533
+ if (!fullText || fullText === emittedText || !fullText.startsWith(emittedText)) {
534
+ return;
535
+ }
536
+ emit({ type, id, delta: fullText.slice(emittedText.length) });
537
+ }
538
+ function stripSyncVersion(type) {
539
+ return type.replace(/\.\d+$/, "");
540
+ }
541
+ function asRecord(value) {
542
+ if (!value || typeof value !== "object" || Array.isArray(value))
543
+ return void 0;
544
+ return value;
545
+ }
546
+
547
+ // src/bridge/opencode-usage.ts
548
+ function mapUsage(tokens) {
549
+ const value = extractOpenCodeTokens(tokens) ?? zeroOpenCodeTokens();
550
+ const cacheRead = value.cache.read;
551
+ return {
552
+ inputTokens: {
553
+ total: value.input,
554
+ noCache: Math.max(0, value.input - cacheRead),
555
+ cacheRead,
556
+ cacheWrite: value.cache.write
557
+ },
558
+ outputTokens: {
559
+ total: value.output + value.reasoning,
560
+ text: value.output,
561
+ reasoning: value.reasoning
562
+ }
563
+ };
564
+ }
565
+ function defaultUsage() {
566
+ return mapUsage(zeroOpenCodeTokens());
567
+ }
568
+ function extractSessionTokens(value) {
569
+ const record = asRecord2(value);
570
+ if (!record) return void 0;
571
+ const tokens = extractOpenCodeTokens(record.tokens) ?? extractOpenCodeTokens(asRecord2(record.info)?.tokens) ?? extractOpenCodeTokens(asRecord2(record.data)?.tokens) ?? extractOpenCodeTokens(asRecord2(asRecord2(record.data)?.data)?.tokens);
572
+ return tokens;
573
+ }
574
+ function subtractSessionTokens({
575
+ before,
576
+ after
577
+ }) {
578
+ return {
579
+ input: diff({ before: before.input, after: after.input }),
580
+ output: diff({ before: before.output, after: after.output }),
581
+ reasoning: diff({ before: before.reasoning, after: after.reasoning }),
582
+ cache: {
583
+ read: diff({ before: before.cache.read, after: after.cache.read }),
584
+ write: diff({ before: before.cache.write, after: after.cache.write })
585
+ }
586
+ };
587
+ }
588
+ function addUsage({
589
+ left,
590
+ right
591
+ }) {
592
+ if (left == null) return right;
593
+ const leftInput = asTokenGroup(left.inputTokens);
594
+ const rightInput = asTokenGroup(right.inputTokens);
595
+ const leftOutput = asTokenGroup(left.outputTokens);
596
+ const rightOutput = asTokenGroup(right.outputTokens);
597
+ return {
598
+ inputTokens: {
599
+ total: add({ left: leftInput.total, right: rightInput.total }),
600
+ noCache: add({ left: leftInput.noCache, right: rightInput.noCache }),
601
+ cacheRead: add({
602
+ left: leftInput.cacheRead,
603
+ right: rightInput.cacheRead
604
+ }),
605
+ cacheWrite: add({
606
+ left: leftInput.cacheWrite,
607
+ right: rightInput.cacheWrite
608
+ })
609
+ },
610
+ outputTokens: {
611
+ total: add({ left: leftOutput.total, right: rightOutput.total }),
612
+ text: add({ left: leftOutput.text, right: rightOutput.text }),
613
+ reasoning: add({
614
+ left: leftOutput.reasoning,
615
+ right: rightOutput.reasoning
616
+ })
617
+ }
618
+ };
619
+ }
620
+ function extractOpenCodeTokens(value) {
621
+ const record = asRecord2(value);
622
+ const cache = asRecord2(record?.cache);
623
+ if (!record || !cache) return void 0;
624
+ return {
625
+ input: numberValue(record.input),
626
+ output: numberValue(record.output),
627
+ reasoning: numberValue(record.reasoning),
628
+ cache: {
629
+ read: numberValue(cache.read),
630
+ write: numberValue(cache.write)
631
+ }
632
+ };
633
+ }
634
+ function zeroOpenCodeTokens() {
635
+ return {
636
+ input: 0,
637
+ output: 0,
638
+ reasoning: 0,
639
+ cache: { read: 0, write: 0 }
640
+ };
641
+ }
642
+ function asTokenGroup(value) {
643
+ return asRecord2(value) ?? {};
644
+ }
645
+ function asRecord2(value) {
646
+ if (!value || typeof value !== "object" || Array.isArray(value))
647
+ return void 0;
648
+ return value;
649
+ }
650
+ function numberValue(value) {
651
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
652
+ }
653
+ function diff({ before, after }) {
654
+ return Math.max(0, after - before);
655
+ }
656
+ function add({
657
+ left,
658
+ right
659
+ }) {
660
+ const leftNumber = typeof left === "number" ? left : void 0;
661
+ const rightNumber = typeof right === "number" ? right : void 0;
662
+ return leftNumber == null && rightNumber == null ? void 0 : (leftNumber ?? 0) + (rightNumber ?? 0);
663
+ }
664
+
665
+ // src/bridge/opencode-finish-step.ts
666
+ function mapOpenCodeFinishReason(reason) {
667
+ const normalized = reason.toLowerCase();
668
+ if (normalized.includes("length")) return "length";
669
+ if (normalized.includes("filter")) return "content-filter";
670
+ if (normalized.includes("tool")) return "tool-calls";
671
+ if (normalized.includes("error") || normalized.includes("fail"))
672
+ return "error";
673
+ if (normalized === "stop" || normalized === "end") return "stop";
674
+ return "other";
675
+ }
676
+ function legacyStepFinishPartToFinishStep(part) {
677
+ if (!isRecord(part) || part.type !== "step-finish") return void 0;
678
+ const rawFinish = typeof part.reason === "string" ? part.reason : "stop";
679
+ return {
680
+ type: "finish-step",
681
+ finishReason: {
682
+ unified: mapOpenCodeFinishReason(rawFinish),
683
+ raw: rawFinish
684
+ },
685
+ usage: mapUsage(part.tokens),
686
+ ...typeof part.cost === "number" ? { harnessMetadata: { opencode: { cost: part.cost } } } : {}
687
+ };
688
+ }
689
+ function isRecord(value) {
690
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
691
+ }
692
+
693
+ // src/bridge/opencode-path.ts
694
+ import path from "path";
695
+ var fallbackPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
696
+ function prependOpenCodeBinToPath({
697
+ bootstrapDir: bootstrapDir2,
698
+ env
699
+ }) {
700
+ env.PATH = [
701
+ path.join(bootstrapDir2, "node_modules", ".bin"),
702
+ env.PATH || fallbackPath
703
+ ].join(path.delimiter);
704
+ }
705
+
706
+ // src/bridge/tool-relay-auth.ts
707
+ import { readdir, readFile, readlink } from "fs/promises";
708
+ var ToolRelayAuthorizer = class {
709
+ constructor({
710
+ ttlMs = 1e4,
711
+ now = Date.now
712
+ } = {}) {
713
+ this.authorizations = [];
714
+ this.ttlMs = ttlMs;
715
+ this.now = now;
716
+ }
717
+ authorizeToolCall(call) {
718
+ this.pruneExpired();
719
+ this.authorizations.push({
720
+ key: toolRelayCallKey(call),
721
+ expiresAt: this.now() + this.ttlMs
722
+ });
723
+ }
724
+ consumeToolCall(call) {
725
+ this.pruneExpired();
726
+ const key = toolRelayCallKey(call);
727
+ const index = this.authorizations.findIndex((auth) => auth.key === key);
728
+ if (index === -1) return false;
729
+ this.authorizations.splice(index, 1);
730
+ return true;
731
+ }
732
+ pruneExpired() {
733
+ const now = this.now();
734
+ for (let i = this.authorizations.length - 1; i >= 0; i--) {
735
+ if (this.authorizations[i].expiresAt <= now) {
736
+ this.authorizations.splice(i, 1);
737
+ }
738
+ }
739
+ }
740
+ };
741
+ function toolRelayCallKey({ toolName, input }) {
742
+ return `${toolName}\0${canonicalJson(input ?? {})}`;
743
+ }
744
+ function canonicalJson(value) {
745
+ return JSON.stringify(normalizeJsonValue(value));
746
+ }
747
+ function normalizeJsonValue(value) {
748
+ if (Array.isArray(value)) {
749
+ return value.map(normalizeJsonValue);
750
+ }
751
+ if (value && typeof value === "object") {
752
+ return Object.fromEntries(
753
+ Object.entries(value).filter(([, entryValue]) => entryValue !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue)])
754
+ );
755
+ }
756
+ return value;
757
+ }
758
+ async function isToolRelayRequestFromAllowedProcess({
759
+ socket,
760
+ allowedScriptPaths
761
+ }) {
762
+ if (process.platform !== "linux") return false;
763
+ if (!socket.remotePort || !socket.localPort) return false;
764
+ const inode = await findTcpSocketInode({
765
+ clientPort: socket.remotePort,
766
+ serverPort: socket.localPort
767
+ });
768
+ if (!inode) return false;
769
+ const cmdline = await findProcessCmdlineForSocketInode({ inode });
770
+ return cmdline?.some((arg) => allowedScriptPaths.has(arg)) ?? false;
771
+ }
772
+ async function findTcpSocketInode({
773
+ clientPort,
774
+ serverPort
775
+ }) {
776
+ for (const tablePath of ["/proc/net/tcp", "/proc/net/tcp6"]) {
777
+ const table = await readFile(tablePath, "utf8").catch(() => void 0);
778
+ if (!table) continue;
779
+ for (const line of table.split("\n").slice(1)) {
780
+ const columns = line.trim().split(/\s+/);
781
+ if (columns.length < 10) continue;
782
+ const local = parseProcNetAddress(columns[1]);
783
+ const remote = parseProcNetAddress(columns[2]);
784
+ if (local?.port === clientPort && remote?.port === serverPort && columns[9] !== "0") {
785
+ return columns[9];
786
+ }
787
+ }
788
+ }
789
+ return void 0;
790
+ }
791
+ function parseProcNetAddress(value) {
792
+ const [, portHex] = value.split(":");
793
+ if (!portHex) return void 0;
794
+ return { port: Number.parseInt(portHex, 16) };
795
+ }
796
+ async function findProcessCmdlineForSocketInode({
797
+ inode
798
+ }) {
799
+ const procEntries = await readdir("/proc", { withFileTypes: true }).catch(
800
+ () => []
801
+ );
802
+ for (const entry of procEntries) {
803
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
804
+ const fdDir = `/proc/${entry.name}/fd`;
805
+ const fds = await readdir(fdDir).catch(() => []);
806
+ for (const fd of fds) {
807
+ const target = await readlink(`${fdDir}/${fd}`).catch(() => void 0);
808
+ if (target !== `socket:[${inode}]`) continue;
809
+ const cmdline = await readFile(`/proc/${entry.name}/cmdline`, "utf8").then((value) => value.split("\0").filter(Boolean)).catch(() => void 0);
810
+ if (cmdline) return cmdline;
811
+ }
812
+ }
813
+ return void 0;
814
+ }
815
+
816
+ // src/bridge/index.ts
817
+ var NATIVE_TO_COMMON = {
818
+ view: "read",
819
+ read: "read",
820
+ write: "write",
821
+ edit: "edit",
822
+ bash: "bash",
823
+ glob: "glob",
824
+ grep: "grep"
825
+ };
826
+ var OPENCODE_TO_WIRE = {
827
+ list: "ls",
828
+ ls: "ls",
829
+ webfetch: "webfetch",
830
+ task: "agent",
831
+ agent: "agent",
832
+ subtask: "agent"
833
+ };
834
+ var PUBLIC_TO_NATIVE = {
835
+ read: "view",
836
+ write: "write",
837
+ edit: "edit",
838
+ bash: "bash",
839
+ glob: "glob",
840
+ grep: "grep",
841
+ ls: "list",
842
+ webfetch: "webfetch",
843
+ skill: "skill",
844
+ todowrite: "todowrite",
845
+ agent: "agent"
846
+ };
847
+ var TOOL_KIND = {
848
+ read: "readonly",
849
+ glob: "readonly",
850
+ grep: "readonly",
851
+ ls: "readonly",
852
+ webfetch: "readonly",
853
+ write: "edit",
854
+ edit: "edit",
855
+ bash: "bash",
856
+ agent: "bash",
857
+ skill: "edit",
858
+ todowrite: "edit"
859
+ };
860
+ var HARNESS_CLIENT_APP = procEnv2.AI_SDK_HARNESS_CLIENT_APP;
861
+ var args = parseArgs(argv.slice(2));
862
+ var workdir = args.workdir ?? emitFatal("Missing --workdir argument.");
863
+ var bridgeStateDir = args.bridgeStateDir ?? emitFatal("Missing --bridge-state-dir argument.");
864
+ var bootstrapDir = args.bootstrapDir ?? workdir;
865
+ var skillsDir = args.skillsDir;
866
+ var runtime = { toolNames: /* @__PURE__ */ new Set() };
867
+ prependOpenCodeBinToPath({ bootstrapDir, env: procEnv2 });
868
+ mkdirSync(process.env.HOME ?? "/tmp/opencode-home", { recursive: true });
869
+ await runBridge({
870
+ bridgeType: "opencode",
871
+ bridgeStateDir,
872
+ onStart: runTurn,
873
+ onDetach: () => runtime.sessionId ? { openCodeSessionId: runtime.sessionId } : {}
874
+ });
875
+ async function runTurn(start, turn) {
876
+ const emit = (msg) => turn.emit(msg);
877
+ let totalUsage;
878
+ try {
879
+ await ensureRuntime({ start, turn, emit });
880
+ const client = runtime.client;
881
+ const sessionId = await ensureSession({ client, start, emit });
882
+ if (start.operation === "compact") {
883
+ await runCompaction({ client, sessionId, start, turn, emit });
884
+ } else {
885
+ totalUsage = await runPrompt({ client, sessionId, start, turn, emit });
886
+ }
887
+ } catch (err) {
888
+ turn.emitError({ error: err, message: "OpenCode turn failed" });
889
+ } finally {
890
+ emit({
891
+ type: "finish",
892
+ finishReason: { unified: "stop", raw: "stop" },
893
+ totalUsage: totalUsage ?? defaultUsage()
894
+ });
895
+ }
896
+ }
897
+ async function ensureRuntime({
898
+ start,
899
+ turn,
900
+ emit
901
+ }) {
902
+ if (runtime.client) return;
903
+ if (start.tools && start.tools.length > 0) {
904
+ runtime.toolNames = new Set(start.tools.map((tool) => tool.name));
905
+ runtime.relay = await startToolRelay({
906
+ allowedScriptPaths: [`${bootstrapDir}/host-tool-mcp.mjs`],
907
+ tools: start.tools,
908
+ emit,
909
+ requestToolResult: turn.requestToolResult
910
+ });
911
+ }
912
+ const server = await createOpencodeServer({
913
+ hostname: "127.0.0.1",
914
+ port: 0,
915
+ timeout: 3e4,
916
+ config: buildOpenCodeConfig({
917
+ start,
918
+ relayPort: runtime.relay?.port
919
+ })
920
+ });
921
+ runtime.server = server;
922
+ runtime.client = createOpencodeClient({
923
+ baseUrl: server.url,
924
+ directory: workdir
925
+ });
926
+ }
927
+ function buildOpenCodeConfig({
928
+ start,
929
+ relayPort
930
+ }) {
931
+ const config = {
932
+ share: "disabled",
933
+ autoupdate: false,
934
+ permission: {
935
+ read: "allow",
936
+ glob: "allow",
937
+ grep: "allow",
938
+ list: "allow",
939
+ edit: "ask",
940
+ bash: "ask",
941
+ external_directory: "ask",
942
+ webfetch: "ask",
943
+ doom_loop: "ask",
944
+ task: "ask"
945
+ }
946
+ };
947
+ if (start.model) config.model = start.model;
948
+ if (skillsDir) config.skills = { paths: [skillsDir] };
949
+ const inactiveToolNames = resolveInactiveBuiltinToolNames(start);
950
+ const permission = config.permission;
951
+ for (const toolName of inactiveToolNames) {
952
+ const permissionName = toPermissionToolName(
953
+ PUBLIC_TO_NATIVE[toolName] ?? toolName
954
+ );
955
+ if (permissionName === "ls") {
956
+ permission.list = "ask";
957
+ } else {
958
+ permission[permissionName] = "ask";
959
+ }
960
+ }
961
+ const provider = buildProviderConfig(start);
962
+ if (provider) config.provider = provider;
963
+ if (relayPort && start.tools && start.tools.length > 0) {
964
+ config.mcp = {
965
+ "harness-tools": {
966
+ type: "local",
967
+ enabled: true,
968
+ command: ["node", `${bootstrapDir}/host-tool-mcp.mjs`],
969
+ environment: {
970
+ TOOL_SCHEMAS: JSON.stringify(
971
+ start.tools.map((t) => ({
972
+ name: t.name,
973
+ description: t.description,
974
+ inputSchema: t.inputSchema
975
+ }))
976
+ ),
977
+ TOOL_RELAY_URL: `http://127.0.0.1:${relayPort}`
978
+ }
979
+ }
980
+ };
981
+ }
982
+ return config;
983
+ }
984
+ function buildProviderConfig(start) {
985
+ const model = splitModel(start.model, start.provider);
986
+ const providerID = model.providerID ?? start.provider ?? procEnv2.OPENAI_NAME ?? "anthropic";
987
+ const modelID = model.modelID;
988
+ if (procEnv2.AI_GATEWAY_API_KEY && procEnv2.AI_GATEWAY_BASE_URL) {
989
+ return {
990
+ [providerID]: {
991
+ options: {
992
+ apiKey: procEnv2.AI_GATEWAY_API_KEY,
993
+ baseURL: toOpenCodeGatewayBaseUrl(procEnv2.AI_GATEWAY_BASE_URL),
994
+ ...HARNESS_CLIENT_APP ? { headers: { "x-client-app": HARNESS_CLIENT_APP } } : {}
995
+ },
996
+ ...modelID ? {
997
+ models: {
998
+ [modelID]: { id: modelID, name: modelID }
999
+ }
1000
+ } : {}
1001
+ }
1002
+ };
1003
+ }
1004
+ if ((procEnv2.OPENAI_NAME || providerID !== "anthropic" && providerID !== "openai") && (procEnv2.OPENAI_API_KEY || procEnv2.OPENAI_BASE_URL)) {
1005
+ const openAICompatibleProviderID = procEnv2.OPENAI_NAME ?? providerID;
1006
+ return {
1007
+ [openAICompatibleProviderID]: {
1008
+ options: {
1009
+ ...procEnv2.OPENAI_API_KEY ? { apiKey: procEnv2.OPENAI_API_KEY } : {},
1010
+ ...procEnv2.OPENAI_BASE_URL ? { baseURL: procEnv2.OPENAI_BASE_URL } : {},
1011
+ ...parseOpenAIQueryParams()
1012
+ },
1013
+ ...modelID ? {
1014
+ models: {
1015
+ [modelID]: { id: modelID, name: modelID }
1016
+ }
1017
+ } : {}
1018
+ }
1019
+ };
1020
+ }
1021
+ if (providerID === "anthropic" && (procEnv2.ANTHROPIC_API_KEY || procEnv2.ANTHROPIC_AUTH_TOKEN || procEnv2.ANTHROPIC_BASE_URL)) {
1022
+ return {
1023
+ anthropic: {
1024
+ options: {
1025
+ ...procEnv2.ANTHROPIC_API_KEY ? { apiKey: procEnv2.ANTHROPIC_API_KEY } : {},
1026
+ ...procEnv2.ANTHROPIC_AUTH_TOKEN ? { authToken: procEnv2.ANTHROPIC_AUTH_TOKEN } : {},
1027
+ ...procEnv2.ANTHROPIC_BASE_URL ? { baseURL: procEnv2.ANTHROPIC_BASE_URL } : {}
1028
+ }
1029
+ }
1030
+ };
1031
+ }
1032
+ if (providerID === "openai" && (procEnv2.OPENAI_API_KEY || procEnv2.OPENAI_BASE_URL)) {
1033
+ return {
1034
+ openai: {
1035
+ options: {
1036
+ ...procEnv2.OPENAI_API_KEY ? { apiKey: procEnv2.OPENAI_API_KEY } : {},
1037
+ ...procEnv2.OPENAI_BASE_URL ? { baseURL: procEnv2.OPENAI_BASE_URL } : {},
1038
+ ...procEnv2.OPENAI_ORGANIZATION ? { organization: procEnv2.OPENAI_ORGANIZATION } : {},
1039
+ ...procEnv2.OPENAI_PROJECT ? { project: procEnv2.OPENAI_PROJECT } : {},
1040
+ ...parseOpenAIQueryParams()
1041
+ }
1042
+ }
1043
+ };
1044
+ }
1045
+ return void 0;
1046
+ }
1047
+ function parseOpenAIQueryParams() {
1048
+ if (!procEnv2.OPENAI_QUERY_PARAMS_JSON) return {};
1049
+ try {
1050
+ const parsed = JSON.parse(procEnv2.OPENAI_QUERY_PARAMS_JSON);
1051
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1052
+ return { queryParams: parsed };
1053
+ }
1054
+ } catch {
1055
+ }
1056
+ return {};
1057
+ }
1058
+ function toOpenCodeGatewayBaseUrl(baseUrl) {
1059
+ const trimmed = baseUrl.replace(/\/+$/, "");
1060
+ return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
1061
+ }
1062
+ async function legacySessionGet({
1063
+ client,
1064
+ sessionId
1065
+ }) {
1066
+ const session = client.session;
1067
+ if (!session?.get) return client.v2.session.get({ sessionID: sessionId });
1068
+ return session.get({ sessionID: sessionId });
1069
+ }
1070
+ async function legacySessionCreate({
1071
+ client
1072
+ }) {
1073
+ return client.session.create({});
1074
+ }
1075
+ async function legacySessionPrompt({
1076
+ client,
1077
+ sessionId,
1078
+ start
1079
+ }) {
1080
+ const session = client.session;
1081
+ const prompt = session.promptAsync ?? session.prompt;
1082
+ return prompt.call(session, {
1083
+ sessionID: sessionId,
1084
+ ...start.instructions ? { system: start.instructions } : {},
1085
+ ...start.variant ? { variant: start.variant } : {},
1086
+ parts: [{ type: "text", text: start.prompt }]
1087
+ });
1088
+ }
1089
+ async function legacySessionSummarize({
1090
+ client,
1091
+ sessionId,
1092
+ model
1093
+ }) {
1094
+ return client.session.summarize({
1095
+ sessionID: sessionId,
1096
+ auto: false,
1097
+ providerID: model.providerID,
1098
+ modelID: model.modelID
1099
+ });
1100
+ }
1101
+ async function subscribeLegacyEvents({
1102
+ client,
1103
+ signal
1104
+ }) {
1105
+ const subscribed = await client.event.subscribe(void 0, {
1106
+ signal,
1107
+ sseMaxRetryAttempts: 0
1108
+ });
1109
+ return getEventStream(subscribed);
1110
+ }
1111
+ function readSessionId(data) {
1112
+ if (!data || typeof data !== "object") return void 0;
1113
+ const record = data;
1114
+ if (typeof record.id === "string") return record.id;
1115
+ if (typeof record.data?.id === "string") return record.data.id;
1116
+ return void 0;
1117
+ }
1118
+ function isAsyncIterable(value) {
1119
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
1120
+ }
1121
+ function getEventStream(source) {
1122
+ if (!source || typeof source !== "object") return null;
1123
+ const candidate = source;
1124
+ if (isAsyncIterable(candidate.stream)) return candidate.stream;
1125
+ if (isAsyncIterable(candidate.data)) return candidate.data;
1126
+ return null;
1127
+ }
1128
+ function legacyStatusType(event) {
1129
+ const status = event.properties?.status;
1130
+ return status && typeof status === "object" ? String(status.type ?? "") : void 0;
1131
+ }
1132
+ function legacyRetryStatusMessage(event) {
1133
+ const status = event.properties?.status;
1134
+ const details = [];
1135
+ if (status && typeof status === "object") {
1136
+ const retryStatus = status;
1137
+ if (typeof retryStatus.attempt === "number") {
1138
+ details.push(`attempt ${retryStatus.attempt}`);
1139
+ }
1140
+ if (typeof retryStatus.message === "string" && retryStatus.message.trim()) {
1141
+ details.push(retryStatus.message.trim());
1142
+ }
1143
+ }
1144
+ return details.length > 0 ? `OpenCode session retry: ${details.join("; ")}` : "OpenCode session retry";
1145
+ }
1146
+ function nextRetryEventMessage(event) {
1147
+ const props = event.properties ?? {};
1148
+ const details = [];
1149
+ if (typeof props.attempt === "number") {
1150
+ details.push(`attempt ${props.attempt}`);
1151
+ }
1152
+ const error = props.error;
1153
+ if (isRecord2(error)) {
1154
+ const message = stringValue(error.message) ?? (isRecord2(error.data) ? stringValue(error.data.message) : void 0);
1155
+ const statusCode = error.statusCode;
1156
+ if (typeof statusCode === "number") {
1157
+ details.push(`HTTP ${statusCode}`);
1158
+ }
1159
+ if (message) details.push(message);
1160
+ } else if (error != null) {
1161
+ details.push(formatError(error));
1162
+ }
1163
+ return details.length > 0 ? `OpenCode session retry: ${details.join("; ")}` : "OpenCode session retry";
1164
+ }
1165
+ async function ensureSession({
1166
+ client,
1167
+ start,
1168
+ emit
1169
+ }) {
1170
+ if (runtime.sessionId) return runtime.sessionId;
1171
+ if (start.resumeSessionId) {
1172
+ const existing = await legacySessionGet({
1173
+ client,
1174
+ sessionId: start.resumeSessionId
1175
+ }).catch(() => void 0);
1176
+ if (existing && !existing.error) {
1177
+ runtime.sessionId = start.resumeSessionId;
1178
+ emit({ type: "bridge-thread", threadId: runtime.sessionId });
1179
+ return runtime.sessionId;
1180
+ }
1181
+ }
1182
+ const created = await legacySessionCreate({ client });
1183
+ if (created.error) {
1184
+ throw new Error(
1185
+ `OpenCode session create failed: ${formatError(created.error)}`
1186
+ );
1187
+ }
1188
+ const id = readSessionId(created.data);
1189
+ if (!id) throw new Error("OpenCode session create returned no id.");
1190
+ runtime.sessionId = id;
1191
+ emit({ type: "bridge-thread", threadId: id });
1192
+ return id;
1193
+ }
1194
+ async function runPrompt({
1195
+ client,
1196
+ sessionId,
1197
+ start,
1198
+ turn,
1199
+ emit
1200
+ }) {
1201
+ const eventsAbort = new AbortController();
1202
+ const turnSettled = createDeferred();
1203
+ let sawContent = false;
1204
+ let sawFinishStep = false;
1205
+ let sawBusy = false;
1206
+ let terminalError;
1207
+ const initialSessionTokens = await readSessionTokens({
1208
+ client,
1209
+ sessionId
1210
+ }).catch(() => void 0);
1211
+ const eventsReady = createDeferred();
1212
+ let stepUsage;
1213
+ let latestSessionTokens;
1214
+ const eventLoop = consumeEvents({
1215
+ client,
1216
+ sessionId,
1217
+ permissionMode: start.permissionMode,
1218
+ builtinToolFiltering: start.builtinToolFiltering,
1219
+ turn,
1220
+ emit: (msg) => {
1221
+ if (msg.type === "text-delta" || msg.type === "reasoning-delta") {
1222
+ sawContent = true;
1223
+ }
1224
+ if (msg.type === "finish-step") {
1225
+ sawFinishStep = true;
1226
+ stepUsage = addUsage({
1227
+ left: stepUsage,
1228
+ right: msg.usage
1229
+ });
1230
+ }
1231
+ emit(msg);
1232
+ },
1233
+ signal: eventsAbort.signal,
1234
+ onSubscribed: () => eventsReady.resolve(void 0),
1235
+ onEvent: (event) => {
1236
+ if (event.type === "session.updated") {
1237
+ latestSessionTokens = extractSessionTokens(event.properties) ?? latestSessionTokens;
1238
+ }
1239
+ if (isStepSettlementEvent(event)) {
1240
+ turnSettled.resolve();
1241
+ return true;
1242
+ }
1243
+ const status = legacyStatusType(event);
1244
+ if (status === "busy") {
1245
+ sawBusy = true;
1246
+ } else if (status === "retry") {
1247
+ sawBusy = true;
1248
+ turn.emitWarning({ message: legacyRetryStatusMessage(event) });
1249
+ } else if (sawBusy && status === "idle") {
1250
+ turnSettled.resolve();
1251
+ return true;
1252
+ }
1253
+ if (event.type === "session.error") {
1254
+ terminalError = formatError(event.properties?.error ?? event);
1255
+ turnSettled.resolve();
1256
+ return true;
1257
+ }
1258
+ }
1259
+ }).finally(() => {
1260
+ eventsReady.resolve(void 0);
1261
+ turnSettled.resolve();
1262
+ });
1263
+ emit({
1264
+ type: "stream-start",
1265
+ ...start.model ? { modelId: start.model } : {}
1266
+ });
1267
+ await eventsReady.promise;
1268
+ const prompted = await legacySessionPrompt({
1269
+ client,
1270
+ sessionId,
1271
+ start
1272
+ });
1273
+ if (prompted.error) {
1274
+ eventsAbort.abort();
1275
+ throw new Error(`OpenCode prompt failed: ${formatError(prompted.error)}`);
1276
+ }
1277
+ await turnSettled.promise;
1278
+ eventsAbort.abort();
1279
+ await eventLoop.catch(() => {
1280
+ });
1281
+ if (terminalError) throw new Error(terminalError);
1282
+ if (!sawFinishStep) {
1283
+ const emittedFallback = await emitContextFallback({
1284
+ client,
1285
+ sessionId,
1286
+ emit,
1287
+ emitContent: !sawContent
1288
+ }).catch(() => false);
1289
+ if (!emittedFallback) {
1290
+ emit({
1291
+ type: "finish-step",
1292
+ finishReason: { unified: "stop", raw: "stop" },
1293
+ usage: defaultUsage(),
1294
+ harnessMetadata: { opencode: { fallback: true, missingContext: true } }
1295
+ });
1296
+ }
1297
+ }
1298
+ const finalSessionTokens = await readSessionTokens({ client, sessionId }).catch(() => void 0) ?? latestSessionTokens;
1299
+ if (initialSessionTokens && finalSessionTokens) {
1300
+ return mapUsage(
1301
+ subtractSessionTokens({
1302
+ before: initialSessionTokens,
1303
+ after: finalSessionTokens
1304
+ })
1305
+ );
1306
+ }
1307
+ return stepUsage;
1308
+ }
1309
+ async function runCompaction({
1310
+ client,
1311
+ sessionId,
1312
+ start,
1313
+ turn,
1314
+ emit
1315
+ }) {
1316
+ const eventsAbort = new AbortController();
1317
+ const compactionSettled = createDeferred();
1318
+ let sawCompaction = false;
1319
+ let sawBusy = false;
1320
+ let terminalError;
1321
+ const model = await resolveCompactionModel({
1322
+ client,
1323
+ sessionId,
1324
+ start
1325
+ });
1326
+ if (!model) {
1327
+ throw new Error(
1328
+ "OpenCode compaction requires a previous turn or an explicit model."
1329
+ );
1330
+ }
1331
+ const eventLoop = consumeEvents({
1332
+ client,
1333
+ sessionId,
1334
+ permissionMode: start.permissionMode,
1335
+ builtinToolFiltering: start.builtinToolFiltering,
1336
+ turn,
1337
+ emit: (msg) => {
1338
+ if (msg.type === "compaction") sawCompaction = true;
1339
+ emit(msg);
1340
+ },
1341
+ signal: eventsAbort.signal,
1342
+ onEvent: (event) => {
1343
+ if (event.type === "session.next.compaction.ended" || event.type === "session.compacted") {
1344
+ compactionSettled.resolve();
1345
+ return true;
1346
+ }
1347
+ const status = legacyStatusType(event);
1348
+ if (status === "busy") {
1349
+ sawBusy = true;
1350
+ } else if (status === "retry") {
1351
+ sawBusy = true;
1352
+ turn.emitWarning({ message: legacyRetryStatusMessage(event) });
1353
+ } else if (sawBusy && status === "idle") {
1354
+ compactionSettled.resolve();
1355
+ return true;
1356
+ }
1357
+ if (event.type === "session.error") {
1358
+ terminalError = formatError(event.properties?.error ?? event);
1359
+ compactionSettled.resolve();
1360
+ return true;
1361
+ }
1362
+ }
1363
+ });
1364
+ const compacted = await legacySessionSummarize({
1365
+ client,
1366
+ sessionId,
1367
+ model
1368
+ });
1369
+ if (compacted.error) {
1370
+ eventsAbort.abort();
1371
+ throw new Error(
1372
+ `OpenCode compaction failed: ${formatError(compacted.error)}`
1373
+ );
1374
+ }
1375
+ await Promise.race([compactionSettled.promise, sleep(250)]);
1376
+ eventsAbort.abort();
1377
+ await eventLoop.catch(() => {
1378
+ });
1379
+ if (terminalError) throw new Error(terminalError);
1380
+ if (!sawCompaction) {
1381
+ emit({
1382
+ type: "compaction",
1383
+ trigger: "manual",
1384
+ summary: "",
1385
+ harnessMetadata: {
1386
+ opencode: { missingSummary: true }
1387
+ }
1388
+ });
1389
+ }
1390
+ }
1391
+ async function consumeEvents({
1392
+ client,
1393
+ sessionId,
1394
+ permissionMode,
1395
+ builtinToolFiltering,
1396
+ turn,
1397
+ emit,
1398
+ signal,
1399
+ onSubscribed,
1400
+ onEvent
1401
+ }) {
1402
+ const stream = await subscribeLegacyEvents({ client, signal });
1403
+ onSubscribed?.();
1404
+ if (!stream) return;
1405
+ const state = createTranslationState();
1406
+ for await (const rawEvent of stream) {
1407
+ if (signal.aborted || turn.abortSignal.aborted) break;
1408
+ const event = unwrapOpenCodeEvent(rawEvent);
1409
+ const eventSessionId = event ? getOpenCodeEventSessionId(event) : void 0;
1410
+ if (!event || eventSessionId && eventSessionId !== sessionId) continue;
1411
+ await translateAndEmit({
1412
+ event,
1413
+ state,
1414
+ sessionId,
1415
+ permissionMode,
1416
+ builtinToolFiltering,
1417
+ client,
1418
+ turn,
1419
+ emit
1420
+ });
1421
+ if (onEvent?.(event)) break;
1422
+ }
1423
+ }
1424
+ function createTranslationState() {
1425
+ return {
1426
+ textDeltas: /* @__PURE__ */ new Map(),
1427
+ reasoningDeltas: /* @__PURE__ */ new Map(),
1428
+ toolInputs: /* @__PURE__ */ new Map(),
1429
+ toolNames: /* @__PURE__ */ new Map(),
1430
+ toolCallsEmitted: /* @__PURE__ */ new Set(),
1431
+ toolResultsEmitted: /* @__PURE__ */ new Set(),
1432
+ hostToolCallsAuthorized: /* @__PURE__ */ new Set(),
1433
+ shellCommands: /* @__PURE__ */ new Map(),
1434
+ messageRoles: /* @__PURE__ */ new Map(),
1435
+ turnUsage: void 0,
1436
+ legacyTextPartIds: /* @__PURE__ */ new Set(),
1437
+ legacyReasoningPartIds: /* @__PURE__ */ new Set(),
1438
+ legacyStepFinishPartIds: /* @__PURE__ */ new Set()
1439
+ };
1440
+ }
1441
+ async function translateAndEmit({
1442
+ event,
1443
+ state,
1444
+ sessionId,
1445
+ permissionMode,
1446
+ builtinToolFiltering,
1447
+ client,
1448
+ turn,
1449
+ emit
1450
+ }) {
1451
+ const type = event.type;
1452
+ const props = event.properties ?? {};
1453
+ if (type === "message.updated") {
1454
+ const info = props.info;
1455
+ if (isRecord2(info)) {
1456
+ const id = stringValue(info.id);
1457
+ const role = stringValue(info.role);
1458
+ if (id && role) state.messageRoles.set(id, role);
1459
+ }
1460
+ return;
1461
+ }
1462
+ if (type === "message.part.delta") {
1463
+ const field = String(props.field ?? "");
1464
+ const delta = String(props.delta ?? "");
1465
+ if (!delta) return;
1466
+ const messageID = stringValue(props.messageID);
1467
+ if (messageID && state.messageRoles.get(messageID) === "user") return;
1468
+ if (field === "text") {
1469
+ const id = legacyPartId({ value: props, fallback: "legacy-text" });
1470
+ startLegacyPart({ ids: state.legacyTextPartIds, id, emit, type: "text" });
1471
+ state.textDeltas.set(id, `${state.textDeltas.get(id) ?? ""}${delta}`);
1472
+ emit({ type: "text-delta", id, delta });
1473
+ return;
1474
+ }
1475
+ if (field === "reasoning") {
1476
+ const id = legacyPartId({ value: props, fallback: "legacy-reasoning" });
1477
+ startLegacyPart({
1478
+ ids: state.legacyReasoningPartIds,
1479
+ id,
1480
+ emit,
1481
+ type: "reasoning"
1482
+ });
1483
+ state.reasoningDeltas.set(
1484
+ id,
1485
+ `${state.reasoningDeltas.get(id) ?? ""}${delta}`
1486
+ );
1487
+ emit({ type: "reasoning-delta", id, delta });
1488
+ }
1489
+ return;
1490
+ }
1491
+ if (type === "message.part.updated") {
1492
+ if (emitLegacyTextPartUpdate({ part: props.part, state, emit })) return;
1493
+ if (emitLegacyStepFinishPart({ part: props.part, state, emit })) return;
1494
+ emitLegacyToolPart({ part: props.part, state, emit });
1495
+ return;
1496
+ }
1497
+ if (type === "session.next.text.started") {
1498
+ emit({ type: "text-start", id: String(props.textID ?? event.id) });
1499
+ return;
1500
+ }
1501
+ if (type === "session.next.text.delta") {
1502
+ const id = String(props.textID ?? event.id);
1503
+ state.textDeltas.set(
1504
+ id,
1505
+ `${state.textDeltas.get(id) ?? ""}${String(props.delta ?? "")}`
1506
+ );
1507
+ emit({
1508
+ type: "text-delta",
1509
+ id,
1510
+ delta: String(props.delta ?? "")
1511
+ });
1512
+ return;
1513
+ }
1514
+ if (type === "session.next.text.ended") {
1515
+ const id = String(props.textID ?? event.id);
1516
+ emitMissingFinalDelta({
1517
+ id,
1518
+ fullText: typeof props.text === "string" ? props.text : void 0,
1519
+ emittedText: state.textDeltas.get(id) ?? "",
1520
+ emit,
1521
+ type: "text-delta"
1522
+ });
1523
+ emit({ type: "text-end", id });
1524
+ return;
1525
+ }
1526
+ if (type === "session.next.reasoning.started") {
1527
+ emit({
1528
+ type: "reasoning-start",
1529
+ id: String(props.reasoningID ?? event.id)
1530
+ });
1531
+ return;
1532
+ }
1533
+ if (type === "session.next.reasoning.delta") {
1534
+ const id = String(props.reasoningID ?? event.id);
1535
+ state.reasoningDeltas.set(
1536
+ id,
1537
+ `${state.reasoningDeltas.get(id) ?? ""}${String(props.delta ?? "")}`
1538
+ );
1539
+ emit({
1540
+ type: "reasoning-delta",
1541
+ id,
1542
+ delta: String(props.delta ?? "")
1543
+ });
1544
+ return;
1545
+ }
1546
+ if (type === "session.next.reasoning.ended") {
1547
+ const id = String(props.reasoningID ?? event.id);
1548
+ emitMissingFinalDelta({
1549
+ id,
1550
+ fullText: typeof props.text === "string" ? props.text : void 0,
1551
+ emittedText: state.reasoningDeltas.get(id) ?? "",
1552
+ emit,
1553
+ type: "reasoning-delta"
1554
+ });
1555
+ emit({ type: "reasoning-end", id });
1556
+ return;
1557
+ }
1558
+ if (type === "session.next.shell.started") {
1559
+ const callID = String(props.callID ?? event.id);
1560
+ const command = String(props.command ?? "");
1561
+ state.shellCommands.set(callID, command);
1562
+ emit({
1563
+ type: "tool-call",
1564
+ toolCallId: callID,
1565
+ toolName: "bash",
1566
+ nativeName: "bash",
1567
+ input: JSON.stringify({ command }),
1568
+ providerExecuted: true
1569
+ });
1570
+ return;
1571
+ }
1572
+ if (type === "session.next.shell.ended") {
1573
+ const callID = String(props.callID ?? event.id);
1574
+ emit({
1575
+ type: "tool-result",
1576
+ toolCallId: callID,
1577
+ toolName: "bash",
1578
+ result: {
1579
+ command: state.shellCommands.get(callID) ?? "",
1580
+ output: String(props.output ?? "")
1581
+ }
1582
+ });
1583
+ return;
1584
+ }
1585
+ if (type === "session.next.tool.input.delta") {
1586
+ const callID = String(props.callID ?? event.id);
1587
+ state.toolInputs.set(
1588
+ callID,
1589
+ `${state.toolInputs.get(callID) ?? ""}${String(props.delta ?? "")}`
1590
+ );
1591
+ return;
1592
+ }
1593
+ if (type === "session.next.tool.input.ended") {
1594
+ state.toolInputs.set(
1595
+ String(props.callID ?? event.id),
1596
+ String(props.text ?? "")
1597
+ );
1598
+ return;
1599
+ }
1600
+ if (type === "session.next.tool.called") {
1601
+ const callID = String(props.callID ?? event.id);
1602
+ const rawToolName = String(props.tool ?? "unknown");
1603
+ const toolName = toWireToolName(rawToolName);
1604
+ state.toolNames.set(callID, { rawToolName, toolName });
1605
+ const hostToolName = getHostToolName(toolName, props.tool);
1606
+ if (hostToolName) {
1607
+ authorizeHostToolCall({
1608
+ callID,
1609
+ toolName: hostToolName,
1610
+ input: props.input ?? parseToolInput(state, props),
1611
+ state
1612
+ });
1613
+ return;
1614
+ }
1615
+ emit({
1616
+ type: "tool-call",
1617
+ toolCallId: callID,
1618
+ toolName,
1619
+ ...nativeNameField({ nativeName: rawToolName, toolName }),
1620
+ input: JSON.stringify(props.input ?? parseToolInput(state, props)),
1621
+ providerExecuted: true,
1622
+ ...props.provider?.metadata ? { providerMetadata: props.provider.metadata } : {}
1623
+ });
1624
+ return;
1625
+ }
1626
+ if (type === "session.next.tool.success" || type === "session.next.tool.failed") {
1627
+ const callID = String(props.callID ?? event.id);
1628
+ const cachedTool = state.toolNames.get(callID);
1629
+ const rawToolName = cachedTool?.rawToolName ?? String(props.tool ?? "");
1630
+ const toolName = cachedTool?.toolName ?? toWireToolName(rawToolName || "unknown");
1631
+ if (getHostToolName(toolName, rawToolName)) return;
1632
+ emit({
1633
+ type: "tool-result",
1634
+ toolCallId: callID,
1635
+ toolName,
1636
+ result: props.result ?? props.structured ?? ("content" in props ? props.content : null) ?? null,
1637
+ ...type === "session.next.tool.failed" ? { isError: true } : {}
1638
+ });
1639
+ return;
1640
+ }
1641
+ if (type === "session.next.retried") {
1642
+ const error = props.error ?? event;
1643
+ if (isRecord2(error) && error.isRetryable === false) {
1644
+ turn.emitError({
1645
+ error,
1646
+ message: "OpenCode session retry failed"
1647
+ });
1648
+ } else {
1649
+ turn.emitWarning({ message: nextRetryEventMessage(event) });
1650
+ }
1651
+ return;
1652
+ }
1653
+ if (type === "session.next.step.ended") {
1654
+ closeLegacyOpenParts({ state, emit });
1655
+ state.turnUsage = mapUsage(props.tokens);
1656
+ emit({
1657
+ type: "finish-step",
1658
+ finishReason: {
1659
+ unified: mapOpenCodeFinishReason(String(props.finish ?? "stop")),
1660
+ raw: String(props.finish ?? "stop")
1661
+ },
1662
+ usage: state.turnUsage,
1663
+ ...typeof props.cost === "number" ? { harnessMetadata: { opencode: { cost: props.cost } } } : {}
1664
+ });
1665
+ return;
1666
+ }
1667
+ if (type === "session.next.compaction.ended") {
1668
+ emit({
1669
+ type: "compaction",
1670
+ trigger: props.reason === "auto" ? "auto" : "manual",
1671
+ summary: String(props.text ?? ""),
1672
+ harnessMetadata: {
1673
+ opencode: {
1674
+ recent: String(props.recent ?? "")
1675
+ }
1676
+ }
1677
+ });
1678
+ return;
1679
+ }
1680
+ if (type === "file.edited") {
1681
+ emit({
1682
+ type: "file-change",
1683
+ event: "modify",
1684
+ path: stripWorkDir(String(props.file ?? ""))
1685
+ });
1686
+ return;
1687
+ }
1688
+ if (type === "session.error" || type === "session.next.step.failed") {
1689
+ const error = props.error ?? event;
1690
+ turn.emitError({
1691
+ error,
1692
+ message: type === "session.error" ? "OpenCode session error" : "OpenCode step failed"
1693
+ });
1694
+ return;
1695
+ }
1696
+ if (type === "permission.v2.asked") {
1697
+ await handlePermissionV2({
1698
+ client,
1699
+ sessionId,
1700
+ permissionMode,
1701
+ builtinToolFiltering,
1702
+ turn,
1703
+ emit,
1704
+ event
1705
+ });
1706
+ return;
1707
+ }
1708
+ if (type === "permission.asked") {
1709
+ await handlePermission({
1710
+ client,
1711
+ sessionId,
1712
+ permissionMode,
1713
+ builtinToolFiltering,
1714
+ turn,
1715
+ emit,
1716
+ event
1717
+ });
1718
+ }
1719
+ }
1720
+ function legacyPartId({
1721
+ value,
1722
+ fallback
1723
+ }) {
1724
+ return stringValue(value.partID) ?? stringValue(value.id) ?? fallback;
1725
+ }
1726
+ function startLegacyPart({
1727
+ ids,
1728
+ id,
1729
+ emit,
1730
+ type
1731
+ }) {
1732
+ if (ids.has(id)) return;
1733
+ ids.add(id);
1734
+ emit({ type: `${type}-start`, id });
1735
+ }
1736
+ function emitLegacyTextPartUpdate({
1737
+ part,
1738
+ state,
1739
+ emit
1740
+ }) {
1741
+ if (!isRecord2(part)) return false;
1742
+ if (part.type !== "text" && part.type !== "reasoning") return false;
1743
+ const id = stringValue(part.id);
1744
+ if (!id) return true;
1745
+ const messageID = stringValue(part.messageID);
1746
+ if (messageID && state.messageRoles.get(messageID) === "user") return true;
1747
+ const isReasoning = part.type === "reasoning";
1748
+ const ids = isReasoning ? state.legacyReasoningPartIds : state.legacyTextPartIds;
1749
+ const deltaMap = isReasoning ? state.reasoningDeltas : state.textDeltas;
1750
+ const deltaType = isReasoning ? "reasoning-delta" : "text-delta";
1751
+ const text = typeof part.text === "string" ? part.text : void 0;
1752
+ startLegacyPart({
1753
+ ids,
1754
+ id,
1755
+ emit,
1756
+ type: isReasoning ? "reasoning" : "text"
1757
+ });
1758
+ if (text !== void 0) {
1759
+ emitMissingFinalDelta({
1760
+ id,
1761
+ fullText: text,
1762
+ emittedText: deltaMap.get(id) ?? "",
1763
+ emit,
1764
+ type: deltaType
1765
+ });
1766
+ deltaMap.set(id, text);
1767
+ }
1768
+ if (legacyPartEnded(part)) {
1769
+ ids.delete(id);
1770
+ deltaMap.delete(id);
1771
+ emit({ type: isReasoning ? "reasoning-end" : "text-end", id });
1772
+ }
1773
+ return true;
1774
+ }
1775
+ function legacyPartEnded(part) {
1776
+ return isRecord2(part.time) && part.time.end != null;
1777
+ }
1778
+ function closeLegacyOpenParts({
1779
+ state,
1780
+ emit
1781
+ }) {
1782
+ for (const id of state.legacyReasoningPartIds) {
1783
+ emit({ type: "reasoning-end", id });
1784
+ state.reasoningDeltas.delete(id);
1785
+ }
1786
+ state.legacyReasoningPartIds.clear();
1787
+ for (const id of state.legacyTextPartIds) {
1788
+ emit({ type: "text-end", id });
1789
+ state.textDeltas.delete(id);
1790
+ }
1791
+ state.legacyTextPartIds.clear();
1792
+ }
1793
+ function emitLegacyStepFinishPart({
1794
+ part,
1795
+ state,
1796
+ emit
1797
+ }) {
1798
+ const event = legacyStepFinishPartToFinishStep(part);
1799
+ if (!event) return false;
1800
+ const id = isRecord2(part) ? stringValue(part.id) : void 0;
1801
+ if (id) {
1802
+ if (state.legacyStepFinishPartIds.has(id)) return true;
1803
+ state.legacyStepFinishPartIds.add(id);
1804
+ }
1805
+ closeLegacyOpenParts({ state, emit });
1806
+ state.turnUsage = event.usage;
1807
+ emit(event);
1808
+ return true;
1809
+ }
1810
+ function emitLegacyToolPart({
1811
+ part,
1812
+ state,
1813
+ emit
1814
+ }) {
1815
+ if (!part || typeof part !== "object") return;
1816
+ const toolPart = part;
1817
+ if (toolPart.type !== "tool") return;
1818
+ const status = legacyToolPartStatus(toolPart);
1819
+ if (status !== "running" && status !== "completed" && status !== "error") {
1820
+ return;
1821
+ }
1822
+ if (typeof toolPart.tool !== "string" || typeof toolPart.callID !== "string") {
1823
+ return;
1824
+ }
1825
+ const callID = toolPart.callID;
1826
+ const rawToolName = toolPart.tool;
1827
+ const toolName = toWireToolName(rawToolName);
1828
+ state.toolNames.set(callID, { rawToolName, toolName });
1829
+ const hostToolName = getHostToolName(toolName, rawToolName);
1830
+ if (hostToolName) {
1831
+ if (status === "running") {
1832
+ authorizeHostToolCall({
1833
+ callID,
1834
+ toolName: hostToolName,
1835
+ input: legacyToolPartInput(toolPart),
1836
+ state
1837
+ });
1838
+ }
1839
+ return;
1840
+ }
1841
+ if (!state.toolCallsEmitted.has(callID)) {
1842
+ state.toolCallsEmitted.add(callID);
1843
+ emit({
1844
+ type: "tool-call",
1845
+ toolCallId: callID,
1846
+ toolName,
1847
+ ...nativeNameField({ nativeName: rawToolName, toolName }),
1848
+ input: JSON.stringify(legacyToolPartInput(toolPart)),
1849
+ providerExecuted: true,
1850
+ ...toolPart.provider?.metadata ? { providerMetadata: toolPart.provider.metadata } : {}
1851
+ });
1852
+ }
1853
+ if ((status === "completed" || status === "error") && !state.toolResultsEmitted.has(callID)) {
1854
+ state.toolResultsEmitted.add(callID);
1855
+ emit({
1856
+ type: "tool-result",
1857
+ toolCallId: callID,
1858
+ toolName,
1859
+ result: legacyToolPartOutput(toolPart),
1860
+ ...status === "error" ? { isError: true } : {}
1861
+ });
1862
+ }
1863
+ }
1864
+ function legacyToolPartStatus(part) {
1865
+ return typeof part.state === "string" ? part.state : typeof part.state === "object" && part.state !== null ? String(part.state.status ?? "") : void 0;
1866
+ }
1867
+ function legacyToolPartInput(part) {
1868
+ const state = typeof part.state === "object" && part.state !== null ? part.state : void 0;
1869
+ return {
1870
+ ...isRecord2(part.metadata) ? part.metadata : {},
1871
+ ...isRecord2(state?.metadata) ? state.metadata : {},
1872
+ ...isRecord2(state?.input) ? state.input : {}
1873
+ };
1874
+ }
1875
+ function legacyToolPartOutput(part) {
1876
+ const state = typeof part.state === "object" && part.state !== null ? part.state : void 0;
1877
+ if (state?.status === "error") {
1878
+ return state.error ?? part.error ?? state.result ?? "tool failed";
1879
+ }
1880
+ return state?.output ?? state?.result ?? state?.structured ?? state?.content ?? null;
1881
+ }
1882
+ function isRecord2(value) {
1883
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
1884
+ }
1885
+ function parseToolInput(state, props) {
1886
+ const text = state.toolInputs.get(String(props.callID ?? ""));
1887
+ if (!text) return {};
1888
+ try {
1889
+ return JSON.parse(text);
1890
+ } catch {
1891
+ return { input: text };
1892
+ }
1893
+ }
1894
+ async function handlePermissionV2({
1895
+ client,
1896
+ sessionId,
1897
+ permissionMode,
1898
+ builtinToolFiltering,
1899
+ turn,
1900
+ emit,
1901
+ event
1902
+ }) {
1903
+ const props = event.properties ?? {};
1904
+ const requestID = String(props.id ?? "");
1905
+ if (!requestID) return;
1906
+ const reply = await selectPermissionReply({
1907
+ action: String(props.action ?? ""),
1908
+ resources: Array.isArray(props.resources) ? props.resources.map(String) : [],
1909
+ requestID,
1910
+ toolCallId: typeof props.source === "object" && props.source !== null && "callID" in props.source ? String(props.source.callID) : requestID,
1911
+ permissionMode,
1912
+ builtinToolFiltering,
1913
+ turn,
1914
+ emit
1915
+ });
1916
+ await client.v2.session.permission.reply({
1917
+ sessionID: sessionId,
1918
+ requestID,
1919
+ reply: reply.reply,
1920
+ ...reply.message ? { message: reply.message } : {}
1921
+ });
1922
+ }
1923
+ async function handlePermission({
1924
+ client,
1925
+ sessionId,
1926
+ permissionMode,
1927
+ builtinToolFiltering,
1928
+ turn,
1929
+ emit,
1930
+ event
1931
+ }) {
1932
+ const props = event.properties ?? {};
1933
+ const requestID = String(props.id ?? "");
1934
+ if (!requestID) return;
1935
+ const reply = await selectPermissionReply({
1936
+ action: String(props.permission ?? ""),
1937
+ resources: Array.isArray(props.patterns) ? props.patterns.map(String) : [],
1938
+ requestID,
1939
+ toolCallId: typeof props.tool === "object" && props.tool !== null && "callID" in props.tool ? String(props.tool.callID) : requestID,
1940
+ permissionMode,
1941
+ builtinToolFiltering,
1942
+ turn,
1943
+ emit
1944
+ });
1945
+ await client.permission.reply({
1946
+ requestID,
1947
+ directory: workdir,
1948
+ reply: reply.reply,
1949
+ ...reply.message ? { message: reply.message } : {}
1950
+ });
1951
+ void sessionId;
1952
+ }
1953
+ async function selectPermissionReply({
1954
+ action,
1955
+ resources,
1956
+ requestID,
1957
+ toolCallId,
1958
+ permissionMode,
1959
+ builtinToolFiltering,
1960
+ turn,
1961
+ emit
1962
+ }) {
1963
+ const toolName = toPermissionToolName(action);
1964
+ if (resources.some((resource) => isExternalPath(resource))) {
1965
+ return { reply: "reject", message: "External directory access rejected." };
1966
+ }
1967
+ if (isBuiltinToolInactive({ toolName, toolFiltering: builtinToolFiltering })) {
1968
+ emit({
1969
+ type: "tool-approval-request",
1970
+ approvalId: requestID,
1971
+ toolCallId
1972
+ });
1973
+ const decision2 = await turn.requestToolApproval(requestID);
1974
+ return decision2.approved ? { reply: "once" } : {
1975
+ reply: "reject",
1976
+ ...decision2.reason ? { message: decision2.reason } : {}
1977
+ };
1978
+ }
1979
+ if (!permissionMode || permissionMode === "allow-all") {
1980
+ return { reply: "always" };
1981
+ }
1982
+ const kind = TOOL_KIND[toolName] ?? "bash";
1983
+ const allowed = permissionMode === "allow-edits" ? kind === "readonly" || kind === "edit" : kind === "readonly";
1984
+ if (allowed) return { reply: "always" };
1985
+ emit({
1986
+ type: "tool-approval-request",
1987
+ approvalId: requestID,
1988
+ toolCallId
1989
+ });
1990
+ const decision = await turn.requestToolApproval(requestID);
1991
+ return decision.approved ? { reply: "once" } : {
1992
+ reply: "reject",
1993
+ ...decision.reason ? { message: decision.reason } : {}
1994
+ };
1995
+ }
1996
+ function toPermissionToolName(action) {
1997
+ const normalized = action.toLowerCase();
1998
+ if (normalized.includes("bash") || normalized.includes("shell"))
1999
+ return "bash";
2000
+ if (normalized.includes("edit")) return "edit";
2001
+ if (normalized.includes("write")) return "write";
2002
+ if (normalized.includes("webfetch")) return "webfetch";
2003
+ if (normalized.includes("task") || normalized.includes("agent"))
2004
+ return "agent";
2005
+ if (normalized.includes("list")) return "ls";
2006
+ if (normalized.includes("grep")) return "grep";
2007
+ if (normalized.includes("glob")) return "glob";
2008
+ if (normalized.includes("read")) return "read";
2009
+ return toWireToolName(normalized);
2010
+ }
2011
+ function resolveInactiveBuiltinToolNames(start) {
2012
+ const toolFiltering = start.builtinToolFiltering;
2013
+ if (toolFiltering == null) return [];
2014
+ return toolFiltering.mode === "allow" ? Object.keys(PUBLIC_TO_NATIVE).filter(
2015
+ (name) => !toolFiltering.toolNames.includes(name)
2016
+ ) : toolFiltering.toolNames;
2017
+ }
2018
+ function isBuiltinToolInactive(input) {
2019
+ if (input.toolFiltering == null) return false;
2020
+ return input.toolFiltering.mode === "allow" ? !input.toolFiltering.toolNames.includes(input.toolName) : input.toolFiltering.toolNames.includes(input.toolName);
2021
+ }
2022
+ function isExternalPath(resource) {
2023
+ if (!path2.isAbsolute(resource)) return false;
2024
+ const normalized = path2.resolve(resource);
2025
+ return !isPathInsideOrEqual(normalized, workdir) && (!skillsDir || !isPathInsideOrEqual(normalized, skillsDir));
2026
+ }
2027
+ function isPathInsideOrEqual(file, root) {
2028
+ const normalizedRoot = path2.resolve(root);
2029
+ return file === normalizedRoot || file.startsWith(`${normalizedRoot}/`);
2030
+ }
2031
+ function toWireToolName(nativeName) {
2032
+ return NATIVE_TO_COMMON[nativeName] ?? OPENCODE_TO_WIRE[nativeName] ?? nativeName;
2033
+ }
2034
+ function nativeNameField({
2035
+ nativeName,
2036
+ toolName
2037
+ }) {
2038
+ if (!nativeName || nativeName === toolName || toolName === "agent") return {};
2039
+ return { nativeName };
2040
+ }
2041
+ function getHostToolName(toolName, rawToolName) {
2042
+ if (runtime.toolNames.has(toolName)) return toolName;
2043
+ if (typeof rawToolName === "string" && runtime.toolNames.has(rawToolName)) {
2044
+ return rawToolName;
2045
+ }
2046
+ if (typeof rawToolName === "string" && rawToolName.startsWith("harness-tools_") && runtime.toolNames.has(rawToolName.slice("harness-tools_".length))) {
2047
+ return rawToolName.slice("harness-tools_".length);
2048
+ }
2049
+ return void 0;
2050
+ }
2051
+ function authorizeHostToolCall({
2052
+ callID,
2053
+ toolName,
2054
+ input,
2055
+ state
2056
+ }) {
2057
+ if (state.hostToolCallsAuthorized.has(callID)) return;
2058
+ state.hostToolCallsAuthorized.add(callID);
2059
+ runtime.relay?.authorizeToolCall({ toolName, input });
2060
+ }
2061
+ async function emitContextFallback({
2062
+ client,
2063
+ sessionId,
2064
+ emit,
2065
+ emitContent
2066
+ }) {
2067
+ const assistant = await latestAssistantSnapshot({ client, sessionId });
2068
+ if (!assistant) return false;
2069
+ if (emitContent && Array.isArray(assistant.contentParts)) {
2070
+ for (const part of assistant.contentParts) {
2071
+ emitAssistantContentPart(part, emit);
2072
+ }
2073
+ }
2074
+ const rawFinish = typeof assistant.finish === "string" ? assistant.finish : assistant.error ? "error" : "stop";
2075
+ emit({
2076
+ type: "finish-step",
2077
+ finishReason: {
2078
+ unified: mapOpenCodeFinishReason(rawFinish),
2079
+ raw: rawFinish
2080
+ },
2081
+ usage: mapUsage(assistant.tokens),
2082
+ ...typeof assistant.cost === "number" ? {
2083
+ harnessMetadata: {
2084
+ opencode: { cost: assistant.cost, fallback: true }
2085
+ }
2086
+ } : { harnessMetadata: { opencode: { fallback: true } } }
2087
+ });
2088
+ return true;
2089
+ }
2090
+ async function readSessionTokens({
2091
+ client,
2092
+ sessionId
2093
+ }) {
2094
+ const session = await legacySessionGet({ client, sessionId });
2095
+ if (session.error) return void 0;
2096
+ return extractSessionTokens(session.data);
2097
+ }
2098
+ async function latestAssistantSnapshot({
2099
+ client,
2100
+ sessionId
2101
+ }) {
2102
+ const legacy = await client.session.messages({ sessionID: sessionId, limit: 20 }).catch(() => void 0);
2103
+ const legacyAssistant = latestLegacyAssistantMessage(legacy?.data);
2104
+ if (legacyAssistant) return legacyAssistant;
2105
+ const context = await client.v2.session.context({ sessionID: sessionId }).catch(() => void 0);
2106
+ if (!context || context.error) return void 0;
2107
+ return latestV2AssistantMessage(context.data);
2108
+ }
2109
+ function latestLegacyAssistantMessage(data) {
2110
+ const messages = Array.isArray(data) ? data : [];
2111
+ for (let i = messages.length - 1; i >= 0; i--) {
2112
+ const item = messages[i];
2113
+ if (!item || typeof item !== "object") continue;
2114
+ const record = item;
2115
+ const info = record.info;
2116
+ if (info && typeof info === "object" && info.role === "assistant") {
2117
+ return {
2118
+ ...info,
2119
+ contentParts: Array.isArray(record.parts) ? record.parts : void 0
2120
+ };
2121
+ }
2122
+ }
2123
+ return void 0;
2124
+ }
2125
+ function latestV2AssistantMessage(data) {
2126
+ const messages = data && typeof data === "object" && Array.isArray(data.data) ? data.data : Array.isArray(data) ? data : [];
2127
+ for (let i = messages.length - 1; i >= 0; i--) {
2128
+ const message = messages[i];
2129
+ if (message && typeof message === "object" && message.type === "assistant") {
2130
+ const record = message;
2131
+ return {
2132
+ ...record,
2133
+ contentParts: Array.isArray(record.content) ? record.content : void 0
2134
+ };
2135
+ }
2136
+ }
2137
+ return void 0;
2138
+ }
2139
+ function emitAssistantContentPart(part, emit) {
2140
+ if (!part || typeof part !== "object") return;
2141
+ const value = part;
2142
+ if (value.type !== "text" && value.type !== "reasoning") return;
2143
+ const id = typeof value.id === "string" && value.id.length > 0 ? value.id : `${value.type}-${randomUUID()}`;
2144
+ const text = typeof value.text === "string" ? value.text : "";
2145
+ if (value.type === "text") {
2146
+ emit({ type: "text-start", id });
2147
+ if (text) emit({ type: "text-delta", id, delta: text });
2148
+ emit({ type: "text-end", id });
2149
+ return;
2150
+ }
2151
+ emit({ type: "reasoning-start", id });
2152
+ if (text) emit({ type: "reasoning-delta", id, delta: text });
2153
+ emit({ type: "reasoning-end", id });
2154
+ }
2155
+ async function startToolRelay({
2156
+ allowedScriptPaths,
2157
+ tools,
2158
+ emit,
2159
+ requestToolResult
2160
+ }) {
2161
+ const toolNames = new Set(tools.map((t) => t.name));
2162
+ const allowedScriptPathSet = new Set(allowedScriptPaths);
2163
+ const authorizer = new ToolRelayAuthorizer();
2164
+ const server = createServer(async (req, res) => {
2165
+ try {
2166
+ if (req.method !== "POST" || req.url !== "/") {
2167
+ res.writeHead(401, { "Content-Type": "application/json" });
2168
+ res.end(JSON.stringify({ error: "unauthorized tool relay request" }));
2169
+ return;
2170
+ }
2171
+ const chunks = [];
2172
+ for await (const chunk of req) {
2173
+ chunks.push(chunk);
2174
+ }
2175
+ const body = Buffer.concat(chunks).toString("utf8");
2176
+ const { requestId, toolName, input } = JSON.parse(body);
2177
+ if (!toolNames.has(toolName)) {
2178
+ res.writeHead(403, { "Content-Type": "application/json" });
2179
+ res.end(
2180
+ JSON.stringify({ error: `Tool "${toolName}" is not available` })
2181
+ );
2182
+ return;
2183
+ }
2184
+ const authorized = authorizer.consumeToolCall({ toolName, input }) || await isToolRelayRequestFromAllowedProcess({
2185
+ socket: req.socket,
2186
+ allowedScriptPaths: allowedScriptPathSet
2187
+ });
2188
+ if (!authorized) {
2189
+ res.writeHead(401, { "Content-Type": "application/json" });
2190
+ res.end(JSON.stringify({ error: "unauthorized tool relay request" }));
2191
+ return;
2192
+ }
2193
+ emit({
2194
+ type: "tool-call",
2195
+ toolCallId: requestId,
2196
+ toolName,
2197
+ input: JSON.stringify(input ?? {}),
2198
+ providerExecuted: false
2199
+ });
2200
+ const { output, isError } = await requestToolResult(requestId);
2201
+ emit({
2202
+ type: "tool-result",
2203
+ toolCallId: requestId,
2204
+ toolName,
2205
+ result: output ?? null,
2206
+ isError: !!isError
2207
+ });
2208
+ res.writeHead(200, { "Content-Type": "application/json" });
2209
+ res.end(JSON.stringify({ result: output }));
2210
+ } catch (error) {
2211
+ res.writeHead(500, { "Content-Type": "application/json" });
2212
+ res.end(
2213
+ JSON.stringify({
2214
+ error: error instanceof Error ? error.message : String(error)
2215
+ })
2216
+ );
2217
+ }
2218
+ });
2219
+ await new Promise(
2220
+ (resolve) => server.listen(0, "127.0.0.1", () => resolve())
2221
+ );
2222
+ const address = server.address();
2223
+ if (!address || typeof address === "string") {
2224
+ throw new Error("tool relay did not expose a numeric port");
2225
+ }
2226
+ return {
2227
+ port: address.port,
2228
+ close: () => closeServer(server),
2229
+ authorizeToolCall: (call) => authorizer.authorizeToolCall(call)
2230
+ };
2231
+ }
2232
+ function closeServer(server) {
2233
+ try {
2234
+ server.close();
2235
+ } catch {
2236
+ }
2237
+ }
2238
+ function createDeferred() {
2239
+ let resolve;
2240
+ const promise = new Promise((res) => {
2241
+ resolve = res;
2242
+ });
2243
+ return { promise, resolve };
2244
+ }
2245
+ function sleep(ms) {
2246
+ return new Promise((resolve) => setTimeout(resolve, ms));
2247
+ }
2248
+ function splitModel(model, provider) {
2249
+ if (!model) return {};
2250
+ if (model.includes("/")) {
2251
+ const [providerID, ...rest] = model.split("/");
2252
+ return { providerID, modelID: rest.join("/") };
2253
+ }
2254
+ return { providerID: provider, modelID: model };
2255
+ }
2256
+ async function resolveCompactionModel({
2257
+ client,
2258
+ sessionId,
2259
+ start
2260
+ }) {
2261
+ const assistant = await latestAssistantSnapshot({ client, sessionId }).catch(
2262
+ () => void 0
2263
+ );
2264
+ const assistantModel = modelRefFromAssistantSnapshot(assistant);
2265
+ if (assistantModel) return assistantModel;
2266
+ const session = await legacySessionGet({ client, sessionId }).catch(
2267
+ () => void 0
2268
+ );
2269
+ const sessionModel = modelRefFromSessionInfo(session?.data);
2270
+ if (sessionModel) return sessionModel;
2271
+ return modelRefFromStart(start);
2272
+ }
2273
+ function modelRefFromAssistantSnapshot(assistant) {
2274
+ if (!assistant) return void 0;
2275
+ const model = modelRefFromValue(assistant.model);
2276
+ if (model) return model;
2277
+ const direct = modelRefFromValue(assistant);
2278
+ if (direct) return direct;
2279
+ if (isRecord2(assistant.metadata)) {
2280
+ return modelRefFromValue(assistant.metadata.assistant);
2281
+ }
2282
+ return void 0;
2283
+ }
2284
+ function modelRefFromSessionInfo(data) {
2285
+ if (!isRecord2(data)) return void 0;
2286
+ return modelRefFromValue(data.model) ?? modelRefFromValue(data);
2287
+ }
2288
+ function modelRefFromStart(start) {
2289
+ const model = splitModel(start.model, start.provider);
2290
+ if (!model.modelID) return void 0;
2291
+ return {
2292
+ providerID: model.providerID ?? start.provider ?? procEnv2.OPENAI_NAME ?? "anthropic",
2293
+ modelID: model.modelID
2294
+ };
2295
+ }
2296
+ function modelRefFromValue(value) {
2297
+ if (!isRecord2(value)) return void 0;
2298
+ const providerID = stringValue(value.providerID);
2299
+ const modelID = stringValue(value.modelID ?? value.id);
2300
+ if (!providerID || !modelID) return void 0;
2301
+ return { providerID, modelID };
2302
+ }
2303
+ function stringValue(value) {
2304
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2305
+ }
2306
+ function stripWorkDir(file) {
2307
+ if (!file) return file;
2308
+ const normalized = path2.resolve(file);
2309
+ const root = path2.resolve(workdir);
2310
+ return normalized.startsWith(`${root}/`) ? normalized.slice(root.length + 1) : file;
2311
+ }
2312
+ function parseArgs(args2) {
2313
+ const out = {};
2314
+ for (let i = 0; i < args2.length; i++) {
2315
+ if (args2[i] === "--workdir" && i + 1 < args2.length) {
2316
+ out.workdir = args2[++i];
2317
+ } else if (args2[i] === "--bridge-state-dir" && i + 1 < args2.length) {
2318
+ out.bridgeStateDir = args2[++i];
2319
+ } else if (args2[i] === "--bootstrap-dir" && i + 1 < args2.length) {
2320
+ out.bootstrapDir = args2[++i];
2321
+ } else if (args2[i] === "--skills-dir" && i + 1 < args2.length) {
2322
+ out.skillsDir = args2[++i];
2323
+ }
2324
+ }
2325
+ return out;
2326
+ }
2327
+ function formatError(error) {
2328
+ if (error instanceof Error) {
2329
+ const cause = "cause" in error ? error.cause : void 0;
2330
+ if (cause === void 0) return error.message;
2331
+ return `${error.message}: ${formatError(cause)}`;
2332
+ }
2333
+ if (typeof error === "string") return error;
2334
+ try {
2335
+ return JSON.stringify(error);
2336
+ } catch {
2337
+ return String(error);
2338
+ }
2339
+ }
2340
+ function emitFatal(message) {
2341
+ process.stderr.write(`[OpenCode bridge] ${message}
2342
+ `);
2343
+ process.exit(1);
2344
+ }
2345
+ //# sourceMappingURL=index.mjs.map