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