Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 74 additions & 2 deletions packages/opencode/src/command/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { CommandV2 } from "@opencode-ai/core/command"
import { LocationServiceMap } from "@opencode-ai/core/location-services"
import { Location } from "@opencode-ai/core/location"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { ModelV2 } from "@opencode-ai/core/model"
import path from "path"
import { InstanceState } from "@/effect/instance-state"
import { EffectBridge } from "@/effect/bridge"
import type { InstanceContext } from "@/project/instance-context"
import { Effect, Layer, Context, Schema } from "effect"
import { Effect, Layer, Context, Schema, Option } from "effect"
import { Config } from "@/config/config"
import { MCP } from "../mcp"
import { Skill } from "../skill"
Expand Down Expand Up @@ -66,6 +71,9 @@ const layer = Layer.effect(
const cfg = yield* config.get()
const bridge = yield* EffectBridge.make()
const commands: Record<string, Info> = {}
// MCP command templates are lazy: reading one resolves the remote MCP
// prompt, so record their names instead of materializing them here.
const lazyTemplates = new Set<string>()

commands[Default.INIT] = {
name: Default.INIT,
Expand Down Expand Up @@ -103,6 +111,7 @@ const layer = Layer.effect(
}

for (const [name, prompt] of Object.entries(yield* mcp.prompts())) {
lazyTemplates.add(name)
commands[name] = {
name,
source: "mcp",
Expand Down Expand Up @@ -151,6 +160,65 @@ const layer = Layer.effect(
}
}

// Bridge this instance's commands into the V2 command store the TUI
// launcher reads (GET /api/command). The V2 store is location-scoped, so
// target the CommandV2 of this directory's location layer (shared with
// V2 requests via the LocationServiceMap), not any locally compiled
// instance. The transform is bound to this state's scope, so disposing
// or invalidating the instance unregisters it and the V2 store reloads
// without the bridged entries.
//
// The bridge owns only the entries it writes: each run removes the
// commands it previously bridged that are now gone, and leaves entries
// from other V2 producers untouched. MCP templates are lazy promises
// (reading one resolves the remote prompt), so they are bridged
// unresolved and materialized only when the command is executed;
// concrete templates are copied verbatim.
//
// Optional lookup: runtimes without a LocationServiceMap (e.g. the CLI)
// have no V2 store to bridge into.
const locationsOpt = Context.getOption(LocationServiceMap.Service)(yield* Effect.context())
if (Option.isSome(locationsOpt)) {
const locations = locationsOpt.value
const bridgedNames = new Set<string>()
yield* Effect.gen(function* () {
const commandV2 = yield* CommandV2.Service
yield* commandV2.transform((draft) => {
for (const name of bridgedNames) {
draft.remove(name)
}
bridgedNames.clear()
for (const [name, info] of Object.entries(commands)) {
bridgedNames.add(name)
draft.update(name, (cmd) => {
cmd.name = info.name
// Non-MCP templates are concrete strings; MCP templates are
// lazy promises that must not be read here, so they are
// bridged unresolved.
const template = lazyTemplates.has(name) ? "" : info.template
cmd.template = typeof template === "string" ? template : ""
cmd.description = info.description
cmd.agent = info.agent
if (info.model) {
const parsed = ModelV2.parse(info.model)
cmd.model = { id: parsed.modelID, providerID: parsed.providerID }
}
cmd.subtask = info.subtask
})
}
})
}).pipe(
Effect.provide(
// Match the V2 location middleware's ref exactly: the location
// map keys by structural equality, where a missing key differs
// from an explicit undefined.
locations.get(
Location.Ref.make({ directory: AbsolutePath.make(ctx.directory), workspaceID: undefined }),
),
),
)
}

return {
commands,
}
Expand All @@ -172,6 +240,10 @@ const layer = Layer.effect(
}),
)

export const node = LayerNode.make({ service: Service, layer: layer, deps: [Config.node, MCP.node, Skill.node] })
export const node = LayerNode.make({
service: Service,
layer: layer,
deps: [Config.node, MCP.node, Skill.node],
})

export * as Command from "."
201 changes: 201 additions & 0 deletions packages/opencode/test/command/bridge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
import { describe, expect } from "bun:test"
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"
import { GetPromptRequestSchema, ListPromptsRequestSchema } from "@modelcontextprotocol/sdk/types.js"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { CommandV2 } from "@opencode-ai/core/command"
import {
LocationServiceMap,
type LocationServices,
} from "@opencode-ai/core/location-services"
import { Location } from "@opencode-ai/core/location"
import { ModelV2 } from "@opencode-ai/core/model"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { Effect, Exit, Layer, LayerMap } from "effect"
import { testEffect } from "../lib/effect"
import { Command } from "../../src/command"
import { Config } from "../../src/config/config"
import { MCP } from "../../src/mcp"
import { Skill } from "../../src/skill"

// The bridge resolves the location-scoped CommandV2 through a
// LocationServiceMap, the same way the server does. This stub map points every
// location at the single CommandV2 layer the assertions read, so the bridge
// and the test share one instance (same layer object, same memoization).
const commandV2Layer = LayerNode.compile(LayerNode.group([CommandV2.node]))
const locationServiceMap = {
get: (_ref: Location.Ref) => commandV2Layer,
} as unknown as LayerMap.LayerMap<Location.Ref, LocationServices>

const it = testEffect(
Layer.merge(
LayerNode.compile(LayerNode.group([Command.node, Config.node, MCP.node, Skill.node])).pipe(
Layer.provide(Layer.succeed(LocationServiceMap.Service, locationServiceMap)),
),
commandV2Layer,
),
)

const remote = (url: string) => ({ type: "remote" as const, url, oauth: false as const })

interface PromptServerState {
name: string
description: string
text: string
failGetPrompt: boolean
getPromptCalls: number
}

// In-process MCP server advertising a single prompt and counting GetPrompt
// requests, so tests can assert when (and whether) prompt templates are
// resolved.
function promptServer(options?: Partial<PromptServerState>) {
const state: PromptServerState = {
name: "my-prompt",
description: "A test prompt",
text: "prompt result",
failGetPrompt: false,
getPromptCalls: 0,
...options,
}
return Effect.acquireRelease(
Effect.promise(async () => {
const protocol = new Server(
{ name: "command-bridge-prompt", version: "1.0.0" },
{ capabilities: { prompts: {} } },
)
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: () => crypto.randomUUID(),
enableJsonResponse: true,
})
protocol.setRequestHandler(ListPromptsRequestSchema, () =>
Promise.resolve({ prompts: [{ name: state.name, description: state.description }] }),
)
protocol.setRequestHandler(GetPromptRequestSchema, () => {
state.getPromptCalls++
if (state.failGetPrompt) throw new Error("prompt failed")
return Promise.resolve({ messages: [{ role: "user", content: { type: "text", text: state.text } }] })
})
await protocol.connect(transport)
const http = Bun.serve({
port: 0,
fetch(request) {
return transport.handleRequest(request)
},
})
return {
state,
url: http.url.toString(),
close: async () => {
await protocol.close().catch(() => {})
await http.stop(true)
},
}
}),
(server) => Effect.promise(server.close),
)
}

