Repository navigation
Expand file tree
/
Copy pathopencodeRuntime.ts
More file actions
1922 lines (1782 loc) · 68.6 KB
/
Copy pathopencodeRuntime.ts
File metadata and controls
1922 lines (1782 loc) · 68.6 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
// FILE: opencodeRuntime.ts
// Purpose: Starts OpenCode-compatible local servers and adapts their SDK/CLI data.
// Layer: Provider runtime utility
// Exports: OpenCodeRuntime, OpenCodeRuntimeLive, model/auth parsers, SDK helpers
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@synara/contracts";
import {
type ConsoleState,
createOpencodeClient,
type Agent,
type FilePartInput,
type OpencodeClient,
type PermissionRuleset,
type ProviderListResponse,
type QuestionAnswer,
type QuestionRequest,
} from "@opencode-ai/sdk/v2";
import {
Cause,
Data,
Deferred,
Effect,
Exit,
Fiber,
Layer,
Option,
Predicate as P,
Ref,
Result,
ServiceMap,
Scope,
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { NetService, type NetServiceShape } from "@synara/shared/Net";
import { splitLines } from "@synara/shared/text";
import type { ProcessTreeKiller } from "../terminal/processTreeKiller.ts";
import { buildOpenCodeCompatibleProcessEnv } from "./openCodeProcessEnv.ts";
import {
findProviderProcessExitUnprovenError,
teardownProviderProcessTree,
} from "./supervisedProcessTeardown.ts";
import { isWindowsShellCommandMissingResult } from "../shell-command-detection.ts";
import {
makeProviderMaintenanceOwnedResourceCoordinator,
type ProviderMaintenanceOwnedResourceCoordinator,
} from "./providerMaintenanceOwnedResources.ts";
import { makeProviderProcessOwnerTracker } from "./providerProcessOwnerTracker.ts";
import {
installPreparedEffectProcessSupervisor,
supervisePreparedEffectProcess,
} from "./windowsJobProcessSupervisor.ts";
import { prepareWindowsProviderProcessAsync } from "./windowsProviderProcess.ts";
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 20_000;
const DEFAULT_HOSTNAME = "127.0.0.1";
export const OPENCODE_LOCAL_SERVER_IDLE_TTL_MS = 5 * 60_000;
const OPENCODE_STARTUP_OUTPUT_MAX_CHARS = 4_000;
const REDACTED_STARTUP_SECRET = "[redacted]";
const STARTUP_OUTPUT_AUTHORIZATION_PATTERN =
/(["']?)(authorization)\1(\s*[:=]\s*)(["']?)(bearer\s+)?[^"'\s,;}]+\4/gi;
const STARTUP_OUTPUT_SECRET_ASSIGNMENT_PATTERN =
/(["']?)([A-Za-z0-9_-]*(?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|id[_-]?token|auth[_-]?token|bearer[_-]?token|token|secret|password)[A-Za-z0-9_-]*)\1(\s*[:=]\s*)(["']?)[^"'\s,;}]+\4/gi;
export interface OpenCodeCompatibleCliSpec {
readonly defaultBinaryPath: string;
readonly displayName: string;
readonly serverReadyPrefix: string;
readonly configContentEnvVar: string;
readonly dataDirectoryName: string;
readonly serverAuthUsername: string;
}
export const OPENCODE_CLI_SPEC: OpenCodeCompatibleCliSpec = {
defaultBinaryPath: "opencode",
displayName: "OpenCode",
serverReadyPrefix: "opencode server listening",
configContentEnvVar: "OPENCODE_CONFIG_CONTENT",
dataDirectoryName: "opencode",
serverAuthUsername: "opencode",
};
export const KILO_CLI_SPEC: OpenCodeCompatibleCliSpec = {
defaultBinaryPath: "kilo",
displayName: "Kilo",
serverReadyPrefix: "kilo server listening",
configContentEnvVar: "KILO_CONFIG_CONTENT",
dataDirectoryName: "kilo",
serverAuthUsername: "kilo",
};
export interface OpenCodeOwnedServerProcess {
readonly exitCode: Effect.Effect<number, never>;
/**
* Proves the complete owned process tree exited. Calls are serialized, a failed proof remains
* retryable, and calls after the first proven exit are idempotent.
*/
readonly stop: Effect.Effect<void, OpenCodeRuntimeError>;
}
export interface OpenCodeServerProcess extends OpenCodeOwnedServerProcess {
readonly url: string;
}
export interface OpenCodeServerConnection {
readonly url: string;
readonly exitCode: Effect.Effect<number, never> | null;
readonly external: boolean;
}
interface PooledOpenCodeServer {
readonly key: string;
readonly cliSpecKey: string;
readonly owner: OpenCodeOwnedServerProcess;
server: OpenCodeServerProcess | null;
readonly scope: Scope.Closeable;
readonly closeOnRelease: boolean;
refCount: number;
closeFailure: OpenCodeRuntimeError | null;
idleCloseFiber: Fiber.Fiber<void, never> | null;
exitWatchFiber: Fiber.Fiber<void, never> | null;
}
const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
readonly operation: string;
readonly cause?: unknown;
readonly detail: string;
}> {
static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
}
export function openCodeRuntimeErrorDetail(cause: unknown): string {
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
if (cause && typeof cause === "object") {
const anyCause = cause as Record<string, unknown>;
const status = (anyCause.response as { status?: number } | undefined)?.status;
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
try {
return `status=${status ?? "?"} body=${JSON.stringify(body ?? cause)}`;
} catch {
// ignore stringify failure
}
}
return String(cause);
}
export const runOpenCodeSdk = <A>(
operation: string,
fn: () => Promise<A>,
): Effect.Effect<A, OpenCodeRuntimeError> =>
Effect.tryPromise({
try: fn,
catch: (cause) =>
new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
}).pipe(Effect.withSpan(`opencode.${operation}`));
interface OpenCodeSdkResponseLike {
readonly error?: unknown;
readonly response?: {
readonly status?: number;
};
}
export const runOpenCodeSdkRequest = <A extends OpenCodeSdkResponseLike>(
operation: string,
fn: () => Promise<A>,
): Effect.Effect<A, OpenCodeRuntimeError> =>
runOpenCodeSdk(operation, fn).pipe(
Effect.flatMap((result) =>
result.error === undefined
? Effect.succeed(result)
: Effect.fail(
new OpenCodeRuntimeError({
operation,
detail:
typeof result.response?.status === "number"
? `${operation} request failed with status ${result.response.status}.`
: `${operation} request failed before receiving a response.`,
cause: result,
}),
),
),
);
export interface OpenCodeCommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number;
}
export interface OpenCodeInventory {
readonly providerList: ProviderListResponse;
readonly agents: ReadonlyArray<Agent>;
readonly consoleState: ConsoleState | null;
}
export interface ParsedOpenCodeModelSlug {
readonly providerID: string;
readonly modelID: string;
}
export interface OpenCodeCliModelDescriptor {
readonly slug: string;
readonly providerID: string;
readonly modelID: string;
readonly name: string;
readonly variants: ReadonlyArray<string>;
readonly supportedReasoningEfforts: ReadonlyArray<{
readonly value: string;
readonly label?: string;
readonly description?: string;
}>;
readonly defaultReasoningEffort?: string;
readonly contextWindowOptions?: ReadonlyArray<{
readonly value: string;
readonly label: string;
readonly isDefault?: true;
}>;
readonly defaultContextWindow?: string;
readonly isFree?: boolean;
}
export interface OpenCodePathInfo {
readonly home: string;
readonly state: string;
readonly config: string;
readonly worktree: string;
readonly directory: string;
}
export interface OpenCodeRuntimeShape {
readonly startOpenCodeServerProcess: (input: {
readonly binaryPath: string;
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly cwd?: string;
readonly port?: number;
readonly hostname?: string;
readonly timeoutMs?: number;
readonly experimentalWebSockets?: boolean;
/**
* Called atomically after process-tree supervision is installed but before readiness is awaited.
* Callers use this handoff to retain exact cleanup ownership if startup later fails.
*/
readonly onProcessOwned?: (process: OpenCodeOwnedServerProcess) => Effect.Effect<void, never>;
}) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
readonly connectToOpenCodeServer: (input: {
readonly binaryPath: string;
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly cwd?: string;
readonly serverUrl?: string | null;
readonly port?: number;
readonly hostname?: string;
readonly timeoutMs?: number;
readonly experimentalWebSockets?: boolean;
/**
* Makes a managed server private to one owner and closes it immediately
* when that owner's scope ends. Required before installing per-thread MCP
* credentials into process-scoped configuration.
*/
readonly poolIsolationKey?: string;
}) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
/**
* Live runtimes implement this pool control API. It remains optional so runtime test doubles
* that never create local pooled processes do not need a meaningless teardown implementation.
*/
readonly closeLocalServerPoolsForCliSpec?: (input: {
readonly cliSpec: OpenCodeCompatibleCliSpec;
}) => Effect.Effect<void, OpenCodeRuntimeError>;
readonly runOpenCodeCommand: (input: {
readonly binaryPath: string;
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly args: ReadonlyArray<string>;
readonly cwd?: string;
}) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
readonly createOpenCodeSdkClient: (input: {
readonly baseUrl: string;
readonly directory: string;
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly serverPassword?: string;
}) => OpencodeClient;
readonly loadOpenCodeInventory: (
client: OpencodeClient,
) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
readonly listOpenCodeCliModels: (input: {
readonly binaryPath: string;
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly cwd?: string;
}) => Effect.Effect<ReadonlyArray<OpenCodeCliModelDescriptor>, OpenCodeRuntimeError>;
readonly loadOpenCodeCredentialProviderIDs: (
client: OpencodeClient,
cliSpec?: OpenCodeCompatibleCliSpec,
) => Effect.Effect<ReadonlyArray<string>, never>;
}
function parseServerUrlFromOutput(output: string, readyPrefix: string): string | null {
for (const line of splitLines(output)) {
if (!line.startsWith(readyPrefix)) {
continue;
}
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
return match?.[1] ?? null;
}
return null;
}
function formatCommandPart(value: string): string {
return /^[A-Za-z0-9_./:=@+-]+$/.test(value) ? value : JSON.stringify(value);
}
// Startup output is user-visible on failures, so keep diagnostics while masking likely secrets.
function redactStartupOutput(value: string): string {
return value
.replace(
STARTUP_OUTPUT_AUTHORIZATION_PATTERN,
(_match, keyQuote, key, separator, valueQuote, scheme = "") =>
`${keyQuote}${key}${keyQuote}${separator}${valueQuote}${scheme}${REDACTED_STARTUP_SECRET}${valueQuote}`,
)
.replace(
STARTUP_OUTPUT_SECRET_ASSIGNMENT_PATTERN,
(_match, keyQuote, key, separator, valueQuote) =>
`${keyQuote}${key}${keyQuote}${separator}${valueQuote}${REDACTED_STARTUP_SECRET}${valueQuote}`,
);
}
function truncateStartupOutput(value: string): string | null {
const trimmed = redactStartupOutput(value).trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.length <= OPENCODE_STARTUP_OUTPUT_MAX_CHARS) {
return trimmed;
}
const remainingChars = trimmed.length - OPENCODE_STARTUP_OUTPUT_MAX_CHARS;
return `${trimmed.slice(0, OPENCODE_STARTUP_OUTPUT_MAX_CHARS)}\n\n[truncated ${remainingChars} chars]`;
}
function formatOpenCodeServerStartupDetail(input: {
readonly displayName: string;
readonly summary: string;
readonly binaryPath: string;
readonly args: ReadonlyArray<string>;
readonly readyPrefix: string;
readonly stdout: string;
readonly stderr: string;
}): string {
const stdout = truncateStartupOutput(input.stdout);
const stderr = truncateStartupOutput(input.stderr);
const command = [input.binaryPath, ...input.args].map(formatCommandPart).join(" ");
return [
input.summary,
`command: ${command}`,
`${input.displayName} ready prefix: ${JSON.stringify(input.readyPrefix)}`,
stdout ? `stdout:\n${stdout}` : "stdout: <empty>",
stderr ? `stderr:\n${stderr}` : "stderr: <empty>",
].join("\n\n");
}
function openCodeCompatibleCliSpecKey(cliSpec: OpenCodeCompatibleCliSpec): string {
return JSON.stringify({
defaultBinaryPath: cliSpec.defaultBinaryPath,
displayName: cliSpec.displayName,
serverReadyPrefix: cliSpec.serverReadyPrefix,
configContentEnvVar: cliSpec.configContentEnvVar,
dataDirectoryName: cliSpec.dataDirectoryName,
serverAuthUsername: cliSpec.serverAuthUsername,
});
}
function pooledOpenCodeServerKey(input: {
readonly binaryPath: string;
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly cwd?: string;
readonly port?: number;
readonly hostname?: string;
readonly experimentalWebSockets?: boolean;
readonly poolIsolationKey?: string;
}): string {
const cliSpec = input.cliSpec ?? OPENCODE_CLI_SPEC;
return JSON.stringify({
binaryPath: input.binaryPath,
cwd: input.cwd ?? null,
hostname: input.hostname ?? DEFAULT_HOSTNAME,
port: input.port ?? null,
experimentalWebSockets: input.experimentalWebSockets === true,
poolIsolationKey: input.poolIsolationKey ?? null,
cliSpec: openCodeCompatibleCliSpecKey(cliSpec),
});
}
export function parseOpenCodeModelSlug(
slug: string | null | undefined,
): ParsedOpenCodeModelSlug | null {
if (typeof slug !== "string") {
return null;
}
const trimmed = slug.trim();
const separator = trimmed.indexOf("/");
if (separator <= 0 || separator === trimmed.length - 1) {
return null;
}
return {
providerID: trimmed.slice(0, separator),
modelID: trimmed.slice(separator + 1),
};
}
function trimToNull(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function fallbackOpenCodeModelName(slug: string, parsedSlug: ParsedOpenCodeModelSlug): string {
return trimToNull(parsedSlug.modelID) ?? slug;
}
function numberToContextWindowValue(value: number): string | null {
if (!Number.isFinite(value) || value <= 0) return null;
if (value >= 1_000_000 && value % 1_000_000 === 0) return `${value / 1_000_000}m`;
if (value >= 1_000 && value % 1_000 === 0) return `${value / 1_000}k`;
return String(value);
}
function contextWindowLabel(value: string): string {
return value.toUpperCase();
}
function parseOpenCodeContextWindowOptions(object: Record<string, unknown>):
| {
readonly contextWindowOptions: ReadonlyArray<{
readonly value: string;
readonly label: string;
readonly isDefault?: true;
}>;
readonly defaultContextWindow: string;
}
| undefined {
const limit =
object.limit && typeof object.limit === "object"
? (object.limit as Record<string, unknown>)
: null;
const context =
typeof limit?.context === "number"
? numberToContextWindowValue(limit.context)
: trimToNull(limit?.context);
if (!context) return undefined;
return {
contextWindowOptions: [{ value: context, label: contextWindowLabel(context), isDefault: true }],
defaultContextWindow: context,
};
}
function readOpenCodeVariantEffort(
variantKey: string,
variantObject: Record<string, unknown>,
): string | null {
const directEffort =
trimToNull(variantObject.reasoningEffort) ??
trimToNull(variantObject.reasoning_effort) ??
trimToNull(variantObject.effort);
if (directEffort) {
return directEffort;
}
const thinkingConfig =
variantObject.thinkingConfig &&
typeof variantObject.thinkingConfig === "object" &&
!Array.isArray(variantObject.thinkingConfig)
? (variantObject.thinkingConfig as Record<string, unknown>)
: variantObject.thinking_config &&
typeof variantObject.thinking_config === "object" &&
!Array.isArray(variantObject.thinking_config)
? (variantObject.thinking_config as Record<string, unknown>)
: null;
const thinkingLevel =
trimToNull(thinkingConfig?.thinkingLevel) ?? trimToNull(thinkingConfig?.thinking_level);
if (thinkingLevel) {
return thinkingLevel;
}
const reasoning =
variantObject.reasoning &&
typeof variantObject.reasoning === "object" &&
!Array.isArray(variantObject.reasoning)
? (variantObject.reasoning as Record<string, unknown>)
: null;
const reasoningConfig =
variantObject.reasoningConfig &&
typeof variantObject.reasoningConfig === "object" &&
!Array.isArray(variantObject.reasoningConfig)
? (variantObject.reasoningConfig as Record<string, unknown>)
: variantObject.reasoning_config &&
typeof variantObject.reasoning_config === "object" &&
!Array.isArray(variantObject.reasoning_config)
? (variantObject.reasoning_config as Record<string, unknown>)
: null;
const nestedReasoningEffort =
trimToNull(reasoning?.effort) ??
trimToNull(reasoningConfig?.maxReasoningEffort) ??
trimToNull(reasoningConfig?.max_reasoning_effort);
if (nestedReasoningEffort) {
return nestedReasoningEffort;
}
if (
"thinking" in variantObject ||
"thinkingConfig" in variantObject ||
"thinking_config" in variantObject ||
"reasoning" in variantObject ||
"reasoningConfig" in variantObject ||
"reasoning_config" in variantObject ||
Object.keys(variantObject).length === 0
) {
return trimToNull(variantKey);
}
return null;
}
function resolveOpenCodeDataDirectory(
homeDirectory: string,
dataDirectoryName = "opencode",
): string {
if (process.platform === "win32") {
const appDataDirectory =
trimToNull(process.env.APPDATA) ?? join(homeDirectory, "AppData", "Roaming");
return join(appDataDirectory, dataDirectoryName);
}
const xdgDataHome =
trimToNull(process.env.XDG_DATA_HOME) ?? join(homeDirectory, ".local", "share");
return join(xdgDataHome, dataDirectoryName);
}
export function resolveOpenCodeAuthFilePath(
pathInfo: Pick<OpenCodePathInfo, "home">,
cliSpec: OpenCodeCompatibleCliSpec = OPENCODE_CLI_SPEC,
): string {
return join(resolveOpenCodeDataDirectory(pathInfo.home, cliSpec.dataDirectoryName), "auth.json");
}
export function parseOpenCodeCredentialProviderIDs(content: string): ReadonlyArray<string> {
const parsed = JSON.parse(content) as unknown;
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
return [];
}
return Object.entries(parsed as Record<string, unknown>)
.flatMap(([providerID, value]) =>
value && typeof value === "object" && !Array.isArray(value) ? [providerID.trim()] : [],
)
.filter((providerID) => providerID.length > 0)
.toSorted((left, right) => left.localeCompare(right));
}
function readJsonObjectBlock(
source: string,
startIndex: number,
): { readonly json: string; readonly nextIndex: number } | null {
if (source[startIndex] !== "{") {
return null;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = startIndex; index < source.length; index += 1) {
const char = source[index];
if (!char) {
break;
}
if (inString) {
if (escaping) {
escaping = false;
continue;
}
if (char === "\\") {
escaping = true;
continue;
}
if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return {
json: source.slice(startIndex, index + 1),
nextIndex: index + 1,
};
}
}
}
return null;
}
function parseOpenCodeCliModelJson(
value: unknown,
slug: string,
parsedSlug: ParsedOpenCodeModelSlug,
): OpenCodeCliModelDescriptor {
const object = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
const providerID = trimToNull(object.providerID) ?? parsedSlug.providerID;
const modelID = trimToNull(object.id) ?? parsedSlug.modelID;
const name = trimToNull(object.name) ?? fallbackOpenCodeModelName(slug, parsedSlug);
const variantsObject =
object.variants && typeof object.variants === "object" && !Array.isArray(object.variants)
? (object.variants as Record<string, unknown>)
: {};
const variants = Object.keys(variantsObject)
.map((variant) => variant.trim())
.filter((variant) => variant.length > 0)
.toSorted((left, right) => left.localeCompare(right));
const supportedReasoningEfforts = Array.from(
new Map(
Object.entries(variantsObject).flatMap(([variantKey, variant]) => {
const variantObject =
variant && typeof variant === "object" && !Array.isArray(variant)
? (variant as Record<string, unknown>)
: null;
if (!variantObject) {
return [];
}
const reasoningValue = readOpenCodeVariantEffort(variantKey, variantObject);
if (!reasoningValue) {
return [];
}
const label = trimToNull(variantObject.label) ?? undefined;
const description = trimToNull(variantObject.description) ?? undefined;
return [
[
reasoningValue,
{
value: reasoningValue,
...(label ? { label } : {}),
...(description ? { description } : {}),
},
] as const,
];
}),
).values(),
);
const defaultReasoningEffort =
trimToNull(object.defaultReasoningEffort) ??
trimToNull(object.default_reasoning_effort) ??
(object.options && typeof object.options === "object" && !Array.isArray(object.options)
? (trimToNull((object.options as Record<string, unknown>).reasoningEffort) ??
trimToNull((object.options as Record<string, unknown>).reasoning_effort) ??
trimToNull((object.options as Record<string, unknown>).effort))
: null) ??
undefined;
const contextWindowOptions = parseOpenCodeContextWindowOptions(object);
const isFree = object.isFree;
return {
slug,
providerID,
modelID,
name,
variants,
supportedReasoningEfforts,
...(defaultReasoningEffort ? { defaultReasoningEffort } : {}),
...(contextWindowOptions ?? {}),
...(typeof isFree === "boolean" ? { isFree } : {}),
};
}
export function parseOpenCodeCliModelsOutput(
output: string,
): ReadonlyArray<OpenCodeCliModelDescriptor> {
const models = new Map<string, OpenCodeCliModelDescriptor>();
let index = 0;
while (index < output.length) {
while (index < output.length && /\s/u.test(output[index]!)) {
index += 1;
}
if (index >= output.length) {
break;
}
const lineEnd = output.indexOf("\n", index);
const nextLineIndex = lineEnd === -1 ? output.length : lineEnd + 1;
const candidate = output.slice(index, lineEnd === -1 ? output.length : lineEnd).trim();
index = nextLineIndex;
const parsedSlug = parseOpenCodeModelSlug(candidate);
if (!parsedSlug) {
continue;
}
let descriptor: OpenCodeCliModelDescriptor = {
slug: candidate,
providerID: parsedSlug.providerID,
modelID: parsedSlug.modelID,
name: fallbackOpenCodeModelName(candidate, parsedSlug),
variants: [],
supportedReasoningEfforts: [],
};
while (index < output.length && /\s/u.test(output[index]!)) {
index += 1;
}
if (output[index] === "{") {
const block = readJsonObjectBlock(output, index);
if (block) {
try {
descriptor = parseOpenCodeCliModelJson(JSON.parse(block.json), candidate, parsedSlug);
} catch {
// Keep the slug-derived fallback descriptor when the JSON block cannot be parsed.
}
index = block.nextIndex;
}
}
models.set(descriptor.slug, descriptor);
}
return [...models.values()].toSorted(
(left, right) => left.name.localeCompare(right.name) || left.slug.localeCompare(right.slug),
);
}
function toListModelsCommandError(input: {
readonly binaryPath: string;
readonly args: ReadonlyArray<string>;
readonly stdout: string;
readonly stderr: string;
readonly code: number;
}): OpenCodeRuntimeError {
return new OpenCodeRuntimeError({
operation: "listOpenCodeCliModels",
detail: [
`Failed to execute '${input.binaryPath} ${input.args.join(" ")}' (exit code ${String(input.code)}).`,
input.stdout.trim().length > 0 ? `stdout:\n${input.stdout.trim()}` : null,
input.stderr.trim().length > 0 ? `stderr:\n${input.stderr.trim()}` : null,
]
.filter(Boolean)
.join("\n\n"),
cause: {
code: input.code,
stdout: input.stdout,
stderr: input.stderr,
},
});
}
function supportsVerboseModelsCommandFailure(stdout: string, stderr: string): boolean {
const combined = `${stdout}\n${stderr}`.toLowerCase();
return (
combined.includes("unknown argument: verbose") || combined.includes("unknown option: verbose")
);
}
export function openCodeQuestionId(
index: number,
question: QuestionRequest["questions"][number],
): string {
const header = question.header
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, "-");
return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
}
// OpenCode file parts reject many document MIME types; keep native parts to images.
export function toOpenCodeFileParts(input: {
readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
}): Array<FilePartInput> {
const parts: Array<FilePartInput> = [];
for (const attachment of input.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
const attachmentPath = input.resolveAttachmentPath(attachment);
if (!attachmentPath) {
continue;
}
parts.push({
type: "file",
mime: attachment.mimeType,
filename: attachment.name,
url: pathToFileURL(attachmentPath).href,
});
}
return parts;
}
export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
if (runtimeMode === "full-access") {
return [{ permission: "*", pattern: "*", action: "allow" }];
}
return [
{ permission: "*", pattern: "*", action: "ask" },
{ permission: "bash", pattern: "*", action: "ask" },
{ permission: "edit", pattern: "*", action: "ask" },
{ permission: "webfetch", pattern: "*", action: "ask" },
{ permission: "websearch", pattern: "*", action: "ask" },
{ permission: "codesearch", pattern: "*", action: "ask" },
{ permission: "external_directory", pattern: "*", action: "ask" },
{ permission: "doom_loop", pattern: "*", action: "ask" },
{ permission: "question", pattern: "*", action: "allow" },
];
}
export function buildOpenCodeServerProcessEnv(input: {
readonly cliSpec?: OpenCodeCompatibleCliSpec;
readonly experimentalWebSockets?: boolean;
readonly baseEnv?: NodeJS.ProcessEnv;
readonly platform?: NodeJS.Platform;
readonly isFile?: (path: string) => boolean;
}): NodeJS.ProcessEnv {
return buildOpenCodeCompatibleProcessEnv({
provider:
input.cliSpec?.dataDirectoryName === KILO_CLI_SPEC.dataDirectoryName ? "kilo" : "opencode",
baseEnv: input.baseEnv ?? process.env,
...(input.experimentalWebSockets !== undefined
? { experimentalWebSockets: input.experimentalWebSockets }
: {}),
...(input.platform ? { platform: input.platform } : {}),
...(input.isFile ? { isFile: input.isFile } : {}),
});
}
export function toOpenCodePermissionReply(
decision: ProviderApprovalDecision,
): "once" | "always" | "reject" {
switch (decision) {
case "accept":
return "once";
case "acceptForSession":
return "always";
case "decline":
case "cancel":
default:
return "reject";
}
}
export function toOpenCodeQuestionAnswers(
request: QuestionRequest,
answers: Record<string, unknown>,
): Array<QuestionAnswer> {
return request.questions.map((question, index) => {
const raw =
answers[openCodeQuestionId(index, question)] ??
answers[question.header] ??
answers[question.question];
if (Array.isArray(raw)) {
return raw.filter((value): value is string => typeof value === "string");
}
if (typeof raw === "string") {
return raw.trim().length > 0 ? [raw] : [];
}
return [];
});
}
function ensureRuntimeError(
operation: OpenCodeRuntimeError["operation"],
detail: string,
cause: unknown,
): OpenCodeRuntimeError {
return OpenCodeRuntimeError.is(cause)
? cause
: new OpenCodeRuntimeError({ operation, detail, cause });
}
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
Stream.runFold(
stream,
() => "",
(acc, chunk) => acc + new TextDecoder().decode(chunk),
);
type PrepareOpenCodeProcess = (
...args: Parameters<typeof prepareWindowsProviderProcessAsync>
) =>
| Awaited<ReturnType<typeof prepareWindowsProviderProcessAsync>>
| ReturnType<typeof prepareWindowsProviderProcessAsync>;
export interface OpenCodeRuntimeLiveOptions {
readonly platform?: NodeJS.Platform;
readonly prepareProcess?: PrepareOpenCodeProcess;
readonly superviseProcess?: typeof supervisePreparedEffectProcess;
readonly teardownProcessTree?: typeof teardownProviderProcessTree;
readonly processTreeKiller?: ProcessTreeKiller;
readonly netService?: NetServiceShape;
readonly maintenanceOwnedResources?: ProviderMaintenanceOwnedResourceCoordinator;
}
const makeOpenCodeRuntime = (options?: OpenCodeRuntimeLiveOptions) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const netService = yield* NetService;
const pooledServerScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const pooledServerMutex = yield* Semaphore.make(1);
const pooledServers = new Map<string, PooledOpenCodeServer>();
const maintenanceOwnedResources =
options?.maintenanceOwnedResources ??
(yield* makeProviderMaintenanceOwnedResourceCoordinator);
const oneShotOwnerTrackers = {
opencode: makeProviderProcessOwnerTracker({
provider: "opencode",
resourcePrefix: "opencode-runtime-command",
maintenanceOwnedResources,
}),
kilo: makeProviderProcessOwnerTracker({
provider: "kilo",
resourcePrefix: "kilo-runtime-command",
maintenanceOwnedResources,
}),
} as const;
const oneShotOwnerTrackerFor = (cliSpec: OpenCodeCompatibleCliSpec) =>
openCodeCompatibleCliSpecKey(cliSpec) === openCodeCompatibleCliSpecKey(KILO_CLI_SPEC)
? oneShotOwnerTrackers.kilo
: oneShotOwnerTrackers.opencode;
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
Effect.gen(function* () {
const platform = options?.platform ?? globalThis.process.platform;
const childEnv = buildOpenCodeServerProcessEnv({
...(input.cliSpec ? { cliSpec: input.cliSpec } : {}),
platform,
});
const cliSpec = input.cliSpec ?? OPENCODE_CLI_SPEC;
const prepared = yield* Effect.tryPromise({
try: () =>
Promise.resolve(
(options?.prepareProcess ?? prepareWindowsProviderProcessAsync)(
input.binaryPath,
input.args,
{
cwd: input.cwd,
env: childEnv,
platform,
},
),
),
catch: (cause) =>
ensureRuntimeError(
"runOpenCodeCommand",
`Failed to prepare ${cliSpec.displayName} command process: ${openCodeRuntimeErrorDetail(cause)}`,
cause,
),
});
const oneShotOwnerTracker = oneShotOwnerTrackerFor(cliSpec);
const owned = yield* Effect.uninterruptible(
Effect.gen(function* () {
const child = yield* spawner.spawn(
ChildProcess.make(prepared.command, prepared.args, {
shell: prepared.shell,
...(prepared.windowsHide ? { windowsHide: true } : {}),
...(prepared.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
...(input.cwd ? { cwd: input.cwd } : {}),
env: childEnv,
detached: platform !== "win32",
synaraExternallySupervised: true,
} as ChildProcess.CommandOptions & { readonly synaraExternallySupervised: true }),
);
const supervisorInstallation = yield* Effect.try({