forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenCodeAdapter.ts
More file actions
4195 lines (4009 loc) · 155 KB
/
Copy pathOpenCodeAdapter.ts
File metadata and controls
4195 lines (4009 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
EventId,
type OpenCodeSettings,
ProviderDriverKind,
ProviderInstanceId,
type ProviderRuntimeEvent,
type ProviderSendTurnInput,
type ProviderSession,
RuntimeItemId,
RuntimeRequestId,
ThreadId,
type ThreadTokenUsageSnapshot,
type ToolLifecycleItemType,
type TurnTokenUsage,
TurnId,
type UserInputQuestion,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
ProviderAdapterSessionClosedError,
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
import { buildRuntimeInstructions } from "../RuntimeInstructions.ts";
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import {
buildOpenCodePermissionRules,
OpenCodeRuntime,
OpenCodeRuntimeError,
openCodeQuestionId,
openCodeRuntimeErrorDetail,
parseOpenCodeModelSlug,
runOpenCodeSdk,
toOpenCodeFileParts,
toOpenCodePermissionReply,
toOpenCodeQuestionAnswers,
type OpenCodeServerConnection,
} from "../opencodeRuntime.ts";
import * as Option from "effect/Option";
const PROVIDER = ProviderDriverKind.make("opencode");
/**
* Bounded wait for the session-start context-usage metadata probes
* (`config.providers` + `config.get`). These are best-effort — the meter
* degrades gracefully without them — so a wedged fetch must not hold up
* session start (`Effect.ignore` handles rejection, not non-resolution,
* so an untimed fetch can hang `startSession` forever).
*/
const OPENCODE_CONTEXT_METADATA_PROBE_TIMEOUT_MS = 2_000;
/**
* Version tag stamped into the OpenCode resume cursor. Bump if the cursor
* shape changes so stale-shaped cursors written by older builds are ignored
* rather than misread (mirrors GROK_RESUME_VERSION / CURSOR_RESUME_VERSION).
*/
const OPENCODE_RESUME_VERSION = 1 as const;
/**
* Decode a persisted resume cursor into the upstream `ses_…` id. Anything
* that isn't a current-version cursor with a non-empty id means "no resume"
* rather than an error. Re-adopting the session id IS the resume mechanism —
* OpenCode scopes a conversation's history by session id.
*/
function parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | undefined {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return undefined;
}
const record = raw as Record<string, unknown>;
if (record.schemaVersion !== OPENCODE_RESUME_VERSION) {
return undefined;
}
if (typeof record.sessionId !== "string" || record.sessionId.trim().length === 0) {
return undefined;
}
return { sessionId: record.sessionId.trim() };
}
/**
* Whether an error definitively reports a missing session. Only a confirmed
* miss may silently start a fresh session; any other failure (the SDK client
* is `throwOnError: true`, so `session.get` rejects on every non-2xx) must
* propagate, or a transient blip resets a live thread to an empty one — the
* #3604 silent context loss. Decides on structured signals only, never free
* text: a numeric 404 or the exact `NotFoundError` name, found via a bounded walk
* over `cause`/`body`/`error`/`data`. An explicit non-404 status seals its
* subtree so a wrapped "NotFound" name can't reclassify a real failure.
* Exported for unit testing.
*/
export function isOpenCodeNotFound(cause: unknown): boolean {
const seen = new Set<unknown>();
const queue: Array<unknown> = [cause];
for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) {
const node = queue.shift();
if (node === null || typeof node !== "object" || seen.has(node)) {
continue;
}
seen.add(node);
const record = node as Record<string, unknown>;
const response = record.response;
const statuses = [
record.status,
record.statusCode,
response !== null && typeof response === "object"
? (response as { readonly status?: unknown }).status
: undefined,
].filter((status): status is number => typeof status === "number");
if (statuses.includes(404)) {
return true;
}
if (statuses.length > 0) {
continue;
}
const name = record.name;
if (typeof name === "string" && name.toLowerCase() === "notfounderror") {
return true;
}
for (const key of ["cause", "body", "error", "data"] as const) {
if (record[key] !== undefined) {
queue.push(record[key]);
}
}
}
return false;
}
/**
* Whether two directory spellings name the same location. Raw string
* equality misreads a trailing slash, `.`/`..` segment, or symlinked cwd
* (macOS `/tmp` → `/private/tmp`) as a cwd change, needlessly forking the
* session on every resume. Lexically equal paths short-circuit; otherwise
* both sides go through `realPath`, each falling back to its lexical form
* on failure (deleted directory, external-server path) — so the probe can
* only widen matches, never split them. Takes the services as arguments so
* adapter methods stay service-free. Exported for unit testing.
*/
export function isSameOpenCodeDirectory(
fileSystem: FileSystem.FileSystem,
path: Path.Path,
left: string,
right: string,
): Effect.Effect<boolean> {
const lexicalLeft = path.resolve(left);
const lexicalRight = path.resolve(right);
if (lexicalLeft === lexicalRight) {
return Effect.succeed(true);
}
const canonicalize = (lexical: string) =>
fileSystem.realPath(lexical).pipe(Effect.orElseSucceed(() => lexical));
return Effect.zipWith(
canonicalize(lexicalLeft),
canonicalize(lexicalRight),
(canonicalLeft, canonicalRight) => canonicalLeft === canonicalRight,
);
}
interface OpenCodeTurnSnapshot {
readonly id: TurnId;
readonly items: Array<unknown>;
}
type OpenCodeSubscribedEvent =
Awaited<ReturnType<OpencodeClient["event"]["subscribe"]>> extends {
readonly stream: AsyncIterable<infer TEvent>;
}
? TEvent
: never;
type OpenCodeSessionStatusEvent = Extract<
OpenCodeSubscribedEvent,
{ readonly type: "session.status" }
>;
const OpenCodeSessionStatusMap = Schema.Record(
Schema.String,
Schema.Struct({ type: Schema.String }),
);
const decodeOpenCodeSessionStatusMap = Schema.decodeUnknownOption(OpenCodeSessionStatusMap);
interface OpenCodeCancellation {
readonly turnId: TurnId | undefined;
readonly acknowledgment: Deferred.Deferred<void>;
readonly completion: Deferred.Deferred<void, ProviderAdapterRequestError>;
acknowledged?: boolean;
turnSettled?: boolean;
deferredIdleEvent?: OpenCodeSessionStatusEvent;
}
interface OpenCodeIdleReconciliation {
readonly turnId: TurnId;
readonly promptGeneration: number;
raw: unknown;
warned: boolean;
dirty: boolean;
fiber?: Fiber.Fiber<void, never>;
}
interface OpenCodePromptAdmission {
readonly generation: number;
readonly turnId: TurnId;
readonly messageId: string;
readonly priorAwaitingBusy: boolean;
readonly priorIdle: { readonly turnId: TurnId; readonly raw: unknown } | undefined;
idleDuringAdmission: { readonly turnId: TurnId; readonly raw: unknown } | undefined;
idleObservedAfterMessage: boolean;
messageObserved: boolean;
busyObserved: boolean;
idleStatusConfirmations: number;
accepted: boolean;
cancelled: boolean;
readonly acceptance: Deferred.Deferred<void>;
readonly submissionSettled: Deferred.Deferred<void>;
promptFiber?: Fiber.Fiber<void, ProviderAdapterRequestError>;
recoveryFiber?: Fiber.Fiber<void, never>;
recoveryRaw: unknown;
}
type OpenCodeTerminalRequestEvent = Extract<
OpenCodeSubscribedEvent,
{
readonly type: "permission.replied" | "question.replied" | "question.rejected";
}
>;
type OpenCodeAskedRequestEvent = Extract<
OpenCodeSubscribedEvent,
{ readonly type: "permission.asked" | "question.asked" }
>;
type OpenCodeRoutedRequestEvent = OpenCodeAskedRequestEvent | OpenCodeTerminalRequestEvent;
interface OpenCodeRequestRelationRetry {
warned: boolean;
fiber?: Fiber.Fiber<void, never>;
}
interface OpenCodePendingRequestRecovery {
warned: boolean;
rerun: boolean;
}
function trimText(value: string | undefined | null): string | undefined {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : undefined;
}
/**
* Token breakdown OpenCode attaches to assistant messages. Counts are
* cumulative over the session, so the last assistant message's total is the
* live window usage. Every field is optional: the type also admits degraded
* breakdowns (missing counters or a missing `cache` block) without throwing.
*/
export interface OpenCodeAssistantTokenCounts {
readonly input?: number;
readonly output?: number;
readonly reasoning?: number;
readonly cache?: { readonly read?: number; readonly write?: number };
}
/**
* Sanitize one OpenCode token counter: anything that is not a finite
* non-negative number becomes `0`. A `NaN` would defeat the `<= 0` guard,
* break the `===` dedup, and serialize to `null` in JSON.
*/
function openCodeTokenCounter(value: unknown): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.round(value) : 0;
}
/**
* Sum of an OpenCode message's disjoint token counters, mirroring the OpenCode
* web app's `tokenTotal`. Unlike Codex/Claude, OpenCode reports `reasoning`
* outside `output`, so the counters all sum. A missing or malformed counter
* degrades to zero via {@link openCodeTokenCounter}.
*/
export function openCodeTokenTotal(
tokens: OpenCodeAssistantTokenCounts | null | undefined,
): number {
return (
openCodeTokenCounter(tokens?.input) +
openCodeTokenCounter(tokens?.output) +
openCodeTokenCounter(tokens?.reasoning) +
openCodeTokenCounter(tokens?.cache?.read) +
openCodeTokenCounter(tokens?.cache?.write)
);
}
/**
* Build a {@link ThreadTokenUsageSnapshot} from an assistant message's
* cumulative counts and the model's context window; `undefined` when there
* are no tokens. `usedTokens` is clamped to `maxTokens` — OpenCode counts can
* momentarily exceed the limit (e.g. around auto-compaction), and a meter
* past 100% reads as a lie. `compactsAutomatically` defaults to `true`
* (OpenCode auto-compacts unless the config disables it); `last*` fields are
* omitted because nothing consumes them and OpenCode reports no
* previous-snapshot. Malformed counters degrade to zero via
* {@link openCodeTokenCounter} instead of throwing.
*/
export function buildOpenCodeContextWindowUsage(input: {
readonly tokens: OpenCodeAssistantTokenCounts | null | undefined;
readonly modelContextWindow?: number | null | undefined;
readonly compactsAutomatically?: boolean | undefined;
}): ThreadTokenUsageSnapshot | undefined {
const inputTokens = openCodeTokenCounter(input.tokens?.input);
const outputTokens = openCodeTokenCounter(input.tokens?.output);
const reasoningTokens = openCodeTokenCounter(input.tokens?.reasoning);
const cachedReadTokens = openCodeTokenCounter(input.tokens?.cache?.read);
const cachedWriteTokens = openCodeTokenCounter(input.tokens?.cache?.write);
const rawUsedTokens =
inputTokens + outputTokens + reasoningTokens + cachedReadTokens + cachedWriteTokens;
if (rawUsedTokens <= 0) {
return undefined;
}
const modelContextWindow =
typeof input.modelContextWindow === "number" &&
Number.isFinite(input.modelContextWindow) &&
input.modelContextWindow > 0
? input.modelContextWindow
: undefined;
const usedTokens =
modelContextWindow !== undefined ? Math.min(rawUsedTokens, modelContextWindow) : rawUsedTokens;
return {
usedTokens,
...(modelContextWindow !== undefined ? { maxTokens: modelContextWindow } : {}),
inputTokens,
cachedInputTokens: cachedReadTokens,
outputTokens,
reasoningOutputTokens: reasoningTokens,
compactsAutomatically: input.compactsAutomatically ?? true,
};
}
/**
* Whether two snapshots display identically. OpenCode re-broadcasts completed
* messages (finish-state updates, resume replays); skipping the equal case
* avoids persisting a duplicate `context-window.updated` activity per
* broadcast.
*/
export function isSameOpenCodeContextWindowUsage(
previous: ThreadTokenUsageSnapshot | undefined,
next: ThreadTokenUsageSnapshot | undefined,
): boolean {
return (
previous !== undefined &&
next !== undefined &&
previous.usedTokens === next.usedTokens &&
previous.maxTokens === next.maxTokens &&
previous.inputTokens === next.inputTokens &&
previous.cachedInputTokens === next.cachedInputTokens &&
previous.outputTokens === next.outputTokens &&
previous.reasoningOutputTokens === next.reasoningOutputTokens &&
previous.compactsAutomatically === next.compactsAutomatically
);
}
function openCodeEventSessionId(event: OpenCodeSubscribedEvent): string | undefined {
const properties = "properties" in event ? event.properties : undefined;
if (!properties || typeof properties !== "object") {
return undefined;
}
const sessionID = (properties as { readonly sessionID?: unknown }).sessionID;
const sessionIDFromProperties = typeof sessionID === "string" ? sessionID : undefined;
if (sessionIDFromProperties) {
return sessionIDFromProperties;
}
const info = (properties as { readonly info?: { readonly id?: unknown } }).info;
return info && typeof info.id === "string" ? info.id : undefined;
}
function openCodeEventSessionTitle(event: OpenCodeSubscribedEvent): string | undefined {
if (event.type !== "session.updated") {
return undefined;
}
const title = trimText(event.properties.info.title);
// OpenCode mints a placeholder title at session.create when no title was
// provided, and re-emits it on every `session.updated`. Mirroring it would
// overwrite the thread's real title (openCodeEventSessionTitle feeds the
// `thread.metadata.updated` mirror). Ignore OpenCode's auto-generated
// placeholders so the thread isn't locked onto them.
if (!title || isOpenCodeDefaultTitle(title)) {
return undefined;
}
return title;
}
function isOpenCodeAbortError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"name" in error &&
error.name === "MessageAbortedError"
);
}
function isOpenCodeChildRequestEvent(event: OpenCodeSubscribedEvent): boolean {
switch (event.type) {
case "permission.asked":
case "permission.replied":
case "question.asked":
case "question.replied":
case "question.rejected":
return true;
default:
return false;
}
}
const OPENCODE_DEFAULT_TITLE_PATTERN =
/^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
function isOpenCodeDefaultTitle(title: string): boolean {
return OPENCODE_DEFAULT_TITLE_PATTERN.test(title);
}
type OpenCodeTextPart = Extract<Part, { readonly type: "text" | "reasoning" }>;
type OpenCodeTextPartState = Pick<OpenCodeTextPart, "id" | "messageID" | "type" | "time"> & {
text: string | undefined;
emittedText: string | undefined;
completed: boolean;
};
type OpenCodeStepUsage = Pick<Extract<Part, { readonly type: "step-finish" }>, "id" | "tokens">;
interface OpenCodeSessionContext {
session: ProviderSession;
readonly client: OpencodeClient;
readonly server: OpenCodeServerConnection;
readonly directory: string;
readonly openCodeSessionId: string;
readonly relatedSessionIds: Set<string>;
readonly resolvedRequestIds: Set<string>;
readonly autoRepliedRequestIds: Set<string>;
readonly emittedTerminalRequestIds: Set<string>;
readonly requestRelationRetries: Map<string, OpenCodeRequestRelationRetry>;
readonly pendingPermissions: Map<string, PermissionRequest>;
readonly pendingQuestions: Map<string, QuestionRequest>;
/** False once teardown starts so the event pump cannot open new requests. */
readonly acceptingRequests: Ref.Ref<boolean>;
/**
* Serializes `permission.asked` / `question.asked` against pending settlement
* so an in-flight asked handler cannot emit `request.opened` after teardown
* has already cancelled the same id.
*/
readonly pendingGate: Semaphore.Semaphore;
readonly messageRoleById: Map<string, "user" | "assistant">;
// OpenCode permits edits to completed parts. Keep text for snapshot comparison
// until native removal or session teardown, but do not retain other part payloads.
readonly textPartsByMessageId: Map<string, Map<string, OpenCodeTextPartState>>;
readonly turns: Array<OpenCodeTurnSnapshot>;
/**
* `providerID/modelID` → model context window (tokens). `null` means the
* model has no known limit. Final once `modelContextWindowCacheLoaded` is
* set — a failed fetch is not retried.
*/
readonly modelContextWindowCache: Map<string, number | null>;
modelContextWindowCacheLoaded: boolean;
/**
* Whether the session auto-compacts its context, from the config
* `compaction.auto` setting.
*/
compactsAutomatically: boolean;
/**
* Last emitted usage snapshot; dedup guard for re-broadcast
* `message.updated` events with unchanged cumulative counts.
*/
lastEmittedContextWindowUsage: ThreadTokenUsageSnapshot | undefined;
turnTokenUsage: OpenCodeTurnTokenUsageAccumulator | undefined;
activeTurnId: TurnId | undefined;
activeAgent: string | undefined;
activeVariant: string | undefined;
cancellation: OpenCodeCancellation | undefined;
interruptedTurnId: TurnId | undefined;
reconcileIdleStatus: boolean;
awaitingBusyAfterInterruption: boolean;
pendingIdleReconciliation: OpenCodeIdleReconciliation | undefined;
pendingRequestRecovery: OpenCodePendingRequestRecovery | undefined;
promptGeneration: number;
promptAdmission: OpenCodePromptAdmission | undefined;
readonly promptSemaphore: Semaphore.Semaphore;
readonly firstConnection: Deferred.Deferred<void, ProviderAdapterRequestError>;
/**
* One-shot guard flipped by `stopOpenCodeContext` / `emitUnexpectedExit`.
* The session lifecycle is owned by `sessionScope`; this Ref exists only
* so concurrent callers can race the transition safely via `getAndSet`.
*/
readonly stopped: Ref.Ref<boolean>;
/**
* Sole lifecycle handle for the session. Closing this scope:
* - aborts the `AbortController` registered as a finalizer
* (cancels the in-flight `event.subscribe` fetch),
* - interrupts the event-pump and server-exit fibers forked
* via `Effect.forkIn(sessionScope)`,
* - tears down the OpenCode server process for scope-owned servers.
*/
readonly sessionScope: Scope.Closeable;
}
interface OpenCodeTurnTokenUsageAccumulator {
readonly partIds: Set<string>;
readonly promptMessageIds: Set<string>;
readonly assistantOwnershipByMessageId: Map<string, "owned" | "other" | "unknown">;
// Native removal does not undo usage. Keep unresolved counts until this turn settles.
readonly unresolvedStepsByMessageId: Map<string, Map<string, OpenCodeStepUsage>>;
inputTokens: number;
cachedInputTokens: number;
cacheCreationTokens: number;
outputTokens: number;
reasoningTokens: number;
complete: boolean;
hasSubagents: boolean;
}
function makeOpenCodeTurnTokenUsageAccumulator(): OpenCodeTurnTokenUsageAccumulator {
return {
partIds: new Set(),
promptMessageIds: new Set(),
assistantOwnershipByMessageId: new Map(),
unresolvedStepsByMessageId: new Map(),
inputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
complete: true,
hasSubagents: false,
};
}
function accumulateOpenCodeStepUsage(
accumulator: OpenCodeTurnTokenUsageAccumulator,
part: OpenCodeStepUsage,
): void {
if (accumulator.partIds.has(part.id)) return;
accumulator.partIds.add(part.id);
accumulator.inputTokens += part.tokens.input + part.tokens.cache.read + part.tokens.cache.write;
accumulator.cachedInputTokens += part.tokens.cache.read;
accumulator.cacheCreationTokens += part.tokens.cache.write;
accumulator.outputTokens += part.tokens.output + part.tokens.reasoning;
accumulator.reasoningTokens += part.tokens.reasoning;
}
function takeOpenCodeTurnTokenUsage(
context: OpenCodeSessionContext,
complete: boolean,
): TurnTokenUsage {
const usage = context.turnTokenUsage;
context.turnTokenUsage = undefined;
if (!usage || usage.partIds.size === 0) {
return {
usageStatus: "unavailable",
usageScope: "main_agent",
hasSubagents: usage?.hasSubagents ?? false,
};
}
return {
usageStatus:
complete && usage.complete && usage.unresolvedStepsByMessageId.size === 0
? "complete"
: "partial",
usageScope: "main_agent",
inputTokens: usage.inputTokens,
cachedInputTokens: usage.cachedInputTokens,
cacheCreationTokens: usage.cacheCreationTokens,
outputTokens: usage.outputTokens,
reasoningTokens: Math.min(usage.outputTokens, usage.reasoningTokens),
hasSubagents: usage.hasSubagents,
};
}
export interface OpenCodeAdapterLiveOptions {
readonly instanceId?: ProviderInstanceId;
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
}
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
/**
* Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into
* the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call
* sites pipe through this in `Effect.mapError` so they never build the error
* shape by hand.
*/
const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: cause.operation,
detail: cause.detail,
cause: cause.cause,
});
/**
* Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The
* typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}),
* in which case we preserve its `detail`; otherwise we fall back to
* {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.).
*/
const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
cause,
});
type EventBaseInput = {
readonly threadId: ThreadId;
readonly turnId?: TurnId | undefined;
readonly itemId?: string | undefined;
readonly requestId?: string | undefined;
readonly createdAt?: string | undefined;
readonly raw?: unknown;
};
function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {
const normalized = toolName.toLowerCase();
if (normalized === "todowrite" || normalized === "todoread") {
return "dynamic_tool_call";
}
if (normalized.includes("bash") || normalized.includes("command")) {
return "command_execution";
}
if (
normalized.includes("edit") ||
normalized.includes("write") ||
normalized.includes("patch") ||
normalized.includes("multiedit")
) {
return "file_change";
}
if (normalized.includes("web")) {
return "web_search";
}
if (normalized.includes("mcp")) {
return "mcp_tool_call";
}
if (normalized.includes("image")) {
return "image_view";
}
if (
normalized.includes("task") ||
normalized.includes("agent") ||
normalized.includes("subtask")
) {
return "collab_agent_tool_call";
}
return "dynamic_tool_call";
}
function mapPermissionToRequestType(
permission: string,
): "command_execution_approval" | "file_read_approval" | "file_change_approval" {
switch (permission) {
case "read":
return "file_read_approval";
case "edit":
return "file_change_approval";
default:
// Every OpenCode permission needs an actionable approval in each client.
return "command_execution_approval";
}
}
function mapPermissionDecision(reply: "once" | "always" | "reject"): string {
switch (reply) {
case "once":
return "accept";
case "always":
return "acceptForSession";
case "reject":
default:
return "decline";
}
}
const ensureSessionContext = Effect.fn("ensureSessionContext")(function* (
sessions: ReadonlyMap<ThreadId, OpenCodeSessionContext>,
threadId: ThreadId,
) {
const session = sessions.get(threadId);
if (!session) {
return yield* new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
});
}
if (yield* Ref.get(session.stopped)) {
return yield* new ProviderAdapterSessionClosedError({
provider: PROVIDER,
threadId,
});
}
return session;
});
function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
return request.questions.map((question, index) => ({
id: openCodeQuestionId(index, question),
header: question.header,
question: question.question,
options: question.options.map((option) => ({
label: option.label,
description: option.description,
})),
...(question.multiple ? { multiSelect: true } : {}),
}));
}
function resolveTextStreamKind(part: Pick<Part, "type">): "assistant_text" | "reasoning_text" {
return part.type === "reasoning" ? "reasoning_text" : "assistant_text";
}
function retainOpenCodeTextPart(
context: OpenCodeSessionContext,
part: OpenCodeTextPart,
): OpenCodeTextPartState {
const parts =
context.textPartsByMessageId.get(part.messageID) ?? new Map<string, OpenCodeTextPartState>();
const previous = parts.get(part.id);
const state = {
id: part.id,
messageID: part.messageID,
type: part.type,
text: part.text,
...(part.time !== undefined ? { time: part.time } : {}),
emittedText: previous?.emittedText,
completed: previous?.completed ?? false,
};
parts.set(part.id, state);
context.textPartsByMessageId.set(part.messageID, parts);
return state;
}
function commonPrefixLength(left: string, right: string): number {
let index = 0;
while (index < left.length && index < right.length && left[index] === right[index]) {
index += 1;
}
return index;
}
function resolveLatestAssistantText(previousText: string | undefined, nextText: string): string {
if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) {
return previousText;
}
return nextText;
}
export function mergeOpenCodeAssistantText(
previousText: string | undefined,
nextText: string,
): {
readonly latestText: string;
readonly deltaToEmit: string;
} {
const latestText = resolveLatestAssistantText(previousText, nextText);
const previous = previousText ?? "";
const prefixLength = latestText.startsWith(previous)
? previous.length
: commonPrefixLength(previous, latestText);
return {
latestText,
deltaToEmit: latestText.slice(prefixLength),
};
}
function appendOpenCodeAssistantTextDelta(
previousText: string,
delta: string,
): {
readonly nextText: string;
readonly deltaToEmit: string;
} {
return {
nextText: previousText + delta,
deltaToEmit: delta,
};
}
const isoFromEpochMs = (value: number) =>
DateTime.make(value).pipe(
Option.match({
onNone: () => undefined,
onSome: DateTime.formatIso,
}),
);
function messageRoleForPart(
context: OpenCodeSessionContext,
part: Pick<Part, "messageID" | "type">,
): "assistant" | "user" | undefined {
const known = context.messageRoleById.get(part.messageID);
if (known) {
return known;
}
return part.type === "tool" ? "assistant" : undefined;
}
function detailFromToolPart(part: Extract<Part, { type: "tool" }>): string | undefined {
switch (part.state.status) {
case "completed":
return part.state.output;
case "error":
return part.state.error;
case "running":
return part.state.title;
default:
return undefined;
}
}
function toolStateCreatedAt(part: Extract<Part, { type: "tool" }>): string | undefined {
switch (part.state.status) {
case "running":
return isoFromEpochMs(part.state.time.start);
case "completed":
case "error":
return isoFromEpochMs(part.state.time.end);
default:
return undefined;
}
}
function sessionErrorMessage(error: unknown): string {
if (!error || typeof error !== "object") {
return "OpenCode session failed.";
}
const data = "data" in error && error.data && typeof error.data === "object" ? error.data : null;
const message = data && "message" in data ? data.message : null;
return typeof message === "string" && message.trim().length > 0
? message
: "OpenCode session failed.";
}
function updateProviderSession(
context: OpenCodeSessionContext,
patch: Partial<ProviderSession>,
options?: {
readonly clearActiveTurnId?: boolean;
readonly clearLastError?: boolean;
},
): Effect.Effect<ProviderSession> {
return Effect.gen(function* () {
return applyProviderSessionUpdate(context, patch, options, yield* nowIso);
});
}
function applyProviderSessionUpdate(
context: OpenCodeSessionContext,
patch: Partial<ProviderSession>,
options:
| {
readonly clearActiveTurnId?: boolean;
readonly clearLastError?: boolean;
}
| undefined,
updatedAt: string,
): ProviderSession {
const nextSession = {
...context.session,
...patch,
updatedAt,
} as ProviderSession & Record<string, unknown>;
const mutableSession = nextSession as Record<string, unknown>;
if (options?.clearActiveTurnId) {
delete mutableSession.activeTurnId;
}
if (options?.clearLastError) {
delete mutableSession.lastError;
}
context.session = nextSession;
return nextSession;
}
const failPendingOpenCodeCancellation = Effect.fn("failPendingOpenCodeCancellation")(function* (
context: OpenCodeSessionContext,
detail: string,
) {
const cancellation = context.cancellation;
if (!cancellation) {
return;
}
context.cancellation = undefined;
yield* Deferred.fail(
cancellation.completion,
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session.abort",
detail,
}),
).pipe(Effect.ignore);
});
const abortOpenCodeDescendants = Effect.fn("abortOpenCodeDescendants")(function* (
context: OpenCodeSessionContext,
) {
const visited = new Set([context.openCodeSessionId]);
const requestSemaphore = Semaphore.makeUnsafe(8);
const visit = (
sessionId: string,
abortSession: boolean,
): Effect.Effect<OpenCodeRuntimeError | undefined> =>
Effect.gen(function* () {
let firstFailure: OpenCodeRuntimeError | undefined;
if (abortSession) {
const abortResult = yield* requestSemaphore
.withPermit(
runOpenCodeSdk("session.abort", (signal) =>
context.client.session.abort({ sessionID: sessionId }, { signal }),
),
)
.pipe(
Effect.catchIf(
(cause) => isOpenCodeNotFound(cause),
() => Effect.void,
),
Effect.result,
);
if (abortResult._tag === "Failure") {
firstFailure = abortResult.failure;
}
}
const childrenResult = yield* requestSemaphore
.withPermit(
runOpenCodeSdk("session.children", (signal) =>
context.client.session.children({ sessionID: sessionId }, { signal }),
),
)
.pipe(
Effect.catchIf(
(cause) => isOpenCodeNotFound(cause),
() => Effect.void,
),
Effect.result,
);
if (childrenResult._tag === "Failure") {
return firstFailure ?? childrenResult.failure;
}
const children = childrenResult.success?.data ?? [];
const newChildren = children.filter((child) => {
if (visited.has(child.id)) {
return false;
}
visited.add(child.id);
return true;
});
const childFailures = yield* Effect.forEach(newChildren, (child) => visit(child.id, true), {
concurrency: 8,
});
firstFailure ??= childFailures.find((failure) => failure !== undefined);
return firstFailure;
});
const firstFailure = yield* visit(context.openCodeSessionId, false);
if (firstFailure) {
return yield* firstFailure;
}
});
const abortOpenCodeSessionForTeardown = Effect.fn("abortOpenCodeSessionForTeardown")(function* (
context: OpenCodeSessionContext,
) {
// Stop the parent before the snapshot so it cannot add another child after
// the adapter reads the tree.