diff --git a/pkgs/mcpx/plugin/opencode/v2/index.ts b/pkgs/mcpx/plugin/opencode/v2/index.ts index 47aa85de9c..e4d0e3fbd2 100644 --- a/pkgs/mcpx/plugin/opencode/v2/index.ts +++ b/pkgs/mcpx/plugin/opencode/v2/index.ts @@ -5,8 +5,10 @@ * the idempotent system-prompt paragraph (session context hook), the * once-per-session full-environment send, execute.after timing records, * the permission gate (permission.ts: evaluate hook + daemon_select - * assert), and tool registration (tools.ts: tool.transform under the mcpx - * namespace, so the model sees the v1 names — mcpx_exec and friends). + * assert), tool registration (tools.ts: tool.transform under the mcpx + * namespace, so the model sees the v1 names — mcpx_exec and friends), + * and the sampling watcher (sampling.ts, #1858 item (4)): broker + * sample rows answered through ctx.generate.text. * The v1 tree stays beside this one, untouched, until v2 is what runs. */ import { targetKey, type Target } from "../mcpx/daemon.ts"; @@ -17,6 +19,11 @@ import { type PermissionDomainLike, } from "./permission.ts"; import { readRememberedDaemon, type StorageLike } from "./remember.ts"; +import { + startSamplingWatcher, + type GenerateTextLike, + type SamplingDaemonLike, +} from "./sampling.ts"; import { createSessionEnv } from "./session-env.ts"; import { createTimingLog, @@ -50,9 +57,21 @@ export type McpxV2Context = { * refuses to apply unconfirmed choices. */ permission?: PermissionDomainLike; + /** + * The v2 generate domain (sampling.ts): one-shot completions. + * Optional in the type because stub hosts omit it; without it the + * sampling watcher never starts and broker sample rows are left + * for another answerer, exactly as before item (4). + */ + generate?: { + text: GenerateTextLike; + }; }; -export async function setupMcpxV2(ctx: McpxV2Context, rawOptions?: Options): Promise { +export async function setupMcpxV2( + ctx: McpxV2Context, + rawOptions?: Options, +): Promise<(() => void) | undefined> { const options = resolveOptions(rawOptions, process.env); const directory = ctx.directory ?? process.cwd(); const sessionEnv = createSessionEnv({ @@ -164,6 +183,32 @@ export async function setupMcpxV2(ctx: McpxV2Context, rawOptions?: Options): Pro toolsEnabled: options.tools ?? false, daemonTools: options.daemonTools, }).catch(() => []); + + // Sampling (#1858 item (4)): when the host offers ctx.generate.text + // and the option has not turned it off, watch the daemon's broker + // for sample rows routed to the agent and answer them. The watcher + // resolves the daemon through the tool runtime on every poll, so + // it follows daemon_select like everything else; a client without + // the elicit methods (a stub, an older daemon core) reads as no + // daemon. Setup returns the watcher's stop as its cleanup. + const generate = ctx.generate; + if (options.answerSampling === false || !generate) return undefined; + const watcher = startSamplingWatcher({ + generate: generate.text, + client: async (): Promise => { + const client = (await runtime?.daemon().catch(() => undefined)) as + | Partial + | undefined; + if ( + typeof client?.pendingElicitations !== "function" || + typeof client?.answer !== "function" + ) { + return undefined; + } + return client as SamplingDaemonLike; + }, + }); + return () => watcher.stop(); } export default { diff --git a/pkgs/mcpx/plugin/opencode/v2/options.ts b/pkgs/mcpx/plugin/opencode/v2/options.ts index 96b5864e37..1d522c2a9c 100644 --- a/pkgs/mcpx/plugin/opencode/v2/options.ts +++ b/pkgs/mcpx/plugin/opencode/v2/options.ts @@ -32,6 +32,14 @@ export type Options = { env?: "minimal" | "standard" | "full"; instructions?: boolean; toolTiming?: boolean; + /** + * Answer mcpx sampling questions (broker sample rows routed to the + * agent) with ctx.generate.text. Default on when the host offers + * ctx.generate; false turns the watcher off. Plugin-option only -- + * no env name is declared for it in the settings registry, and the + * settings guard forbids reading undeclared MCPX_* names. + */ + answerSampling?: boolean; tools?: boolean; /** Offer mcpx_daemon_status and mcpx_daemon_select. Default: when unclear. */ daemonTools?: boolean; @@ -113,6 +121,7 @@ export function resolveOptions( daemonTools: o.daemonTools ?? truthy(env.MCPX_PLUGIN_DAEMON_TOOLS), annotate: o.annotate ?? truthy(env.MCPX_PLUGIN_ANNOTATE) ?? true, toolTiming: o.toolTiming ?? truthy(env.MCPX_PLUGIN_TOOL_TIMING) ?? false, + answerSampling: o.answerSampling ?? true, discoveryRetryMs: goDurationMs(env.MCPX_PLUGIN_DISCOVERY_RETRY), }; } diff --git a/pkgs/mcpx/plugin/opencode/v2/sampling.test.ts b/pkgs/mcpx/plugin/opencode/v2/sampling.test.ts new file mode 100644 index 0000000000..7552387691 --- /dev/null +++ b/pkgs/mcpx/plugin/opencode/v2/sampling.test.ts @@ -0,0 +1,191 @@ +/** + * Sampling answers (#1858 item (4), #2841), against stubs: a fake + * broker client serving canned rows and recording answers, and a + * fake ctx.generate.text. The round-trip asserted here is the one + * the daemon performs for real: a sample-mode broker row's + * requestedSchema is the CreateMessageRequest params, and the + * answer posted back must be a CreateMessageResult the broker's + * ValidateSampleResult accepts (role "assistant", non-empty model, + * text content, a stop reason). + * + * bun test plugin/opencode/v2/sampling.test.ts + */ +import { describe, expect, test } from "bun:test"; +import { + createMessageResult, + createSamplingAnswerer, + samplingModel, + samplingPrompt, + type BrokerRow, + type SamplingDaemonLike, +} from "./sampling.ts"; + +const sampleRow = (over: Partial = {}): BrokerRow => ({ + id: "elc-1", + mode: "sample", + audience: "agent", + requestedSchema: { + messages: [ + { role: "user", content: { type: "text", text: "Say hello." } }, + ], + systemPrompt: "Be brief.", + modelPreferences: { hints: [{ name: "hinted-model" }] }, + maxTokens: 64, + }, + ...over, +}); + +const stubClient = (rows: BrokerRow[]): { + client: SamplingDaemonLike; + answers: Array<{ id: string; action: string; content?: unknown }>; +} => { + const answers: Array<{ id: string; action: string; content?: unknown }> = []; + const client: SamplingDaemonLike = { + pendingElicitations: async () => rows as unknown[], + answer: async (id, action, content) => { + answers.push({ id, action, content }); + return {}; + }, + } as SamplingDaemonLike; + return { client, answers }; +}; + +describe("samplingPrompt", () => { + test("flattens system prompt and message text in order", () => { + const prompt = samplingPrompt({ + systemPrompt: "Be brief.", + messages: [ + { role: "user", content: { type: "text", text: "Say hello." } }, + { + role: "assistant", + content: [ + { type: "text", text: "Hello." }, + { type: "image", data: "..." }, + ], + }, + { role: "user", content: "Again, please." }, + ], + }); + expect(prompt).toBe( + "Be brief.\n\nuser: Say hello.\n\nassistant: Hello.\n[image content omitted]\n\nuser: Again, please.", + ); + }); + + test("refuses a request carrying tools or a toolChoice", () => { + const base = { messages: [{ role: "user", content: { type: "text", text: "hi" } }] }; + expect(samplingPrompt({ ...base, tools: [{ name: "t" }] })).toBeUndefined(); + expect(samplingPrompt({ ...base, toolChoice: "auto" })).toBeUndefined(); + }); + + test("refuses a request with no text at all", () => { + expect(samplingPrompt({ messages: [] })).toBeUndefined(); + expect(samplingPrompt({})).toBeUndefined(); + }); +}); + +describe("samplingModel", () => { + test("prefers the first non-empty hint, else the generate label", () => { + expect(samplingModel({ modelPreferences: { hints: [{ name: "" }, { name: "m2" }] } })).toBe("m2"); + expect(samplingModel({})).toBe("opencode-v2-generate"); + }); +}); + +describe("createMessageResult", () => { + test("is the CreateMessageResult shape the broker validates", () => { + expect(createMessageResult("Hello.", "m")).toEqual({ + role: "assistant", + model: "m", + content: { type: "text", text: "Hello." }, + stopReason: "endTurn", + }); + }); +}); + +describe("the sampling round-trip", () => { + test("a sample row is generated and answered as a CreateMessageResult", async () => { + const { client, answers } = stubClient([sampleRow()]); + const prompts: string[] = []; + const answerer = createSamplingAnswerer({ + client: async () => client, + generate: async ({ prompt }) => { + prompts.push(prompt); + return { text: "Hello." }; + }, + }); + expect(await answerer.pollOnce()).toBe(1); + expect(prompts).toEqual(["Be brief.\n\nuser: Say hello."]); + expect(answers).toEqual([ + { + id: "elc-1", + action: "accept", + content: { + role: "assistant", + model: "hinted-model", + content: { type: "text", text: "Hello." }, + stopReason: "endTurn", + }, + }, + ]); + }); + + test("the { data: { text } } generate envelope is unwrapped", async () => { + const { client, answers } = stubClient([sampleRow()]); + const answerer = createSamplingAnswerer({ + client: async () => client, + generate: async () => ({ data: { text: "Wrapped." } }), + }); + expect(await answerer.pollOnce()).toBe(1); + expect((answers[0]?.content as { content: { text: string } }).content.text).toBe("Wrapped."); + }); + + test("form rows, human rows and tool-carrying samples are left open", async () => { + const rows = [ + sampleRow({ id: "elc-form", mode: "form" }), + sampleRow({ id: "elc-human", audience: "human" }), + sampleRow({ + id: "elc-tools", + requestedSchema: { + messages: [{ role: "user", content: { type: "text", text: "hi" } }], + tools: [{ name: "t", description: "d", inputSchema: { type: "object" } }], + }, + }), + ]; + const { client, answers } = stubClient(rows); + let generated = 0; + const answerer = createSamplingAnswerer({ + client: async () => client, + generate: async () => { + generated++; + return { text: "x" }; + }, + }); + expect(await answerer.pollOnce()).toBe(0); + expect(generated).toBe(0); + expect(answers).toEqual([]); + }); + + test("a failed generation leaves the row open for the next poll", async () => { + const { client, answers } = stubClient([sampleRow()]); + let calls = 0; + const answerer = createSamplingAnswerer({ + client: async () => client, + generate: async () => { + calls++; + if (calls === 1) throw new Error("model unavailable"); + return { text: "Second try." }; + }, + }); + expect(await answerer.pollOnce()).toBe(0); + expect(answers).toEqual([]); + expect(await answerer.pollOnce()).toBe(1); + expect(answers.length).toBe(1); + }); + + test("no daemon means no answers and no throw", async () => { + const answerer = createSamplingAnswerer({ + client: async () => undefined, + generate: async () => ({ text: "x" }), + }); + expect(await answerer.pollOnce()).toBe(0); + }); +}); diff --git a/pkgs/mcpx/plugin/opencode/v2/sampling.ts b/pkgs/mcpx/plugin/opencode/v2/sampling.ts new file mode 100644 index 0000000000..8f4c523b30 --- /dev/null +++ b/pkgs/mcpx/plugin/opencode/v2/sampling.ts @@ -0,0 +1,207 @@ +/** + * Sampling answers for the v2 plugin (#1858 SET-REMAINDER item (4), + * #2841): mcpx relays a server's sampling/createMessage to its broker + * as a sample-mode question routed to the agent audience ("sampling + * asks a model, and the agent driving mcpx has one" — elicit.Route). + * Until this module, the v2 plugin never looked at those rows, so + * every sampling request sat in the broker until its 120s TTL expired + * and the upstream heard an internal error. + * + * The v2 surface's answer is ctx.generate.text: one stateless + * completion taking a plain prompt string and returning { text } + * (pinned v2 source, protocol generate group: POST + * /api/experimental/generate, { prompt, model? } -> { data: { text } }; + * docs/compare/register/plugin-apis.md PLG-33). It has no messages, + * system prompt or tool use, so the CreateMessageRequest params the + * broker stores in the row's requestedSchema are flattened to a + * prompt: system prompt first, then each message's text blocks in + * order, labelled by role. Non-text blocks are named, not dropped + * silently. A request that carries tools or a toolChoice cannot be + * honoured by a plain-text completion, so it is left open for another + * answerer rather than answered with a result that pretends the + * tools were available. + * + * The answer posted back is a CreateMessageResult — the shape the + * broker validates (elicit.ValidateSampleResult): role "assistant", + * a non-empty model, one text content block, stopReason "endTurn". + * The model names the request's first model-preference hint when it + * gave one (hints are expressly ignorable and unchecked upstream); + * generate itself is called without a model, so the host's default + * model does the work. + * + * Trigger: there is no push surface for broker rows in the v2 plugin + * context, so setup starts a watcher that polls the daemon's elicit + * list every 5s — comfortably inside the 120s sample TTL — and stops + * on the setup cleanup. Every failure is swallowed: a missing daemon, + * a failed generation or a lost answer race (the broker refuses a + * second answer) leaves the question open for the next poll or + * another answerer, and never fails the session or setup. + */ +import type { DaemonClient } from "../mcpx/daemon.ts"; + +/** The slice of the daemon client the watcher uses. */ +export type SamplingDaemonLike = Pick; + +/** ctx.generate.text, structurally: prompt in, text out. */ +export type GenerateTextLike = (input: { + prompt: string; + model?: string; +}) => Promise; + +/** One broker row from GET /v1/elicit, the fields sampling reads. */ +export type BrokerRow = { + id?: unknown; + mode?: unknown; + audience?: unknown; + requestedSchema?: unknown; +}; + +type SamplingParams = { + messages?: unknown; + systemPrompt?: unknown; + modelPreferences?: { hints?: Array<{ name?: unknown }> }; + tools?: unknown; + toolChoice?: unknown; +}; + +const textOf = (content: unknown): string[] => { + if (typeof content === "string") return [content]; + if (Array.isArray(content)) { + const out: string[] = []; + for (const block of content) out.push(...textOf(block)); + return out; + } + if (content !== null && typeof content === "object") { + const b = content as { type?: unknown; text?: unknown }; + if (b.type === "text" && typeof b.text === "string") return [b.text]; + if (typeof b.type === "string") return [`[${b.type} content omitted]`]; + } + return []; +}; + +/** + * Flatten CreateMessageRequest params to the plain prompt + * ctx.generate.text takes. Returns undefined when the request cannot + * be answered by a plain-text completion: it carries tools or a + * toolChoice, or it has no text content at all. + */ +export function samplingPrompt(params: SamplingParams): string | undefined { + if (params.tools !== undefined || params.toolChoice !== undefined) return undefined; + const parts: string[] = []; + if (typeof params.systemPrompt === "string" && params.systemPrompt !== "") { + parts.push(params.systemPrompt); + } + const messages = Array.isArray(params.messages) ? params.messages : []; + for (const message of messages) { + if (message === null || typeof message !== "object") continue; + const m = message as { role?: unknown; content?: unknown }; + const texts = textOf(m.content); + if (texts.length === 0) continue; + const role = typeof m.role === "string" ? m.role : "user"; + parts.push(`${role}: ${texts.join("\n")}`); + } + if (parts.length === 0) return undefined; + return parts.join("\n\n"); +} + +/** The model name a sampling answer reports: the first hint, else a label. */ +export function samplingModel(params: SamplingParams): string { + const hints = params.modelPreferences?.hints; + if (Array.isArray(hints)) { + for (const hint of hints) { + if (typeof hint?.name === "string" && hint.name !== "") return hint.name; + } + } + return "opencode-v2-generate"; +} + +/** The CreateMessageResult the broker validates and relays upstream. */ +export function createMessageResult(text: string, model: string): Record { + return { + role: "assistant", + model, + content: { type: "text", text }, + stopReason: "endTurn", + }; +} + +const generateText = async (generate: GenerateTextLike, prompt: string): Promise => { + const out = (await generate({ prompt })) as + | { text?: unknown; data?: { text?: unknown } } + | null + | undefined; + const text = typeof out?.text === "string" ? out.text : out?.data?.text; + if (typeof text !== "string") throw new Error("generate.text returned no text"); + return text; +}; + +export type SamplingDeps = { + client: () => Promise; + generate: GenerateTextLike; +}; + +/** + * One poll: answer every open sample-mode, agent-audience broker row + * that a plain-text completion can honour. Returns how many answers + * were posted. Rows already being answered by this watcher are + * skipped, so a slow generation is never started twice for one row. + */ +export function createSamplingAnswerer(deps: SamplingDeps): { + pollOnce: () => Promise; +} { + const inFlight = new Set(); + const pollOnce = async (): Promise => { + const client = await deps.client().catch(() => undefined); + if (!client) return 0; + const rows = (await client.pendingElicitations().catch(() => [])) as BrokerRow[]; + let answered = 0; + for (const row of rows) { + if (row.mode !== "sample" || row.audience !== "agent") continue; + if (typeof row.id !== "string" || row.id === "" || inFlight.has(row.id)) continue; + const params = (row.requestedSchema ?? {}) as SamplingParams; + const prompt = samplingPrompt(params); + if (prompt === undefined) continue; + inFlight.add(row.id); + try { + const text = await generateText(deps.generate, prompt); + await client.answer(row.id, "accept", createMessageResult(text, samplingModel(params))); + answered++; + } catch { + // Generation failed or the answer lost its race: the row + // stays open for the next poll or another answerer. + } finally { + inFlight.delete(row.id); + } + } + return answered; + }; + return { pollOnce }; +} + +/** + * The polling watcher setup starts. The interval is unref'd where + * the runtime supports it so a forgotten stop can never keep a host + * process alive; stop() is still the contract (setup's cleanup). + */ +export function startSamplingWatcher( + deps: SamplingDeps, + intervalMs = 5000, +): { stop: () => void } { + const answerer = createSamplingAnswerer(deps); + let stopped = false; + const tick = (): void => { + if (stopped) return; + void answerer.pollOnce().catch(() => 0); + }; + const timer = setInterval(tick, intervalMs) as unknown as { + unref?: () => void; + }; + timer.unref?.(); + tick(); + return { + stop: () => { + stopped = true; + clearInterval(timer as unknown as ReturnType); + }, + }; +}