-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathOpenCodeProvider.ts
More file actions
597 lines (542 loc) · 17.5 KB
/
OpenCodeProvider.ts
File metadata and controls
597 lines (542 loc) · 17.5 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
import {
ProviderDriverKind,
type ModelCapabilities,
type OpenCodeSettings,
type ServerProviderModel,
type ServerProviderSkill,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { createModelCapabilities } from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
buildServerProvider,
nonEmptyTrimmed,
parseGenericCliVersion,
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
type OpenCodeInventory,
} from "../opencodeRuntime.ts";
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
const PROVIDER = ProviderDriverKind.make("opencode");
const OPENCODE_PRESENTATION = {
displayName: "OpenCode",
showInteractionModeToggle: false,
} as const;
const MINIMUM_OPENCODE_VERSION = "1.14.19";
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
readonly cause: unknown;
readonly detail: string;
}> {}
function normalizeProbeMessage(message: string): string | undefined {
const trimmed = message.trim();
if (trimmed.length === 0) {
return undefined;
}
if (
trimmed === "An error occurred in Effect.tryPromise" ||
trimmed === "An error occurred in Effect.try"
) {
return undefined;
}
return trimmed;
}
function normalizedErrorMessage(cause: unknown): string | undefined {
if (cause instanceof OpenCodeProbeError) {
return normalizeProbeMessage(cause.detail);
}
if (!(cause instanceof Error)) {
return undefined;
}
return normalizeProbeMessage(cause.message);
}
function formatOpenCodeProbeError(input: {
readonly cause: unknown;
readonly isExternalServer: boolean;
readonly serverUrl: string;
}): { readonly installed: boolean; readonly message: string } {
const detail = normalizedErrorMessage(input.cause);
const lower = detail?.toLowerCase() ?? "";
if (input.isExternalServer) {
if (
lower.includes("401") ||
lower.includes("403") ||
lower.includes("unauthorized") ||
lower.includes("forbidden")
) {
return {
installed: true,
message: "OpenCode server rejected authentication. Check the server URL and password.",
};
}
if (
lower.includes("econnrefused") ||
lower.includes("enotfound") ||
lower.includes("fetch failed") ||
lower.includes("networkerror") ||
lower.includes("timed out") ||
lower.includes("timeout") ||
lower.includes("socket hang up")
) {
return {
installed: true,
message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
};
}
return {
installed: true,
message: detail ?? "Failed to connect to the configured OpenCode server.",
};
}
if (lower.includes("enoent") || lower.includes("notfound")) {
return {
installed: false,
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
};
}
if (lower.includes("quarantine")) {
return {
installed: true,
message:
"macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
};
}
if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
return {
installed: true,
message:
"macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.",
};
}
return {
installed: true,
message: detail
? `Failed to execute OpenCode CLI health check: ${detail}`
: "Failed to execute OpenCode CLI health check.",
};
}
function titleCaseSlug(value: string): string {
return value
.split(/[-_/]+/)
.filter((segment) => segment.length > 0)
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
.join(" ");
}
function inferDefaultVariant(
providerID: string,
variants: ReadonlyArray<string>,
): string | undefined {
if (variants.length === 1) {
return variants[0];
}
if (providerID === "anthropic" || providerID.startsWith("google")) {
return variants.includes("high") ? "high" : undefined;
}
if (providerID === "openai" || providerID === "opencode") {
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
}
return undefined;
}
function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
}
const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
function openCodeCapabilitiesForModel(input: {
readonly providerID: string;
readonly model: ProviderListResponse["all"][number]["models"][string];
readonly agents: ReadonlyArray<Agent>;
}): ModelCapabilities {
const variantValues = Object.keys(input.model.variants ?? {});
const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
const variantOptions = variantValues.map((value) =>
defaultVariant === value
? { id: value, label: titleCaseSlug(value), isDefault: true as const }
: { id: value, label: titleCaseSlug(value) },
);
const primaryAgents = input.agents.filter(
(agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
);
const defaultAgent = inferDefaultAgent(primaryAgents);
const agentOptions = primaryAgents.map((agent) =>
defaultAgent === agent.name
? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }
: { id: agent.name, label: titleCaseSlug(agent.name) },
);
return createModelCapabilities({
optionDescriptors: [
...(variantOptions.length > 0
? [
{
id: "variant",
label: "Variant",
type: "select" as const,
options: variantOptions,
...(defaultVariant ? { currentValue: defaultVariant } : {}),
},
]
: []),
...(agentOptions.length > 0
? [
{
id: "agent",
label: "Agent",
type: "select" as const,
options: agentOptions,
...(defaultAgent ? { currentValue: defaultAgent } : {}),
},
]
: []),
],
});
}
const SKILLS_DIR_NAME = ".agents";
const SKILLS_SUBDIR_NAME = "skills";
const SKILL_FILE_NAME = "SKILL.md";
function parseSkillFrontmatter(
content: string,
): { name: string; description?: string; displayName?: string } | null {
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (!frontmatterMatch) {
return null;
}
const frontmatter = frontmatterMatch[1]!;
const nameMatch = frontmatter.match(/^name:\s*(.+)$/m);
if (!nameMatch) {
return null;
}
const name = nameMatch[1]!.trim();
if (name.length === 0) {
return null;
}
const descMatch = frontmatter.match(/^description:\s*(?:>\s*\n([\s\S]*?)|(.+))?$/m);
let description: string | undefined;
if (descMatch) {
const raw = descMatch[1] ?? descMatch[2];
if (raw) {
description = raw
.split("\n")
.map((line) => line.replace(/^\s*\|?\s*/, ""))
.join(" ")
.trim();
}
}
const displayNameMatch = frontmatter.match(/^displayName:\s*(.+)$/m);
const displayName = displayNameMatch ? displayNameMatch[1]!.trim() : undefined;
const result: { name: string; description?: string; displayName?: string } = { name };
if (description !== undefined) {
result.description = description;
}
if (displayName !== undefined) {
result.displayName = displayName;
}
return result;
}
function loadOpenCodeSkills(
cwd: string,
): Effect.Effect<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const skillsDir = path.join(cwd, SKILLS_DIR_NAME, SKILLS_SUBDIR_NAME);
const entriesExit = yield* Effect.exit(fs.readDirectory(skillsDir, { recursive: false }));
if (entriesExit._tag !== "Success") {
return [];
}
const skills: Array<ServerProviderSkill> = [];
for (const entryName of entriesExit.value) {
const fullPath = path.join(skillsDir, entryName);
const statExit = yield* Effect.exit(fs.stat(fullPath));
if (statExit._tag !== "Success" || statExit.value.type !== "Directory") {
continue;
}
const contentExit = yield* Effect.exit(
fs.readFileString(path.join(fullPath, SKILL_FILE_NAME)),
);
if (contentExit._tag !== "Success") {
continue;
}
const parsed = parseSkillFrontmatter(contentExit.value);
if (!parsed) {
continue;
}
const shortDescription =
parsed.description && parsed.description.length > 200
? parsed.description.slice(0, 200) + "..."
: parsed.description;
const skill: ServerProviderSkill = {
name: parsed.name,
path: fullPath,
enabled: true,
...(parsed.description !== undefined ? { description: parsed.description } : {}),
...(parsed.displayName !== undefined ? { displayName: parsed.displayName } : {}),
...(shortDescription !== undefined ? { shortDescription } : {}),
};
skills.push(skill);
}
return skills;
});
}
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
const connected = new Set(input.providerList.connected);
const models: Array<ServerProviderModel> = [];
for (const provider of input.providerList.all) {
if (!connected.has(provider.id)) {
continue;
}
for (const model of Object.values(provider.models)) {
const name = nonEmptyTrimmed(model.name);
if (!name) {
continue;
}
const subProvider = nonEmptyTrimmed(provider.name);
models.push({
slug: `${provider.id}/${model.id}`,
name,
...(subProvider ? { subProvider } : {}),
isCustom: false,
capabilities: openCodeCapabilitiesForModel({
providerID: provider.id,
model,
agents: input.agents,
}),
});
}
}
return models.toSorted((left, right) => left.name.localeCompare(right.name));
}
export const makePendingOpenCodeProvider = (
openCodeSettings: OpenCodeSettings,
cwd: string,
): Effect.Effect<ServerProviderDraft, never, FileSystem.FileSystem | Path.Path> =>
Effect.gen(function* () {
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
const models = providerModelsFromSettings(
[],
PROVIDER,
openCodeSettings.customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
const skills = yield* loadOpenCodeSkills(cwd);
if (!openCodeSettings.enabled) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models,
skills,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message:
openCodeSettings.serverUrl.trim().length > 0
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
models,
skills,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "OpenCode provider status has not been checked in this session yet.",
},
});
});
export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (
openCodeSettings: OpenCodeSettings,
cwd: string,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
ServerProviderDraft,
never,
OpenCodeRuntime | FileSystem.FileSystem | Path.Path
> {
const openCodeRuntime = yield* OpenCodeRuntime;
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const customModels = openCodeSettings.customModels;
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
const skills = yield* loadOpenCodeSkills(cwd);
const fallback = (cause: unknown, version: string | null = null) => {
const failure = formatOpenCodeProbeError({
cause,
isExternalServer,
serverUrl: openCodeSettings.serverUrl,
});
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
skills,
probe: {
installed: failure.installed,
version,
status: "error",
auth: { status: "unknown" },
message: failure.message,
},
});
};
if (!openCodeSettings.enabled) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: false,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
skills,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: isExternalServer
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
: "OpenCode is disabled in T3 Code settings.",
},
});
}
let version: string | null = null;
if (!isExternalServer) {
const versionExit = yield* Effect.exit(
openCodeRuntime
.runOpenCodeCommand({
binaryPath: openCodeSettings.binaryPath,
args: ["--version"],
environment,
})
.pipe(
Effect.mapError(
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
),
);
if (versionExit._tag === "Failure") {
return fallback(Cause.squash(versionExit.cause));
}
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
if (!version) {
return fallback(
new Error(
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
),
null,
);
}
if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
checkedAt,
models: providerModelsFromSettings(
[],
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
),
skills,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
},
});
}
}
const inventoryExit = yield* Effect.exit(
Effect.scoped(
Effect.gen(function* () {
const server = yield* openCodeRuntime
.connectToOpenCodeServer({
binaryPath: openCodeSettings.binaryPath,
serverUrl: openCodeSettings.serverUrl,
environment,
})
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
return yield* openCodeRuntime
.loadOpenCodeInventory(
openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: cwd,
...(isExternalServer && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
),
);
}),
),
);
if (inventoryExit._tag === "Failure") {
return fallback(Cause.squash(inventoryExit.cause), version);
}
const models = providerModelsFromSettings(
flattenOpenCodeModels(inventoryExit.value),
PROVIDER,
customModels,
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
);
const connectedCount = inventoryExit.value.providerList.connected.length;
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: true,
checkedAt,
models,
skills,
probe: {
installed: true,
version,
status: connectedCount > 0 ? "ready" : "warning",
auth: {
status: connectedCount > 0 ? "authenticated" : "unknown",
type: "opencode",
},
message:
connectedCount > 0
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
: isExternalServer
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
: "OpenCode is available, but it did not report any connected upstream providers.",
},
});
});