@ai-sdk/harness-opencode 0.0.0-cca10482-20260708215408

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