describe("CommandV2 bridge", () => {
it.instance("syncs factory default commands into CommandV2", () =>
Effect.gen(function* () {
const command = yield* Command.Service
yield* command.list()
const commandV2 = yield* CommandV2.Service
const names = (yield* commandV2.list()).map((c) => c.name)
expect(names).toContain("init")
expect(names).toContain("review")

const init = yield* commandV2.get("init")
expect(init?.name).toBe("init")
expect(init?.template).toContain("AGENTS.md")

const review = yield* commandV2.get("review")
expect(review?.name).toBe("review")
expect(review?.template).toContain("review")
expect(review?.subtask).toBe(true)
}),
)

it.instance(
"syncs configured command model, agent, subtask, and template into CommandV2",
() =>
Effect.gen(function* () {
const command = yield* Command.Service
yield* command.list()
const commandV2 = yield* CommandV2.Service
const custom = yield* commandV2.get("my-cmd")
expect(custom).toBeDefined()
expect(custom?.agent).toBe("build")
expect(custom?.subtask).toBe(true)
expect(custom?.template).toBe("echo hello")
expect(custom?.description).toBe("test command")
// The legacy command model is a "provider/model" string, so the bridge
// must split it into the V2 model reference. Legacy commands cannot
// carry a variant, so none is bridged.
expect(custom?.model).toBeDefined()
expect(custom?.model?.id).toBe(ModelV2.ID.make("claude-3-opus-20240229"))
expect(custom?.model?.providerID).toBe(ProviderV2.ID.make("anthropic"))
expect(custom?.model?.variant).toBeUndefined()
}),
{
config: {
command: {
"my-cmd": {
agent: "build",
model: "anthropic/claude-3-opus-20240229",
description: "test command",
template: "echo hello",
subtask: true,
},
},
},
},
)

it.instance("bridges MCP prompt metadata without resolving the prompt", () =>
Effect.gen(function* () {
const server = yield* promptServer()
const mcp = yield* MCP.Service
yield* mcp.add("lazy", remote(server.url))

const command = yield* Command.Service
yield* command.list()

const commandV2 = yield* CommandV2.Service
const bridged = yield* commandV2.get("lazy:my-prompt")
expect(bridged).toBeDefined()
expect(bridged?.description).toBe("A test prompt")
// The template stays unresolved in the V2 store; command initialization
// must not execute the remote prompt.
expect(bridged?.template).toBe("")
expect(server.state.getPromptCalls).toBe(0)

// Lazy resolution still happens when the template is consumed.
const legacy = yield* command.get("lazy:my-prompt")
expect(legacy).toBeDefined()
const template = yield* Effect.promise(async () => legacy!.template)
expect(template).toBe("prompt result")
expect(server.state.getPromptCalls).toBe(1)
}),
)

it.instance("does not fail command initialization when an MCP prompt fails", () =>
Effect.gen(function* () {
const server = yield* promptServer({ failGetPrompt: true })
const mcp = yield* MCP.Service
yield* mcp.add("broken", remote(server.url))

const command = yield* Command.Service
const exit = yield* command.list().pipe(Effect.exit)
expect(Exit.isSuccess(exit)).toBe(true)

const commandV2 = yield* CommandV2.Service
const names = (yield* commandV2.list()).map((c) => c.name)
expect(names).toContain("init")
expect(names).toContain("review")
expect(names).toContain("broken:my-prompt")
expect(server.state.getPromptCalls).toBe(0)
}),
)
})
Loading
Loading