Skip to content

Commit be53874

Browse files
committed
refactor(opencode): keep SDK-only command catalog (option B)
Drop ACP and filesystem fallbacks so we can validate the OpenCode SDK /command + /skill path in isolation. Reintroduce A only if B fails in manual testing.
1 parent db2b2f7 commit be53874

2 files changed

Lines changed: 21 additions & 250 deletions

File tree

‎apps/server/src/provider/Layers/OpenCodeProvider.ts‎

Lines changed: 2 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,11 @@ import {
22
type ModelCapabilities,
33
type OpenCodeSettings,
44
type ServerProviderModel,
5-
type ServerProviderSkill,
65
} from "@t3tools/contracts";
76
import * as Cause from "effect/Cause";
87
import * as Data from "effect/Data";
98
import * as DateTime from "effect/DateTime";
109
import * as Effect from "effect/Effect";
11-
import * as FileSystem from "effect/FileSystem";
12-
import * as Path from "effect/Path";
1310

1411
import { createModelCapabilities } from "@t3tools/shared/model";
1512
import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -31,8 +28,6 @@ import {
3128
providerCommandCatalogIsEmpty,
3229
} from "../providerCommandCatalog.ts";
3330
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
34-
import { expandHomePath } from "../../pathExpansion.ts";
35-
import { parse as parseYamlDocument } from "yaml";
3631

3732
const OPENCODE_PRESENTATION = {
3833
displayName: "OpenCode",
@@ -442,12 +437,12 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
442437
);
443438
const connectedCount = inventory.providerList.connected.length;
444439

445-
// Command/skill catalog: B (SDK) → A (ACP) → C (filesystem skills).
440+
// SDK catalog only (option B). Local CLI inventory leaves commands/skills
441+
// empty — enrich once via a short-lived serve + the same SDK endpoints.
446442
let catalog = mapOpenCodeSdkCatalogToProviderCatalog({
447443
commands: inventory.commands,
448444
skills: inventory.skills,
449445
});
450-
451446
if (providerCommandCatalogIsEmpty(catalog)) {
452447
catalog = yield* openCodeRuntime
453448
.loadProviderCommandCatalog({
@@ -466,18 +461,6 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
466461
.pipe(Effect.orElseSucceed(() => EMPTY_PROVIDER_COMMAND_CATALOG));
467462
}
468463

469-
if (catalog.skills.length === 0) {
470-
const fsSkills = yield* discoverOpenCodeSkillsFromFilesystem(cwd).pipe(
471-
Effect.orElseSucceed(() => [] as ReadonlyArray<ServerProviderSkill>),
472-
);
473-
if (fsSkills.length > 0) {
474-
catalog = {
475-
slashCommands: catalog.slashCommands,
476-
skills: fsSkills,
477-
};
478-
}
479-
}
480-
481464
return buildServerProvider({
482465
presentation: OPENCODE_PRESENTATION,
483466
enabled: true,
@@ -502,71 +485,3 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
502485
},
503486
});
504487
});
505-
506-
const OPENCODE_SKILL_FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
507-
508-
/**
509-
* Option C: scan OpenCode skill directories on disk when SDK/ACP catalogs are empty.
510-
* Paths mirror OpenCode's own loader (project + global + external agent skills).
511-
*/
512-
export const discoverOpenCodeSkillsFromFilesystem = (
513-
cwd: string,
514-
): Effect.Effect<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> =>
515-
Effect.gen(function* () {
516-
const fs = yield* FileSystem.FileSystem;
517-
const path = yield* Path.Path;
518-
const home = expandHomePath("~") ?? "";
519-
const roots: ReadonlyArray<{ readonly directory: string; readonly scope: string }> = [
520-
{ directory: path.join(cwd, ".opencode", "skill"), scope: "project" },
521-
{ directory: path.join(cwd, ".opencode", "skills"), scope: "project" },
522-
{ directory: path.join(home, ".config", "opencode", "skill"), scope: "user" },
523-
{ directory: path.join(home, ".config", "opencode", "skills"), scope: "user" },
524-
{ directory: path.join(home, ".agents", "skills"), scope: "user" },
525-
{ directory: path.join(home, ".claude", "skills"), scope: "user" },
526-
];
527-
528-
const skillsByName = new Map<string, ServerProviderSkill>();
529-
530-
for (const root of roots) {
531-
const entries = yield* fs.readDirectory(root.directory).pipe(Effect.orElseSucceed(() => []));
532-
for (const entry of entries) {
533-
const skillMd = path.join(root.directory, entry, "SKILL.md");
534-
const exists = yield* fs.exists(skillMd).pipe(Effect.orElseSucceed(() => false));
535-
if (!exists) {
536-
continue;
537-
}
538-
const contents = yield* fs.readFileString(skillMd).pipe(Effect.orElseSucceed(() => ""));
539-
const match = OPENCODE_SKILL_FRONTMATTER.exec(contents);
540-
let name = entry;
541-
let description: string | undefined;
542-
if (match?.[1]) {
543-
try {
544-
const parsed = parseYamlDocument(match[1]) as Record<string, unknown> | null;
545-
if (parsed && typeof parsed === "object") {
546-
if (typeof parsed.name === "string" && parsed.name.trim()) {
547-
name = parsed.name.trim();
548-
}
549-
if (typeof parsed.description === "string" && parsed.description.trim()) {
550-
description = parsed.description.trim();
551-
}
552-
}
553-
} catch {
554-
// keep directory name
555-
}
556-
}
557-
const key = name.toLowerCase();
558-
if (skillsByName.has(key)) {
559-
continue;
560-
}
561-
skillsByName.set(key, {
562-
name,
563-
path: skillMd,
564-
enabled: true,
565-
scope: root.scope,
566-
...(description ? { description } : {}),
567-
});
568-
}
569-
}
570-
571-
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
572-
});

