Repository navigation
Expand file tree
/
Copy pathOpenCodeAdapterV2.ts
More file actions
3758 lines (3642 loc) · 148 KB
/
Copy pathOpenCodeAdapterV2.ts
File metadata and controls
3758 lines (3642 loc) · 148 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 type {
Event as OpenCodeEvent,
Message as OpenCodeMessage,
Part as OpenCodePart,
PermissionRequest,
PermissionRuleset,
QuestionRequest,
Session as OpenCodeSession,
Todo as OpenCodeTodo,
ToolPart,
} from "@opencode-ai/sdk/v2";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { causeErrorTag } from "@t3tools/shared/observability";
import {
defaultInstanceIdForDriver,
type ModelSelection,
type OpenCodeSettings,
type OrchestrationV2AppThread,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
type OrchestrationV2PlanStep,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2ProviderRef,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
OpenCodeSettings as OpenCodeSettingsSchema,
type PlanId,
ProviderDriverKind,
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderSessionId,
type RuntimeRequestId,
type ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import * as ServerConfig from "../../config.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
import * as ProviderEventLoggers from "../../provider/Layers/ProviderEventLoggers.ts";
import {
structuralProtocolMethod,
summarizeNativeProtocolPayload,
} from "../../provider/NativeProtocolLogging.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import { t3OrchestrationSystemPrompt } from "../../provider/T3OrchestrationInstructions.ts";
import { buildRuntimeInstructions } from "../../provider/RuntimeInstructions.ts";
import * as OpenCodeRuntime from "../../provider/opencodeRuntime.ts";
import * as IdAllocator from "../IdAllocator.ts";
import { makeProviderFailure } from "../ProviderFailure.ts";
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
import { providerMessageTextWithAttachmentPaths } from "../AttachmentPrompt.ts";
import * as ProviderAdapter from "../ProviderAdapter.ts";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "../ProviderAdapterDriver.ts";
import { makeSubagentChildThread, subagentThreadTitle } from "../SubagentProjection.ts";
import { openCodeToolTurnItem } from "./OpenCodeToolItems.ts";
export { openCodeToolProjectionKind } from "./OpenCodeToolItems.ts";
export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode");
export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_PROVIDER);
export const OPENCODE_SDK_PROTOCOL = "opencode-sdk.sse" as const;
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettingsSchema)({});
let openCodeMessageIdEpochMillis = -1;
let openCodeMessageIdCounter = 0;
const makeOpenCodeMessageId = Effect.fnUntraced(function* () {
const epochMillis = DateTime.toEpochMillis(yield* DateTime.now);
if (epochMillis !== openCodeMessageIdEpochMillis) {
openCodeMessageIdEpochMillis = epochMillis;
openCodeMessageIdCounter = 0;
}
openCodeMessageIdCounter += 1;
const encodedTime = BigInt.asUintN(
48,
BigInt(epochMillis) * 0x1000n + BigInt(openCodeMessageIdCounter),
)
.toString(16)
.padStart(12, "0");
const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const random = (yield* Effect.forEach(Array.from({ length: 28 }), () =>
Random.nextIntBetween(0, alphabet.length - 1),
))
.map((index) => alphabet[index])
.join("");
return `msg_${encodedTime}${random}`;
});
/**
* OpenCode's session, message, part, and interaction-request identifiers are
* durable. It does not expose a first-class turn object: the initiating user
* message is the best native turn correlation point, and session idle is the
* authoritative terminal signal.
*/
const OpenCodeProviderCapabilitiesV2 = {
sessions: {
// The current adapter owns one directory-bound client/server per session.
// Keep it isolated until its runtime is made safe for cross-thread pooling.
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: true,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: true,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
supportsSteeringByInterruptRestart: true,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: true,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: false,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: true,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: true,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: false,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: true,
emitsSubagentLifecycle: true,
canWaitForSubagents: true,
canCloseSubagents: false,
canForkSubagentThread: true,
},
context: {
acceptsSystemContext: false,
acceptsDeveloperContext: false,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: true,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "weak",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
runtimePolicy: {
enforcement: "native",
},
} satisfies OrchestrationV2ProviderCapabilities;
type TerminalTurnStatus = Extract<
OrchestrationV2ProviderTurn["status"],
"completed" | "interrupted" | "failed" | "cancelled"
>;
type OpenCodeStepUsage = Pick<
Extract<OpenCodePart, { readonly type: "step-finish" }>,
"id" | "tokens"
>;
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;
hasSubagents: boolean;
complete: 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,
hasSubagents: false,
complete: true,
};
}
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;
}
interface ActiveOpenCodeTurn {
readonly usage: OpenCodeTurnTokenUsageAccumulator;
readonly isRoot: boolean;
readonly threadId: ThreadId;
readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null;
readonly rootNodeId: ProviderAdapter.ProviderAdapterV2TurnInput["rootNodeId"];
readonly appThread: OrchestrationV2AppThread;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
readonly providerTurnOrdinal: number;
readonly runOrdinal: number;
readonly runAttemptId: OrchestrationV2ProviderTurn["runAttemptId"];
readonly startedAt: DateTime.Utc;
readonly itemOrdinals: Map<string, number>;
readonly parts: Map<string, Exclude<OpenCodePart, ToolPart>>;
readonly partIdsByMessage: Map<string, Set<string>>;
readonly toolNamesByCallId: Map<string, string>;
readonly providerTurn: OrchestrationV2ProviderTurn;
nextItemOrdinal: number;
nativeUserMessageId: string | null;
admissionMessageId: string | null;
interrupted: boolean;
finalized: boolean;
planId: PlanId | null;
admissionGeneration: number;
admissionReconciliationGeneration: number | null;
admissionPending: boolean;
admissionAccepted: boolean;
admissionMessageObserved: boolean;
idleDuringAdmission: boolean;
admissionSettled: Deferred.Deferred<void>;
admissionAbortController: AbortController | null;
}
type OpenCodeAdmissionSignal =
| "accepted"
| "assistant-completed"
| "busy"
| "idle"
| "user-message";
type OpenCodeAdmissionAction = "hold" | "reconcile-idle" | "release";
export function advanceOpenCodePromptAdmission(
admission: Pick<
ActiveOpenCodeTurn,
"admissionAccepted" | "admissionMessageObserved" | "admissionPending" | "idleDuringAdmission"
>,
signal: OpenCodeAdmissionSignal,
): OpenCodeAdmissionAction {
if (!admission.admissionPending) return "release";
if (signal === "assistant-completed") {
admission.admissionAccepted = true;
admission.admissionMessageObserved = true;
admission.admissionPending = false;
return "release";
}
if (signal === "idle") {
admission.idleDuringAdmission = true;
return "hold";
}
if (signal === "accepted") admission.admissionAccepted = true;
if (signal === "busy" || signal === "user-message") admission.admissionMessageObserved = true;
if (!admission.admissionAccepted || !admission.admissionMessageObserved) return "hold";
if (admission.idleDuringAdmission) return "reconcile-idle";
admission.admissionPending = false;
return "release";
}
export function cancelOpenCodePromptAdmission(
admission: Pick<ActiveOpenCodeTurn, "admissionGeneration" | "admissionPending">,
nextGeneration: number,
): void {
admission.admissionGeneration = nextGeneration;
admission.admissionPending = false;
}
export const reconcileOpenCodePromptAdmissionStatus = Effect.fn(
"reconcileOpenCodePromptAdmissionStatus",
)(function* (
admission: Pick<ActiveOpenCodeTurn, "admissionGeneration" | "admissionPending">,
generation: number,
readStatus: Effect.Effect<"busy" | "idle" | "unknown">,
) {
if (admission.admissionGeneration !== generation || !admission.admissionPending) {
return "stale" as const;
}
const status = yield* readStatus;
if (admission.admissionGeneration !== generation || !admission.admissionPending) {
return "stale" as const;
}
if (status !== "unknown") admission.admissionPending = false;
return status;
});
interface OpenCodeSubagentContext {
readonly nativeItemId: string;
readonly nodeId: OrchestrationV2Subagent["id"];
readonly parentState: OpenCodeThreadState;
readonly parentTurn: ActiveOpenCodeTurn;
readonly prompt: string;
readonly title: string | null;
readonly startedAt: DateTime.Utc;
childSessionId: string | null;
childThreadId: ThreadId | null;
childProviderThreadId: OrchestrationV2ProviderThread["id"] | null;
model: string | null;
result: string | null;
}
interface OpenCodeThreadState {
readonly nativeSessionId: string;
providerThread: OrchestrationV2ProviderThread;
appThread: OrchestrationV2AppThread | null;
activeTurn: ActiveOpenCodeTurn | null;
readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>;
readonly messages: Map<string, OrchestrationV2ConversationMessage>;
readonly runtimeRequests: Map<string, OrchestrationV2RuntimeRequest>;
readonly messageRoles: Map<string, "user" | "assistant">;
readonly userMessageIds: Array<string>;
parentSubagent: OpenCodeSubagentContext | null;
nextChildTurnOrdinal: number;
nextAdmissionGeneration: number;
}
interface OpenCodeRequestOwner {
readonly state: OpenCodeThreadState;
readonly turn: ActiveOpenCodeTurn;
/** The subagent on the owner's thread that leads to the asking session. */
readonly subagent: OpenCodeSubagentContext | null;
}
/**
* The top-level thread and active turn that own a session's requests, walking
* up through (possibly nested) subagents.
*/
function topLevelRequestOwner(state: OpenCodeThreadState): OpenCodeRequestOwner | undefined {
let owner = state;
let subagent: OpenCodeSubagentContext | null = null;
while (owner.parentSubagent !== null) {
subagent = owner.parentSubagent;
owner = subagent.parentState;
}
return owner.activeTurn === null ? undefined : { state: owner, turn: owner.activeTurn, subagent };
}
interface PendingOpenCodeRequest {
readonly requestId: RuntimeRequestId;
readonly nativeRequestId: string;
/** The session that asked, which may be a subagent's. */
readonly nativeSessionId: string;
readonly turn: ActiveOpenCodeTurn;
readonly state: OpenCodeThreadState;
readonly nodeId: OrchestrationV2ExecutionNode["id"];
readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
readonly turnItemId: OrchestrationV2TurnItem["id"];
readonly requestKind: OpenCodePermissionRequestKind | "user_input";
readonly createdAt: DateTime.Utc;
readonly permission?: PermissionRequest;
readonly question?: QuestionRequest;
}
export interface OpenCodeAdapterV2Options {
readonly instanceId: ProviderInstanceId;
readonly settings: OpenCodeSettings;
readonly environment: NodeJS.ProcessEnv;
readonly runtime: OpenCodeRuntime.OpenCodeRuntimeShape;
readonly idAllocator: IdAllocator.IdAllocatorV2Shape;
readonly serverConfig: ServerConfig.ServerConfig["Service"];
readonly nativeEventLogger?: EventNdjsonLogger;
}
export interface OpenCodeProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
readonly messageKind: "request" | "response" | "notification" | "error";
readonly method: string;
readonly payload: unknown;
}
function formatOpenCodeProtocolLogPayload(event: OpenCodeProtocolLogEvent) {
return {
direction: event.direction,
messageKind: event.messageKind,
method: structuralProtocolMethod(event.method),
payload: summarizeNativeProtocolPayload(event.payload),
};
}
export function makeOpenCodeProtocolLogger(input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly idAllocator: IdAllocator.IdAllocatorV2Shape;
readonly providerInstanceId: ProviderInstanceId;
readonly providerSessionId: ProviderSessionId;
readonly threadId: ThreadId;
}): (event: OpenCodeProtocolLogEvent) => Effect.Effect<void, never> {
return (event) =>
Effect.gen(function* () {
if (!input.nativeEventLogger) return;
const observedAt = DateTime.formatIso(yield* DateTime.now);
const method = structuralProtocolMethod(event.method);
yield* input.nativeEventLogger.write(
{
observedAt,
event: {
id: yield* input.idAllocator.allocate.rawEvent({
providerSessionId: input.providerSessionId,
method,
}),
kind: "protocol",
protocol: OPENCODE_SDK_PROTOCOL,
provider: OPENCODE_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
createdAt: observedAt,
threadId: input.threadId,
payload: formatOpenCodeProtocolLogPayload(event),
},
},
input.threadId,
);
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.interrupt
: Effect.logWarning("Failed to write native OpenCode event log.", {
errorTag: causeErrorTag(cause),
reasonCount: cause.reasons.length,
provider: OPENCODE_PROVIDER,
threadId: input.threadId,
}),
),
);
}
function protocolError(
detail: string,
payload?: unknown,
): ProviderAdapter.ProviderAdapterProtocolError {
return new ProviderAdapter.ProviderAdapterProtocolError({
driver: OPENCODE_PROVIDER,
detail,
...(payload === undefined ? {} : { payload }),
});
}
function nativeThreadId(providerThread: OrchestrationV2ProviderThread): string {
const nativeId = providerThread.nativeThreadRef?.nativeId;
if (nativeId === null || nativeId === undefined) {
throw protocolError(`Provider thread ${providerThread.id} has no OpenCode session id`);
}
return nativeId;
}
function dateTimeFromEpoch(value: number | undefined, fallback: DateTime.Utc): DateTime.Utc {
if (value === undefined) return fallback;
return Option.getOrElse(DateTime.make(value), () => fallback);
}
function nonEmptyString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
}
function recordValue(input: unknown, key: string): unknown {
return typeof input === "object" && input !== null && key in input
? (input as Record<string, unknown>)[key]
: undefined;
}
function recordString(input: unknown, ...keys: ReadonlyArray<string>): string | undefined {
for (const key of keys) {
const value = nonEmptyString(recordValue(input, key));
if (value !== undefined) return value;
}
return undefined;
}
function sdkResponseForRawLog(value: unknown): unknown {
if (typeof value !== "object" || value === null) return value;
if ("data" in value) return { data: (value as { readonly data?: unknown }).data ?? null };
if ("stream" in value) return { subscribed: true };
return value;
}
type OpenCodePermissionRequestKind = Extract<
ProviderRequestKind,
"command" | "file-read" | "file-change"
>;
export function openCodePermissionRequestKind(
permission: string,
toolName?: string,
): OpenCodePermissionRequestKind {
const normalized = permission.toLowerCase();
const normalizedTool = toolName?.toLowerCase() ?? "";
if (
normalized === "edit" ||
normalized === "write" ||
normalized === "patch" ||
normalized === "apply_patch" ||
normalizedTool === "edit" ||
normalizedTool === "write" ||
normalizedTool === "patch" ||
normalizedTool === "apply_patch"
) {
return "file-change";
}
if (
normalized === "read" ||
normalized === "glob" ||
normalized === "grep" ||
normalized === "lsp" ||
normalized === "external_directory" ||
normalizedTool === "read" ||
normalizedTool.includes("glob") ||
normalizedTool.includes("grep") ||
normalizedTool.includes("search")
) {
return "file-read";
}
return "command";
}
const OPENCODE_ALWAYS_ALLOWED_PERMISSIONS = [
"question",
"read",
"glob",
"grep",
"lsp",
"todowrite",
"task",
"skill",
] as const;
const OPENCODE_RESTRICTED_PERMISSIONS = [
"bash",
"edit",
"webfetch",
"websearch",
"codesearch",
"external_directory",
"doom_loop",
] as const;
/**
* OpenCode does not provide an OS sandbox, so permission rules are also the
* enforcement boundary for non-interactive policies. Read/planning tools are
* safe by default; edits are auto-approved only for workspace-write modes,
* while shell/network/external access remains gated unless policy explicitly
* allows it.
*/
export function openCodePermissionRules(
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
): PermissionRuleset {
const sandboxPolicy = recordValue(runtimePolicy, "sandboxPolicy");
const sandboxType = recordString(sandboxPolicy, "type");
const rawApprovalPolicy = runtimePolicy.approvalPolicy;
const approvalPolicy = nonEmptyString(rawApprovalPolicy);
const requiresApproval =
approvalPolicy === undefined
? (typeof rawApprovalPolicy === "object" && rawApprovalPolicy !== null) ||
runtimePolicy.runtimeMode !== "full-access"
: approvalPolicy !== "never";
const externallySandboxed = sandboxType === "externalSandbox";
const dangerFullAccess = sandboxType === "dangerFullAccess";
const implicitFullAccess =
sandboxType === undefined && runtimePolicy.runtimeMode === "full-access";
if (!requiresApproval && (externallySandboxed || dangerFullAccess || implicitFullAccess)) {
return [{ permission: "*", pattern: "*", action: "allow" }];
}
// Task sessions initially inherit only parent deny rules. Seed explicit
// denies before the effective ask/allow overrides so a child is safe during
// the short interval before emitSubagent installs its complete policy.
const rules: PermissionRuleset = [
{ permission: "*", pattern: "*", action: "deny" },
...OPENCODE_RESTRICTED_PERMISSIONS.map((permission) => ({
permission,
pattern: "*",
action: "deny" as const,
})),
];
if (requiresApproval) {
rules.push({ permission: "*", pattern: "*", action: "ask" });
for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) {
rules.push({ permission, pattern: "*", action: "ask" });
}
}
rules.push(
...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({
permission,
pattern: "*",
action: "allow" as const,
})),
);
rules.push(
{ permission: "read", pattern: "*.env", action: requiresApproval ? "ask" : "deny" },
{ permission: "read", pattern: "*.env.*", action: requiresApproval ? "ask" : "deny" },
{ permission: "read", pattern: "*.env.example", action: "allow" },
);
if (
runtimePolicy.runtimeMode === "auto-accept-edits" ||
(!requiresApproval && sandboxType === "workspaceWrite")
) {
rules.push({ permission: "edit", pattern: "*", action: "allow" });
}
if (!requiresApproval && recordValue(sandboxPolicy, "networkAccess") === true) {
for (const permission of ["webfetch", "websearch", "codesearch"] as const) {
rules.push({ permission, pattern: "*", action: "allow" });
}
}
if (!requiresApproval && sandboxType === "readOnly") {
const access = recordValue(sandboxPolicy, "access");
if (recordString(access, "type") === "fullAccess") {
rules.push({ permission: "external_directory", pattern: "*", action: "allow" });
}
}
if (!requiresApproval && sandboxType === "workspaceWrite") {
const writableRoots = recordValue(sandboxPolicy, "writableRoots");
if (Array.isArray(writableRoots)) {
for (const root of writableRoots) {
if (typeof root === "string" && root.trim().length > 0) {
rules.push({
permission: "external_directory",
pattern: `${root.replace(/\/$/, "")}/*`,
action: "allow",
});
}
}
}
}
return rules;
}
function permissionRuleEquals(
left: PermissionRuleset[number],
right: PermissionRuleset[number],
): boolean {
return (
left.permission === right.permission &&
left.pattern === right.pattern &&
left.action === right.action
);
}
/**
* OpenCode task sessions inherit only the parent's deny/external-directory
* rules and then add agent-specific restrictions such as disabling nested
* tasks. Install the complete parent policy while retaining only rules that
* were added specifically for the selected child agent.
*/
export function openCodeChildPermissionRules(
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
nativeChildRules: PermissionRuleset,
): PermissionRuleset {
const parentRules = openCodePermissionRules(runtimePolicy);
const inheritedRules = parentRules.filter(
(rule) => rule.permission === "external_directory" || rule.action === "deny",
);
const childSpecificRules = nativeChildRules.filter(
(childRule) =>
!inheritedRules.some((inheritedRule) => permissionRuleEquals(childRule, inheritedRule)),
);
return [...parentRules, ...childSpecificRules];
}
/**
* OpenCode's fork/revert boundary is exclusive. To retain the selected app
* turn, address the next native user message; omitting a boundary retains the
* current head when the selected turn is already last.
*/
export function openCodeBoundaryAfterProviderTurn(
providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
selectedProviderTurnId: OrchestrationV2ProviderTurn["id"],
): string | undefined {
const selected = providerTurns.find((turn) => turn.id === selectedProviderTurnId);
if (selected === undefined) return undefined;
return providerTurns
.filter((turn) => turn.ordinal > selected.ordinal)
.toSorted((left, right) => left.ordinal - right.ordinal)
.map((turn) => turn.nativeTurnRef?.nativeId)
.find((nativeId): nativeId is string => nativeId !== null && nativeId !== undefined);
}
function toolStatus(part: ToolPart): {
readonly node: OrchestrationV2ExecutionNode["status"];
readonly item: OrchestrationV2TurnItem["status"];
} {
switch (part.state.status) {
case "pending":
return { node: "pending", item: "pending" };
case "running":
return { node: "running", item: "running" };
case "completed":
return { node: "completed", item: "completed" };
case "error":
return { node: "failed", item: "failed" };
}
}
function toolInput(part: ToolPart): Record<string, unknown> {
return part.state.input;
}
function toolOutput(part: ToolPart): string | undefined {
if (part.state.status === "completed") return part.state.output;
if (part.state.status === "error") return part.state.error;
return undefined;
}
function toolStartedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc {
return dateTimeFromEpoch(
part.state.status === "pending" ? undefined : part.state.time.start,
now,
);
}
function toolCompletedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc | null {
return part.state.status === "completed" || part.state.status === "error"
? dateTimeFromEpoch(part.state.time.end, now)
: null;
}
function toolTitle(part: ToolPart): string | null {
return part.state.status === "running" || part.state.status === "completed"
? (part.state.title ?? null)
: null;
}
function toolModel(part: ToolPart): string | null {
const metadata =
part.state.status === "running" ||
part.state.status === "completed" ||
part.state.status === "error"
? part.state.metadata
: undefined;
const model = recordValue(metadata, "model");
const providerId = recordString(model, "providerID", "providerId");
const modelId = recordString(model, "modelID", "modelId", "id");
return providerId !== undefined && modelId !== undefined ? `${providerId}/${modelId}` : null;
}
function taskSessionId(part: ToolPart): string | null {
const metadata =
part.state.status === "running" ||
part.state.status === "completed" ||
part.state.status === "error"
? part.state.metadata
: undefined;
return recordString(metadata, "sessionId", "sessionID") ?? null;
}
function makeProviderThread(input: {
readonly idAllocator: IdAllocator.IdAllocatorV2Shape;
readonly providerInstanceId: ProviderInstanceId;
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
readonly nativeSession: OpenCodeSession;
readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"];
readonly now: DateTime.Utc;
}): OrchestrationV2ProviderThread {
const createdAt = dateTimeFromEpoch(input.nativeSession.time.created, input.now);
return {
id: input.idAllocator.derive.providerThread({
driver: OPENCODE_PROVIDER,
nativeThreadId: input.nativeSession.id,
}),
driver: OPENCODE_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
driver: OPENCODE_PROVIDER,
nativeId: input.nativeSession.id,
strength: "strong",
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: input.forkedFrom ?? null,
createdAt,
updatedAt: dateTimeFromEpoch(input.nativeSession.time.updated, input.now),
};
}
function providerRef(nativeId: string, strength: "strong" | "weak" = "strong") {
return {
driver: OPENCODE_PROVIDER,
nativeId,
strength,
} satisfies OrchestrationV2ProviderRef;
}
function openCodeErrorMessage(event: Extract<OpenCodeEvent, { type: "session.error" }>): string {
const error = event.properties.error;
if (error === undefined) return "OpenCode session failed without an error payload.";
return recordString(error.data, "message") ?? error.name;
}
function terminalStatusForError(
event: Extract<OpenCodeEvent, { type: "session.error" }>,
turn: ActiveOpenCodeTurn,
): TerminalTurnStatus {
return turn.interrupted || isMessageAbortedError(event) ? "interrupted" : "failed";
}
function isMessageAbortedError(event: Extract<OpenCodeEvent, { type: "session.error" }>): boolean {
return event.properties.error?.name === "MessageAbortedError";
}
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;
}
function unwrapData<A>(operation: string, result: { readonly data?: A }): NonNullable<A> {
if (result.data === undefined) {
throw new OpenCodeRuntime.OpenCodeRuntimeError({
operation,
detail: `OpenCode ${operation} returned no response payload.`,
});
}
return result.data as NonNullable<A>;
}
export function makeOpenCodeAdapterV2(
options: OpenCodeAdapterV2Options,
): ProviderAdapter.ProviderAdapterV2Shape {
const { idAllocator, runtime, serverConfig } = options;
return ProviderAdapter.ProviderAdapterV2.of({
instanceId: options.instanceId,
driver: OPENCODE_PROVIDER,
getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2),
planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
openSession: Effect.fn("OpenCodeAdapterV2.openSession")(
function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
const scope = yield* Effect.scope;
const cwd = input.runtimePolicy.cwd ?? serverConfig.cwd;
const connection = yield* runtime.connectToOpenCodeServer({
binaryPath: options.settings.binaryPath,
directory: cwd,
serverUrl: options.settings.serverUrl,
environment: options.environment,
});
const client = runtime.createOpenCodeSdkClient({
baseUrl: connection.url,
directory: cwd,
...(connection.external && options.settings.serverPassword
? { serverPassword: options.settings.serverPassword }
: {}),
});
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const hasT3Mcp = mcpSession !== undefined && !connection.external;
const orchestrationSystemPrompt = t3OrchestrationSystemPrompt(hasT3Mcp);
if (hasT3Mcp) {
yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
client.mcp.add({
name: "t3-code",
config: {
type: "remote",
url: mcpSession.endpoint,
headers: { Authorization: mcpSession.authorizationHeader },
oauth: false,
},
}),
);
}
const now = yield* DateTime.now;
let sessionEntity: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
status: "ready",
cwd,
model: input.modelSelection.model,
capabilities: OpenCodeProviderCapabilitiesV2,
createdAt: now,
updatedAt: now,
lastError: null,
};