@nones/agentflow-opencode 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/adapter.ts ADDED
@@ -0,0 +1,1114 @@
1
+ import {
2
+ readSettings,
3
+ resolveConnection,
4
+ resolveDirectory,
5
+ resolveModel,
6
+ resolveTurnDelivery,
7
+ tryResolveModel,
8
+ type ResolvedConnection,
9
+ } from "./config";
10
+ import {
11
+ OpenCodeAmbiguousAdmissionError,
12
+ OpenCodeConfigError,
13
+ OpenCodeHttpError,
14
+ OpenCodeRateLimitError,
15
+ OpenCodeTimeoutError,
16
+ OpenCodeTransportError,
17
+ } from "./errors";
18
+ import { HttpClient, combineSignals, type HttpResult } from "./http";
19
+ import {
20
+ asString,
21
+ assistantMessagesForScope,
22
+ classifyRateLimit,
23
+ combineAssistantText,
24
+ errorMessage,
25
+ extractActiveCatalogue,
26
+ extractMessages,
27
+ extractModelListing,
28
+ extractSession,
29
+ extractSessionId,
30
+ extractSessionModel,
31
+ isRecord,
32
+ isUserMessage,
33
+ isIntermediateToolStep,
34
+ messageCreatedAt,
35
+ messageErrorText,
36
+ messageId,
37
+ normalizeEvent,
38
+ modelToString,
39
+ parseRetryAfter,
40
+ retryScheduledFromEvent,
41
+ sessionModelMatches,
42
+ terminalFromEvent,
43
+ terminalFromMessage,
44
+ terminalFromWaitBody,
45
+ unwrapData,
46
+ type JsonRecord,
47
+ type MessageScope,
48
+ type NormalizedEvent,
49
+ type TerminalInfo,
50
+ } from "./normalize";
51
+ import { bindHistoryCapability } from "./provider-history";
52
+ import { SseParser, type SseMessage } from "./sse";
53
+ import {
54
+ parseTranscriptPage,
55
+ type TranscriptPage,
56
+ type TranscriptPageRequest,
57
+ } from "./transcript";
58
+ import type {
59
+ ActiveModel,
60
+ AgentSpec,
61
+ CancelRequest,
62
+ ModelRef,
63
+ OpenCodeAdapterOptions,
64
+ Profile,
65
+ ProviderAdapter,
66
+ ProviderEvent,
67
+ SendRequest,
68
+ SessionConfiguration,
69
+ TurnRequest,
70
+ TurnResult,
71
+ } from "./types";
72
+
73
+ interface MutableScope extends MessageScope {
74
+ receiptId?: string;
75
+ baselineIds: Set<string>;
76
+ }
77
+
78
+ function assistantArtifacts(text: string): Record<string, unknown> | undefined {
79
+ if (!text.trimStart().startsWith("{")) return undefined;
80
+ try {
81
+ const response: unknown = JSON.parse(text);
82
+ if (isRecord(response) && isRecord(response.artifacts))
83
+ return response.artifacts;
84
+ } catch {
85
+ // Plain assistant text stays available in the turn result.
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ type SubmitOutcome =
91
+ | { kind: "accepted"; receipt?: string }
92
+ | { kind: "rate_limited"; result: TurnResult }
93
+ | { kind: "failed"; result: TurnResult }
94
+ | { kind: "interrupted"; result: TurnResult };
95
+
96
+ interface WaitOutcome {
97
+ ok: boolean;
98
+ idle: boolean;
99
+ terminal?: TerminalInfo;
100
+ messages?: JsonRecord[];
101
+ }
102
+
103
+ interface ObserverOptions {
104
+ sessionId: string;
105
+ scope: MutableScope;
106
+ signal?: AbortSignal;
107
+ onEvent?: (event: ProviderEvent) => void;
108
+ onTerminal: (terminal: TerminalInfo) => void;
109
+ onError?: (error: unknown) => void;
110
+ }
111
+
112
+ interface EventObserver {
113
+ close: () => Promise<void>;
114
+ refresh: () => void;
115
+ }
116
+
117
+ export class OpenCodeAdapter implements ProviderAdapter {
118
+ readonly id: string;
119
+ private readonly options: OpenCodeAdapterOptions;
120
+ private readonly http: HttpClient;
121
+ private readonly sleep: (ms: number) => Promise<void>;
122
+ private readonly now: () => number;
123
+ private readonly pollIntervalMs: number;
124
+ private readonly useWaitEndpoint: boolean;
125
+
126
+ constructor(options: OpenCodeAdapterOptions = {}) {
127
+ this.options = options;
128
+ this.id = options.id ?? "opencode";
129
+ this.now = options.now ?? (() => Date.now());
130
+ this.sleep = options.sleep ?? Bun.sleep;
131
+ this.pollIntervalMs = Math.max(1, options.pollIntervalMs ?? 100);
132
+ this.useWaitEndpoint = options.useWaitEndpoint ?? true;
133
+ const fetchImpl =
134
+ options.fetch ??
135
+ ((input: string, init: RequestInit) => globalThis.fetch(input, init));
136
+ this.http = new HttpClient(fetchImpl, this.now);
137
+ }
138
+
139
+ async open(
140
+ agent: AgentSpec,
141
+ profile: Profile,
142
+ session?: SessionConfiguration,
143
+ ): Promise<string> {
144
+ const connection = await resolveConnection(profile, this.options);
145
+ const model = resolveModel(agent, profile);
146
+ const permissions = session?.permissions ?? [];
147
+
148
+ const response = await this.request(connection, {
149
+ method: "POST",
150
+ path: "/api/session",
151
+ body: {
152
+ title: agent.id || "agentflow",
153
+ location: { directory: agent.cwd },
154
+ model,
155
+ ...(permissions.length === 0 ? {} : { permissions }),
156
+ },
157
+ });
158
+ if (!response.ok) throw this.httpError(response, "POST /api/session", true);
159
+
160
+ const sessionId = extractSessionId(response.body);
161
+ if (!sessionId) {
162
+ throw new OpenCodeHttpError(
163
+ "OpenCode created a session but did not return a session id.",
164
+ response.status,
165
+ response.body,
166
+ );
167
+ }
168
+
169
+ await this.awaitConcreteModel(connection, sessionId, model);
170
+
171
+ const instructions = session?.instructions?.trim();
172
+ if (instructions !== undefined && instructions !== "") {
173
+ // Session-only instructions, attached before the first prompt. This is
174
+ // deliberately not provider-wide or global configuration.
175
+ const attached = await this.request(connection, {
176
+ method: "PUT",
177
+ path: `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/agentflow_modules`,
178
+ body: { value: instructions },
179
+ });
180
+ if (!attached.ok) {
181
+ throw this.httpError(attached, "PUT module instructions", false);
182
+ }
183
+ }
184
+ return sessionId;
185
+ }
186
+
187
+ async turn(request: TurnRequest): Promise<TurnResult> {
188
+ const connection = await resolveConnection(request.profile, this.options);
189
+ const settings = readSettings(request.profile);
190
+ const scope: MutableScope = {
191
+ sessionId: request.sessionId,
192
+ turnId: request.turnId,
193
+ receiptId: request.receipt,
194
+ baselineIds: new Set<string>(),
195
+ baselineAt: this.now(),
196
+ acceptedAt: this.now(),
197
+ };
198
+
199
+ // Establish a baseline so older assistant messages and terminal events are
200
+ // never attributed to this turn. A failed baseline read is not fatal.
201
+ try {
202
+ const baseline = await this.fetchMessages(connection, request.sessionId);
203
+ for (const message of baseline) {
204
+ const id = messageId(message);
205
+ if (id) scope.baselineIds.add(id);
206
+ }
207
+ scope.baselineAt = this.now();
208
+ } catch {
209
+ // Continue; receipt and creation-time scoping still apply.
210
+ }
211
+
212
+ let eventTerminal: TerminalInfo | undefined;
213
+ const waitController = new AbortController();
214
+ let waitTask: Promise<void> | undefined;
215
+ let waitOutcome: WaitOutcome | undefined;
216
+ let sessionIdle = false;
217
+ let observer: EventObserver | undefined;
218
+ let messages: JsonRecord[] = [];
219
+ let terminal: TerminalInfo | undefined;
220
+ let lastError: string | undefined;
221
+
222
+ try {
223
+ observer =
224
+ settings.eventStream === false
225
+ ? undefined
226
+ : this.startEventObserver(connection, {
227
+ sessionId: request.sessionId,
228
+ scope,
229
+ signal: request.signal,
230
+ onEvent: request.onEvent,
231
+ onTerminal: (value) => {
232
+ eventTerminal ??= value;
233
+ },
234
+ onError: () => {
235
+ // Message/wait polling remains the fallback.
236
+ },
237
+ });
238
+
239
+ let receipt = request.receipt;
240
+ if (!receipt) {
241
+ const outcome = await this.submitPrompt(
242
+ connection,
243
+ request.sessionId,
244
+ request.prompt,
245
+ resolveTurnDelivery(settings),
246
+ request.signal,
247
+ );
248
+ if (outcome.kind === "rate_limited") return outcome.result;
249
+ if (outcome.kind === "failed") return outcome.result;
250
+ if (outcome.kind === "interrupted") return outcome.result;
251
+ receipt = outcome.receipt;
252
+ if (receipt) {
253
+ scope.receiptId = receipt;
254
+ request.onReceipt?.(receipt);
255
+ }
256
+ scope.acceptedAt = this.now();
257
+ // Events observed between subscription and the admission response may
258
+ // now become attributable to this receipt.
259
+ observer?.refresh();
260
+ }
261
+
262
+ if (this.useWaitEndpoint) {
263
+ waitTask = this.waitOnce(
264
+ connection,
265
+ request.sessionId,
266
+ combineSignals([request.signal, waitController.signal]),
267
+ )
268
+ .then((outcome) => {
269
+ waitOutcome = outcome;
270
+ if (outcome.idle && !outcome.terminal) sessionIdle = true;
271
+ })
272
+ .catch(() => {
273
+ // The wait endpoint is experimental; polling below is authoritative.
274
+ });
275
+ }
276
+
277
+ const deadline = this.now() + connection.timeouts.turnMs;
278
+
279
+ for (;;) {
280
+ terminal = eventTerminal ?? waitOutcome?.terminal;
281
+ if (terminal) break;
282
+
283
+ if (request.signal?.aborted) {
284
+ terminal = {
285
+ status: "interrupted",
286
+ error: "Turn aborted.",
287
+ source: "message",
288
+ };
289
+ break;
290
+ }
291
+ if (this.now() >= deadline) {
292
+ terminal = {
293
+ status: "interrupted",
294
+ error: `Turn timed out after ${connection.timeouts.turnMs}ms.`,
295
+ source: "message",
296
+ };
297
+ break;
298
+ }
299
+
300
+ await this.sleep(this.pollIntervalMs);
301
+
302
+ terminal = eventTerminal ?? waitOutcome?.terminal;
303
+ if (terminal) break;
304
+
305
+ try {
306
+ messages = await this.fetchMessages(connection, request.sessionId);
307
+ this.alignScopeToReceipt(messages, scope);
308
+ const scoped = assistantMessagesForScope(messages, scope);
309
+ const errors = scoped
310
+ .map(messageErrorText)
311
+ .filter((value): value is string => !!value);
312
+ if (errors.length > 0) lastError = errors.join("; ");
313
+
314
+ const completed = scoped
315
+ .map((message) => terminalFromMessage(message))
316
+ .find((value): value is TerminalInfo => value !== undefined);
317
+ if (completed) {
318
+ terminal =
319
+ completed.error || !lastError
320
+ ? completed
321
+ : { ...completed, error: lastError };
322
+ break;
323
+ }
324
+
325
+ if (
326
+ sessionIdle &&
327
+ scoped.length > 0 &&
328
+ !scoped.some((message) => isIntermediateToolStep(message))
329
+ ) {
330
+ terminal = {
331
+ status: errors.length > 0 ? "failed" : "succeeded",
332
+ error: lastError,
333
+ source: "wait",
334
+ };
335
+ break;
336
+ }
337
+ } catch (error) {
338
+ lastError = errorMessage(error);
339
+ }
340
+
341
+ if (waitOutcome?.messages) {
342
+ messages = waitOutcome.messages;
343
+ }
344
+ }
345
+ } finally {
346
+ // Abort both observers first, then await every tracked task so no
347
+ // rejecting or detached promise survives the turn. `waitOnce` and the
348
+ // event observer both swallow their own cancellation errors; these
349
+ // catches are a final safety net.
350
+ waitController.abort();
351
+ const observerClose = observer?.close();
352
+ if (waitTask) {
353
+ try {
354
+ await waitTask;
355
+ } catch {
356
+ // Cancellation must never surface as an unhandled rejection.
357
+ }
358
+ }
359
+ if (observerClose) {
360
+ try {
361
+ await observerClose;
362
+ } catch {
363
+ // Cancellation must never surface as an unhandled rejection.
364
+ }
365
+ }
366
+ }
367
+
368
+ if (!terminal) {
369
+ terminal = {
370
+ status: "interrupted",
371
+ error: "Turn ended without a scoped terminal event.",
372
+ source: "message",
373
+ };
374
+ }
375
+
376
+ try {
377
+ messages = await this.fetchMessages(connection, request.sessionId);
378
+ this.alignScopeToReceipt(messages, scope);
379
+ } catch (error) {
380
+ if (messages.length === 0 && waitOutcome?.messages)
381
+ messages = waitOutcome.messages;
382
+ lastError ??= errorMessage(error);
383
+ }
384
+
385
+ const scoped = assistantMessagesForScope(messages, scope);
386
+ const text = combineAssistantText(scoped);
387
+ const messageErrors = scoped
388
+ .map(messageErrorText)
389
+ .filter((value): value is string => !!value);
390
+ if (messageErrors.length > 0) lastError = messageErrors.join("; ");
391
+
392
+ const finalStatus: TerminalInfo["status"] =
393
+ terminal.status === "succeeded" && messageErrors.length > 0
394
+ ? "failed"
395
+ : terminal.status;
396
+ const artifacts =
397
+ finalStatus === "succeeded" ? assistantArtifacts(text) : undefined;
398
+
399
+ return {
400
+ status: finalStatus,
401
+ ...(text.length > 0 ? { text } : {}),
402
+ ...(artifacts === undefined ? {} : { artifacts }),
403
+ ...(terminal.error || lastError
404
+ ? { error: terminal.error ?? lastError }
405
+ : {}),
406
+ };
407
+ }
408
+
409
+ async reconcile(request: TurnRequest): Promise<TurnResult | undefined> {
410
+ if (!request.receipt) return undefined;
411
+ const connection = await resolveConnection(request.profile, this.options);
412
+ const messages = await this.fetchMessages(connection, request.sessionId);
413
+ const receiptMessage = messages.find(
414
+ (message) =>
415
+ messageId(message) === request.receipt && isUserMessage(message),
416
+ );
417
+ const acceptedAt = receiptMessage
418
+ ? (messageCreatedAt(receiptMessage) ?? 0)
419
+ : 0;
420
+ const scope: MessageScope = {
421
+ sessionId: request.sessionId,
422
+ turnId: request.turnId,
423
+ receiptId: request.receipt,
424
+ baselineIds: new Set<string>(),
425
+ baselineAt: 0,
426
+ acceptedAt,
427
+ };
428
+ const scoped = assistantMessagesForScope(messages, scope);
429
+ if (scoped.length === 0) return undefined;
430
+ const terminal = scoped
431
+ .map((message) => terminalFromMessage(message))
432
+ .find((value): value is TerminalInfo => value !== undefined);
433
+ if (!terminal) return undefined;
434
+
435
+ const text = combineAssistantText(scoped);
436
+ if (terminal.status !== "succeeded") {
437
+ return {
438
+ status: terminal.status,
439
+ ...(text.length > 0 ? { text } : {}),
440
+ ...(terminal.error ? { error: terminal.error } : {}),
441
+ };
442
+ }
443
+ const artifacts = assistantArtifacts(text);
444
+ return {
445
+ status: "succeeded",
446
+ ...(text.length > 0 ? { text } : {}),
447
+ ...(artifacts === undefined ? {} : { artifacts }),
448
+ };
449
+ }
450
+
451
+ async send(request: SendRequest): Promise<{ receipt?: string }> {
452
+ const connection = await resolveConnection(request.profile, this.options);
453
+ let response: HttpResult;
454
+ try {
455
+ response = await this.request(connection, {
456
+ method: "POST",
457
+ path: `/api/session/${encodeURIComponent(request.sessionId)}/prompt`,
458
+ body: { text: request.prompt, delivery: request.delivery },
459
+ });
460
+ } catch (error) {
461
+ if (error instanceof OpenCodeConfigError) throw error;
462
+ throw new OpenCodeAmbiguousAdmissionError(
463
+ `Message admission is ambiguous: ${errorMessage(error)}`,
464
+ { cause: error },
465
+ );
466
+ }
467
+ if (response.status === 429) {
468
+ const { reason, message } = classifyRateLimit(
469
+ response.body,
470
+ response.text,
471
+ );
472
+ throw new OpenCodeRateLimitError(
473
+ message ?? "OpenCode rejected the message with HTTP 429.",
474
+ response.status,
475
+ response.body,
476
+ {
477
+ reason,
478
+ retryAfterMs: this.retryAfterMs(response),
479
+ safeToRetry: true,
480
+ },
481
+ );
482
+ }
483
+ if (!response.ok) throw this.httpError(response, "POST prompt", false);
484
+ return { receipt: this.extractReceipt(response.body) };
485
+ }
486
+
487
+ async cancel(request: CancelRequest): Promise<void> {
488
+ const connection = await resolveConnection(request.profile, this.options);
489
+ const response = await this.request(connection, {
490
+ method: "POST",
491
+ path: `/api/session/${encodeURIComponent(request.sessionId)}/interrupt`,
492
+ body: {},
493
+ });
494
+ if (response.ok || response.status === 404 || response.status === 410)
495
+ return;
496
+ throw this.httpError(response, "POST interrupt", false);
497
+ }
498
+
499
+ async doctor(profile: Profile): Promise<unknown> {
500
+ const limitations: string[] = [];
501
+ const directory = resolveDirectory(profile, this.options);
502
+ const base = {
503
+ adapter: this.id,
504
+ profile: profile.id,
505
+ endpoint: undefined as string | undefined,
506
+ directory,
507
+ reachable: false,
508
+ configuredModel: undefined as string | undefined,
509
+ modelListing: "unavailable" as "available" | "unavailable" | "unknown",
510
+ modelAvailable: undefined as boolean | undefined,
511
+ ok: false,
512
+ limitations,
513
+ };
514
+
515
+ let connection: ResolvedConnection;
516
+ try {
517
+ connection = await resolveConnection(profile, this.options);
518
+ base.endpoint = connection.endpoint;
519
+ } catch (error) {
520
+ base.limitations.push(errorMessage(error));
521
+ return base;
522
+ }
523
+
524
+ const agent: AgentSpec = {
525
+ id: profile.id,
526
+ prompt: "",
527
+ cwd: directory ?? ".",
528
+ };
529
+ const configuredModel = tryResolveModel(agent, profile);
530
+ if (!configuredModel) {
531
+ base.limitations.push(
532
+ "No concrete default model is configured for this profile; a session cannot be opened safely.",
533
+ );
534
+ } else {
535
+ base.configuredModel = modelToString(configuredModel);
536
+ }
537
+
538
+ let response: HttpResult;
539
+ try {
540
+ response = await this.request(connection, {
541
+ method: "GET",
542
+ path: this.modelCataloguePath(directory),
543
+ });
544
+ } catch (error) {
545
+ base.limitations.push(`Endpoint unreachable: ${errorMessage(error)}`);
546
+ return base;
547
+ }
548
+
549
+ base.reachable = true;
550
+ if (!response.ok) {
551
+ base.modelListing = "unavailable";
552
+ if (response.status === 401 || response.status === 403) {
553
+ base.ok = false;
554
+ base.limitations.push(
555
+ `OpenCode rejected authentication with HTTP ${response.status}; the profile cannot be verified.`,
556
+ );
557
+ } else {
558
+ base.limitations.push(
559
+ `The endpoint is reachable but /api/model returned HTTP ${response.status}; the model catalogue could not be verified.`,
560
+ );
561
+ base.ok = configuredModel !== undefined;
562
+ }
563
+ return base;
564
+ }
565
+
566
+ const listing = extractModelListing(response.body);
567
+ const catalogueEmpty =
568
+ listing.shape === "known" && listing.models.length === 0;
569
+ base.modelListing =
570
+ listing.shape !== "known"
571
+ ? "unknown"
572
+ : catalogueEmpty
573
+ ? "unavailable"
574
+ : "available";
575
+ if (listing.shape !== "known") {
576
+ base.limitations.push(
577
+ "The /api/model response shape was not recognised; configured model availability was not verified.",
578
+ );
579
+ }
580
+ if (catalogueEmpty) {
581
+ base.limitations.push(
582
+ directory
583
+ ? `The /api/model catalogue returned no models for location "${directory}"; configured model availability was not verified.`
584
+ : "The /api/model catalogue returned no models and no location was supplied; configured model availability was not verified.",
585
+ );
586
+ }
587
+ if (configuredModel) {
588
+ if (listing.shape === "known" && !catalogueEmpty) {
589
+ base.modelAvailable = listing.models.some(
590
+ (candidate) =>
591
+ candidate.providerID === configuredModel.providerID &&
592
+ candidate.id === configuredModel.id,
593
+ );
594
+ if (!base.modelAvailable) {
595
+ base.limitations.push(
596
+ `Configured model "${base.configuredModel}" is not present in the endpoint model catalogue.`,
597
+ );
598
+ }
599
+ } else if (listing.shape !== "known") {
600
+ base.limitations.push(
601
+ "Configured model presence could not be confirmed because the catalogue shape is unknown.",
602
+ );
603
+ }
604
+ }
605
+
606
+ if (listing.shape === "known") {
607
+ base.ok =
608
+ configuredModel !== undefined &&
609
+ !catalogueEmpty &&
610
+ base.modelAvailable === true;
611
+ } else {
612
+ // Reachable and configuration-valid, but the catalogue itself was not
613
+ // verified. The limitation above makes that distinction explicit.
614
+ base.ok = configuredModel !== undefined;
615
+ }
616
+ return base;
617
+ }
618
+
619
+ /**
620
+ * List the models the connected local endpoint currently exposes.
621
+ *
622
+ * Resolution reuses the same authenticated connection as the rest of the
623
+ * adapter, so the catalogue reflects only providers this endpoint has
624
+ * configured or authenticated. Providers explicitly advertised as
625
+ * unconnected or as public inventory are excluded and never returned.
626
+ *
627
+ * Failure reporting is deliberate: an unreachable endpoint, an HTTP rejection
628
+ * (including 401/403) or an unrecognised catalogue throws. A verified,
629
+ * authenticated catalogue with no active models resolves to an empty array.
630
+ * This lets callers tell a concrete error from a true empty catalogue.
631
+ */
632
+ async listModels(profile: Profile): Promise<readonly ActiveModel[]> {
633
+ const connection = await resolveConnection(profile, this.options);
634
+ const directory = resolveDirectory(profile, this.options);
635
+ let response: HttpResult;
636
+ try {
637
+ response = await this.request(connection, {
638
+ method: "GET",
639
+ path: this.modelCataloguePath(directory),
640
+ });
641
+ } catch (error) {
642
+ throw new OpenCodeTransportError(
643
+ `OpenCode model catalogue is unreachable: ${errorMessage(error)}`,
644
+ { cause: error },
645
+ );
646
+ }
647
+
648
+ if (response.status === 401 || response.status === 403) {
649
+ throw new OpenCodeHttpError(
650
+ `OpenCode rejected authentication for the model catalogue with HTTP ${response.status}; no active models can be listed.`,
651
+ response.status,
652
+ response.body,
653
+ );
654
+ }
655
+ if (!response.ok) {
656
+ throw new OpenCodeHttpError(
657
+ this.httpMessage(response, "GET /api/model"),
658
+ response.status,
659
+ response.body,
660
+ );
661
+ }
662
+
663
+ const catalogue = extractActiveCatalogue(response.body);
664
+ if (catalogue.shape !== "known") {
665
+ throw new OpenCodeConfigError(
666
+ "The /api/model response shape was not recognised; active model listing requires an explicit catalogue.",
667
+ );
668
+ }
669
+
670
+ const defaultModel = catalogue.defaultModel;
671
+ const models: ActiveModel[] = [];
672
+ for (const provider of catalogue.providers) {
673
+ for (const option of provider.models) {
674
+ const isDefault = option.default === true || option.id === defaultModel;
675
+ models.push({
676
+ id: option.id,
677
+ ...(option.label ? { label: option.label } : {}),
678
+ provider: provider.id,
679
+ ...(option.description ? { description: option.description } : {}),
680
+ ...(isDefault ? { default: true } : {}),
681
+ ...(option.reasoningEfforts
682
+ ? { reasoningEfforts: option.reasoningEfforts }
683
+ : {}),
684
+ });
685
+ }
686
+ }
687
+ return models;
688
+ }
689
+
690
+ createHistory(profile: Profile) {
691
+ return bindHistoryCapability(this, profile, { options: this.options });
692
+ }
693
+
694
+ /**
695
+ * Optional read-only history slice. It uses only the already-supported
696
+ * `GET /api/session/{id}/message` contract and never submits a prompt.
697
+ * Pagination metadata is reported when the endpoint returns it; otherwise the
698
+ * page status says so and callers must not follow a cursor.
699
+ */
700
+ async inspectTranscript(
701
+ profile: Profile,
702
+ sessionId: string,
703
+ request: TranscriptPageRequest & { signal?: AbortSignal } = {},
704
+ ): Promise<TranscriptPage> {
705
+ const connection = await resolveConnection(profile, this.options);
706
+ const params = new URLSearchParams();
707
+ if (request.cursor !== undefined) params.set("cursor", request.cursor);
708
+ if (request.limit !== undefined)
709
+ params.set("limit", String(Math.floor(request.limit)));
710
+ const query = params.toString();
711
+ const response = await this.request(connection, {
712
+ method: "GET",
713
+ path: `/api/session/${encodeURIComponent(sessionId)}/message${query ? `?${query}` : ""}`,
714
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
715
+ });
716
+ const capturedAt = this.now();
717
+ if (!response.ok) {
718
+ throw this.httpError(response, `GET message ${sessionId}`, false);
719
+ }
720
+ return parseTranscriptPage(response.body, request, capturedAt);
721
+ }
722
+
723
+ private async awaitConcreteModel(
724
+ connection: ResolvedConnection,
725
+ sessionId: string,
726
+ expected: ModelRef,
727
+ ): Promise<void> {
728
+ const deadline = this.now() + connection.timeouts.sessionReadyMs;
729
+ let lastObservation: string | undefined;
730
+ for (;;) {
731
+ const response = await this.request(connection, {
732
+ method: "GET",
733
+ path: `/api/session/${encodeURIComponent(sessionId)}`,
734
+ });
735
+
736
+ if (response.ok) {
737
+ const session =
738
+ extractSession(response.body) ?? unwrapData(response.body);
739
+ const observed = extractSessionModel(session);
740
+ if (observed !== undefined) {
741
+ const matches = sessionModelMatches(observed, expected);
742
+ if (matches === false) {
743
+ lastObservation =
744
+ typeof observed === "string" ? observed : modelToString(observed);
745
+ throw new OpenCodeConfigError(
746
+ `OpenCode session "${sessionId}" resolved model "${lastObservation}" instead of requested "${modelToString(expected)}".`,
747
+ );
748
+ }
749
+ return;
750
+ }
751
+ } else if (response.status !== 404) {
752
+ throw this.httpError(response, `GET session ${sessionId}`, false);
753
+ }
754
+
755
+ if (this.now() >= deadline) {
756
+ throw new OpenCodeTimeoutError(
757
+ `OpenCode session "${sessionId}" did not expose a concrete model within ${connection.timeouts.sessionReadyMs}ms${lastObservation ? ` (last observed ${lastObservation})` : ""}.`,
758
+ );
759
+ }
760
+ await this.sleep(this.pollIntervalMs);
761
+ }
762
+ }
763
+
764
+ private async submitPrompt(
765
+ connection: ResolvedConnection,
766
+ sessionId: string,
767
+ prompt: string,
768
+ delivery: "queue" | "steer",
769
+ signal?: AbortSignal,
770
+ ): Promise<SubmitOutcome> {
771
+ let response: HttpResult;
772
+ try {
773
+ response = await this.request(connection, {
774
+ method: "POST",
775
+ path: `/api/session/${encodeURIComponent(sessionId)}/prompt`,
776
+ body: { text: prompt, delivery },
777
+ signal,
778
+ });
779
+ } catch (error) {
780
+ if (error instanceof OpenCodeConfigError) throw error;
781
+ // A transport failure after the request may have left the server with an
782
+ // admitted turn. Never retry automatically; expose it as interrupted.
783
+ return {
784
+ kind: "interrupted",
785
+ result: {
786
+ status: "interrupted",
787
+ error: `Admission is ambiguous: ${errorMessage(error)}`,
788
+ },
789
+ };
790
+ }
791
+
792
+ if (response.status === 429) {
793
+ const { reason, message } = classifyRateLimit(
794
+ response.body,
795
+ response.text,
796
+ );
797
+ return {
798
+ kind: "rate_limited",
799
+ result: {
800
+ status: "rate_limited",
801
+ error: message ?? "OpenCode rejected the prompt with HTTP 429.",
802
+ rateLimit: {
803
+ reason,
804
+ retryAfterMs: this.retryAfterMs(response),
805
+ safeToRetry: true,
806
+ },
807
+ },
808
+ };
809
+ }
810
+ if (!response.ok) {
811
+ return {
812
+ kind: "failed",
813
+ result: {
814
+ status: "failed",
815
+ error: this.httpMessage(response, "POST prompt"),
816
+ },
817
+ };
818
+ }
819
+ return { kind: "accepted", receipt: this.extractReceipt(response.body) };
820
+ }
821
+
822
+ private async waitOnce(
823
+ connection: ResolvedConnection,
824
+ sessionId: string,
825
+ signal: AbortSignal,
826
+ ): Promise<WaitOutcome> {
827
+ let response: HttpResult;
828
+ try {
829
+ response = await this.request(connection, {
830
+ method: "POST",
831
+ path: `/api/experimental/session/${encodeURIComponent(sessionId)}/wait`,
832
+ body: {},
833
+ signal,
834
+ });
835
+ } catch {
836
+ return { ok: false, idle: false };
837
+ }
838
+ if (!response.ok) return { ok: false, idle: false };
839
+ const terminal = terminalFromWaitBody(response.body);
840
+ const messages = extractMessages(response.body);
841
+ return {
842
+ ok: true,
843
+ idle: terminal === undefined,
844
+ terminal,
845
+ ...(messages.length > 0 ? { messages } : {}),
846
+ };
847
+ }
848
+
849
+ private alignScopeToReceipt(
850
+ messages: readonly JsonRecord[],
851
+ scope: MutableScope,
852
+ ): void {
853
+ if (!scope.receiptId) return;
854
+ const receipt = messages.find(
855
+ (message) =>
856
+ messageId(message) === scope.receiptId && isUserMessage(message),
857
+ );
858
+ const created = receipt ? messageCreatedAt(receipt) : undefined;
859
+ if (created !== undefined) scope.acceptedAt = created;
860
+ }
861
+
862
+ private async fetchMessages(
863
+ connection: ResolvedConnection,
864
+ sessionId: string,
865
+ ): Promise<JsonRecord[]> {
866
+ const response = await this.request(connection, {
867
+ method: "GET",
868
+ path: `/api/session/${encodeURIComponent(sessionId)}/message`,
869
+ });
870
+ if (!response.ok) throw this.httpError(response, "GET messages", false);
871
+ return extractMessages(response.body);
872
+ }
873
+
874
+ private startEventObserver(
875
+ connection: ResolvedConnection,
876
+ options: ObserverOptions,
877
+ ): EventObserver {
878
+ const controller = new AbortController();
879
+ const signal = combineSignals([options.signal, controller.signal]);
880
+ let reader:
881
+ | Pick<ReadableStreamDefaultReader<Uint8Array>, "read" | "cancel">
882
+ | undefined;
883
+ const pending: NormalizedEvent[] = [];
884
+ let closed = false;
885
+
886
+ const report = (error: unknown) => {
887
+ try {
888
+ options.onError?.(error);
889
+ } catch {
890
+ // The observer's error hook must never reject the stream task.
891
+ }
892
+ };
893
+ const emit = (event: ProviderEvent) => {
894
+ try {
895
+ options.onEvent?.(event);
896
+ } catch (error) {
897
+ report(error);
898
+ }
899
+ };
900
+ const emitTerminal = (value: TerminalInfo) => {
901
+ try {
902
+ options.onTerminal(value);
903
+ } catch (error) {
904
+ report(error);
905
+ }
906
+ };
907
+
908
+ const handle = (message: SseMessage) => {
909
+ if (!message.data) return;
910
+ let parsed: unknown;
911
+ try {
912
+ parsed = JSON.parse(message.data);
913
+ } catch {
914
+ return;
915
+ }
916
+ const event = normalizeEvent(parsed, message.event);
917
+ if (!event) return;
918
+ if (event.sessionID && event.sessionID !== options.sessionId) return;
919
+ emit({ type: event.type, data: parsed });
920
+
921
+ // A confirmed native retry.scheduled is an observation about the active
922
+ // session, not a new turn. Surface it as a provider event only.
923
+ const retry = retryScheduledFromEvent(event);
924
+ if (retry) emit({ type: "provider.rate_limit", data: retry });
925
+
926
+ // Keep a small replay window so an event that arrives before the
927
+ // admission response can be rescoped once the receipt is known.
928
+ pending.push(event);
929
+ if (pending.length > 100) pending.shift();
930
+
931
+ const terminal = terminalFromEvent(event, options.scope);
932
+ if (terminal) emitTerminal(terminal);
933
+ };
934
+
935
+ const cancelReader = async () => {
936
+ const current = reader;
937
+ if (!current) return;
938
+ try {
939
+ await current.cancel();
940
+ } catch {
941
+ // Stream already closed.
942
+ }
943
+ };
944
+
945
+ const run = (async () => {
946
+ try {
947
+ const response = await this.http.stream(
948
+ connection,
949
+ "/api/event",
950
+ signal,
951
+ );
952
+ if (!response.ok || !response.body) {
953
+ report(new Error(`Event stream returned HTTP ${response.status}.`));
954
+ return;
955
+ }
956
+ const current = response.body.getReader();
957
+ reader = current;
958
+ if (closed) await cancelReader();
959
+ const decoder = new TextDecoder();
960
+ const parser = new SseParser();
961
+ for (;;) {
962
+ const { done, value } = await current.read();
963
+ if (done) break;
964
+ const chunk = decoder.decode(value, { stream: true });
965
+ for (const message of parser.push(chunk)) handle(message);
966
+ }
967
+ for (const message of parser.flush()) handle(message);
968
+ } catch (error) {
969
+ if (!controller.signal.aborted && !signal.aborted) report(error);
970
+ } finally {
971
+ try {
972
+ await reader?.cancel();
973
+ } catch {
974
+ // Stream already closed.
975
+ }
976
+ }
977
+ })();
978
+
979
+ // The stream task is deliberately backgrounded, but never left without a
980
+ // rejection handler. close() additionally awaits it.
981
+ void run.catch(() => undefined);
982
+
983
+ return {
984
+ close: async () => {
985
+ if (closed) return;
986
+ closed = true;
987
+ controller.abort();
988
+ await cancelReader();
989
+ try {
990
+ await run;
991
+ } catch {
992
+ // Cancellation is expected; the turn result must not be affected.
993
+ }
994
+ },
995
+ refresh: () => {
996
+ for (const event of pending) {
997
+ const terminal = terminalFromEvent(event, options.scope);
998
+ if (terminal) {
999
+ emitTerminal(terminal);
1000
+ break;
1001
+ }
1002
+ }
1003
+ },
1004
+ };
1005
+ }
1006
+
1007
+ private request(
1008
+ connection: ResolvedConnection,
1009
+ options: Parameters<HttpClient["request"]>[1],
1010
+ ) {
1011
+ return this.http.request(connection, options);
1012
+ }
1013
+
1014
+ /** The shared `/api/model` path, with the optional location query. */
1015
+ private modelCataloguePath(directory: string | undefined): string {
1016
+ const params = new URLSearchParams();
1017
+ if (directory) params.set("location[directory]", directory);
1018
+ const query = params.toString();
1019
+ return `/api/model${query ? `?${query}` : ""}`;
1020
+ }
1021
+
1022
+ private extractReceipt(body: unknown): string | undefined {
1023
+ const value = unwrapData(body);
1024
+ if (isRecord(value)) {
1025
+ const receipt = value.receipt;
1026
+ if (typeof receipt === "string") return receipt;
1027
+ if (isRecord(receipt)) {
1028
+ const id = asString(receipt.id);
1029
+ if (id) return id;
1030
+ }
1031
+ const message = value.message;
1032
+ if (isRecord(message)) {
1033
+ const id = asString(message.id);
1034
+ if (id) return id;
1035
+ }
1036
+ return (
1037
+ asString(value.id) ??
1038
+ asString(value.receiptID) ??
1039
+ asString(value.receiptId) ??
1040
+ asString(value.messageID) ??
1041
+ asString(value.messageId)
1042
+ );
1043
+ }
1044
+ return undefined;
1045
+ }
1046
+
1047
+ private retryAfterMs(response: {
1048
+ headers: Headers;
1049
+ body: unknown;
1050
+ }): number | undefined {
1051
+ const fromHeader = parseRetryAfter(response.headers, this.now());
1052
+ if (fromHeader !== undefined) return fromHeader;
1053
+ const body = unwrapData(response.body);
1054
+ if (isRecord(body)) {
1055
+ const direct = body.retryAfterMs;
1056
+ if (typeof direct === "number" && Number.isFinite(direct) && direct >= 0)
1057
+ return direct;
1058
+ const seconds = body.retryAfter;
1059
+ if (
1060
+ typeof seconds === "number" &&
1061
+ Number.isFinite(seconds) &&
1062
+ seconds >= 0
1063
+ ) {
1064
+ return Math.round(seconds * 1_000);
1065
+ }
1066
+ }
1067
+ return undefined;
1068
+ }
1069
+
1070
+ private httpMessage(
1071
+ response: { status: number; text: string; body: unknown },
1072
+ action: string,
1073
+ ) {
1074
+ const body = unwrapData(response.body);
1075
+ let detail = "";
1076
+ if (isRecord(body)) {
1077
+ const error = body.error;
1078
+ if (typeof error === "string") detail = error;
1079
+ else if (isRecord(error))
1080
+ detail = asString(error.message) ?? asString(error.type) ?? "";
1081
+ detail ||= asString(body.message) ?? "";
1082
+ }
1083
+ if (!detail && response.text) detail = response.text.slice(0, 500);
1084
+ return `${action} failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}`;
1085
+ }
1086
+
1087
+ private httpError(
1088
+ response: { status: number; text: string; body: unknown; headers: Headers },
1089
+ action: string,
1090
+ safeToRetry: boolean,
1091
+ ): OpenCodeHttpError {
1092
+ const message = this.httpMessage(response, action);
1093
+ if (response.status === 429) {
1094
+ const { reason } = classifyRateLimit(response.body, response.text);
1095
+ return new OpenCodeRateLimitError(
1096
+ message,
1097
+ response.status,
1098
+ response.body,
1099
+ {
1100
+ reason,
1101
+ retryAfterMs: this.retryAfterMs(response),
1102
+ safeToRetry,
1103
+ },
1104
+ );
1105
+ }
1106
+ return new OpenCodeHttpError(message, response.status, response.body);
1107
+ }
1108
+ }
1109
+
1110
+ export function createOpenCodeAdapter(
1111
+ options: OpenCodeAdapterOptions = {},
1112
+ ): OpenCodeAdapter {
1113
+ return new OpenCodeAdapter(options);
1114
+ }