‎apps/server/src/provider/opencodeRuntime.ts‎

Lines changed: 19 additions & 163 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@ import { isWindowsCommandNotFound } from "../processRunner.ts";
3434
import { collectStreamAsString } from "./providerSnapshot.ts";
3535
import {
3636
EMPTY_PROVIDER_COMMAND_CATALOG,
37-
mapAcpAvailableCommandsToProviderCatalog,
3837
mapOpenCodeSdkCatalogToProviderCatalog,
39-
providerCommandCatalogIsEmpty,
4038
type ProviderCommandCatalog,
4139
} from "./providerCommandCatalog.ts";
4240
import * as NetService from "@t3tools/shared/Net";
@@ -171,9 +169,8 @@ export interface OpenCodeRuntimeShape {
171169
readonly environment?: NodeJS.ProcessEnv;
172170
}) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
173171
/**
174-
* Load slash/skill catalogs when the primary inventory left them empty.
175-
* Order: B (SDK via serve/server URL) → A (`opencode acp` available_commands).
176-
* Filesystem discovery (C) is handled by the provider layer.
172+
* Load slash/skill catalogs via the OpenCode SDK (`/command` + `/skill`).
173+
* Spawns a short-lived local serve when `serverUrl` is absent.
177174
*/
178175
readonly loadProviderCommandCatalog: (input: {
179176
readonly binaryPath: string;
@@ -799,8 +796,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
799796
}
800797

801798
// CLI inventory does not expose commands/skills; callers that need a
802-
// catalog should open an SDK session (server URL or local serve) and use
803-
// loadOpenCodeInventory, or fall back to ACP / filesystem discovery.
799+
// catalog open an SDK session via loadProviderCommandCatalog.
804800
return {
805801
providerList: { all: allProviders, default: {}, connected },
806802
agents,
@@ -809,166 +805,26 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
809805
};
810806
});
811807

