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
51 changes: 48 additions & 3 deletions pkgs/mcpx/plugin/opencode/v2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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,
Expand Down Expand Up @@ -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<void> {
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({
Expand Down Expand Up @@ -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<SamplingDaemonLike | undefined> => {
const client = (await runtime?.daemon().catch(() => undefined)) as
| Partial<SamplingDaemonLike>
| undefined;
if (
typeof client?.pendingElicitations !== "function" ||
typeof client?.answer !== "function"
) {
return undefined;
}
return client as SamplingDaemonLike;
},
});
return () => watcher.stop();
}

export default {
Expand Down
9 changes: 9 additions & 0 deletions pkgs/mcpx/plugin/opencode/v2/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
};
}
191 changes: 191 additions & 0 deletions pkgs/mcpx/plugin/opencode/v2/sampling.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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);
});
});
Loading
Loading