812-
const loadProviderCommandCatalogViaSdk = (input: {
813-
readonly binaryPath: string;
814-
readonly directory: string;
815-
readonly environment?: NodeJS.ProcessEnv;
816-
readonly serverUrl?: string | null;
817-
readonly serverPassword?: string;
818-
}): Effect.Effect<ProviderCommandCatalog, OpenCodeRuntimeError, Scope.Scope> =>
819-
Effect.gen(function* () {
820-
const server = yield* connectToOpenCodeServer({
821-
binaryPath: input.binaryPath,
822-
serverUrl: input.serverUrl,
823-
environment: input.environment,
824-
});
825-
const client = createOpenCodeSdkClient({
826-
baseUrl: server.url,
827-
directory: input.directory,
828-
...(input.serverPassword ? { serverPassword: input.serverPassword } : {}),
829-
});
830-
const inventory = yield* loadOpenCodeInventory(client);
831-
return mapOpenCodeSdkCatalogToProviderCatalog({
832-
commands: inventory.commands,
833-
skills: inventory.skills,
834-
});
835-
});
836-
837-
const loadProviderCommandCatalogViaAcp = (input: {
838-
readonly binaryPath: string;
839-
readonly directory: string;
840-
readonly environment?: NodeJS.ProcessEnv;
841-
}): Effect.Effect<ProviderCommandCatalog, OpenCodeRuntimeError, Scope.Scope> =>
842-
Effect.gen(function* () {
843-
const env = input.environment ?? process.env;
844-
const spawnCommand = yield* resolveCommand(input.binaryPath || "opencode", ["acp"], env);
845-
const handle = yield* spawner
846-
.spawn(
847-
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
848-
cwd: input.directory,
849-
env,
850-
shell: spawnCommand.shell,
851-
}),
852-
)
853-
.pipe(
854-
Effect.mapError(
855-
(cause) =>
856-
new OpenCodeRuntimeError({
857-
operation: "loadProviderCommandCatalogViaAcp",
858-
detail: openCodeRuntimeErrorDetail(cause),
859-
cause,
860-
}),
861-
),
862-
);
863-
864-
const encoder = new TextEncoder();
865-
const writeLine = (message: unknown) =>
866-
handle.stdin.write(encoder.encode(`${JSON.stringify(message)}\n`)).pipe(
867-
Effect.mapError(
868-
(cause) =>
869-
new OpenCodeRuntimeError({
870-
operation: "loadProviderCommandCatalogViaAcp",
871-
detail: "Failed to write ACP request.",
872-
cause,
873-
}),
874-
),
875-
Effect.asVoid,
876-
);
877-
878-
yield* writeLine({
879-
jsonrpc: "2.0",
880-
id: 1,
881-
method: "initialize",
882-
params: {
883-
protocolVersion: 1,
884-
clientCapabilities: {},
885-
clientInfo: { name: "t3-code-opencode-catalog", version: "0.0.0" },
886-
},
887-
});
888-
yield* writeLine({
889-
jsonrpc: "2.0",
890-
id: 2,
891-
method: "session/new",
892-
params: { cwd: input.directory, mcpServers: [] },
893-
});
894-
895-
let buffer = "";
896-
type AcpCommand = {
897-
readonly name: string;
898-
readonly description?: string;
899-
readonly input?: { readonly hint?: string } | null;
900-
readonly _meta?: { readonly [x: string]: unknown } | null;
901-
};
902-
const found = yield* Deferred.make<ReadonlyArray<AcpCommand>>();
903-
let availableCommands: ReadonlyArray<AcpCommand> = [];
904-
905-
const reader = yield* handle.stdout.pipe(
906-
Stream.decodeText(),
907-
Stream.runForEach((chunk) =>
908-
Effect.gen(function* () {
909-
buffer += chunk;
910-
const lines = buffer.split("\n");
911-
buffer = lines.pop() ?? "";
912-
for (const line of lines) {
913-
const trimmed = line.trim();
914-
if (!trimmed) continue;
915-
try {
916-
const message = JSON.parse(trimmed) as {
917-
readonly method?: string;
918-
readonly params?: {
919-
readonly update?: {
920-
readonly sessionUpdate?: string;
921-
readonly availableCommands?: ReadonlyArray<AcpCommand>;
922-
};
923-
};
924-
};
925-
if (
926-
message.method === "session/update" &&
927-
message.params?.update?.sessionUpdate === "available_commands_update" &&
928-
Array.isArray(message.params.update.availableCommands) &&
929-
message.params.update.availableCommands.length > 0
930-
) {
931-
availableCommands = message.params.update.availableCommands;
932-
yield* Deferred.succeed(found, availableCommands).pipe(Effect.ignore);
933-
}
934-
} catch {
935-
// ignore non-JSON chatter
936-
}
937-
}
938-
}),
939-
),
940-
Effect.forkScoped,
941-
);
942-
943-
const commands = yield* Deferred.await(found).pipe(
944-
Effect.timeoutOption(8_000),
945-
Effect.map((option) => (Option.isSome(option) ? option.value : availableCommands)),
946-
Effect.ensuring(
947-
Effect.all([Fiber.interrupt(reader), handle.kill()], { concurrency: "unbounded" }).pipe(
948-
Effect.ignore,
949-
),
950-
),
951-
);
952-
953-
return mapAcpAvailableCommandsToProviderCatalog(commands);
954-
});
955-
956808
const loadProviderCommandCatalog: OpenCodeRuntimeShape["loadProviderCommandCatalog"] = (input) =>
957809
Effect.scoped(
958810
Effect.gen(function* () {
959-
// B — SDK
960-
const fromSdk = yield* loadProviderCommandCatalogViaSdk(input).pipe(
961-
Effect.orElseSucceed(() => EMPTY_PROVIDER_COMMAND_CATALOG),
962-
);
963-
if (!providerCommandCatalogIsEmpty(fromSdk)) {
964-
return fromSdk;
965-
}
966-
// A — ACP
967-
return yield* loadProviderCommandCatalogViaAcp(input).pipe(
968-
Effect.orElseSucceed(() => EMPTY_PROVIDER_COMMAND_CATALOG),
969-
);
811+
const server = yield* connectToOpenCodeServer({
812+
binaryPath: input.binaryPath,
813+
serverUrl: input.serverUrl,
814+
environment: input.environment,
815+
});
816+
const client = createOpenCodeSdkClient({
817+
baseUrl: server.url,
818+
directory: input.directory,
819+
...(input.serverPassword ? { serverPassword: input.serverPassword } : {}),
820+
});
821+
const inventory = yield* loadOpenCodeInventory(client);
822+
return mapOpenCodeSdkCatalogToProviderCatalog({
823+
commands: inventory.commands,
824+
skills: inventory.skills,
825+
});
970826
}),
971-
);
827+
).pipe(Effect.orElseSucceed(() => EMPTY_PROVIDER_COMMAND_CATALOG));
972828

973829
return {
974830
startOpenCodeServerProcess,

0 commit comments

Comments
 (0)