Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Enable OpenCode fast mode through per-request provider options (#1597)

Regan Bell41ced0058da3
diff --git a/plugins/web-ui/src/runtime-capabilities.ts b/plugins/web-ui/src/runtime-capabilities.ts
index 18e327afb..4544f13a2 100644
--- a/plugins/web-ui/src/runtime-capabilities.ts
+++ b/plugins/web-ui/src/runtime-capabilities.ts
@@ -21,7 +21,7 @@ export function harnessSupportsEffort(harnessId: string): boolean {
}
export function harnessSupportsFastMode(harnessId: string): boolean {
- return harnessId === "pi" || harnessId === "claude" || harnessId === "codex";
+ return harnessId === "pi" || harnessId === "claude" || harnessId === "codex" || harnessId === "opencode";
}
export function harnessSupportsSteer(harnessId: string): boolean {
diff --git a/plugins/web-ui/test/composer-picker.test.ts b/plugins/web-ui/test/composer-picker.test.ts
index 059c556f1..003b75640 100644
--- a/plugins/web-ui/test/composer-picker.test.ts
+++ b/plugins/web-ui/test/composer-picker.test.ts
@@ -362,14 +362,13 @@ test("the personal-account picker preserves composer choices and saves context d
assert.equal(composer!.currentModelOption()?.value, "opencode:alpha");
assert.equal(agent.state.model.id, "alpha");
assert.equal(composer!.state.effortLevel, "auto");
- assert.equal(composer!.state.fastMode, false);
- assert.deepEqual(saved()[1], { value: "opencode:alpha", effort: "auto", fast: false });
+ assert.equal(composer!.state.fastMode, true);
+ assert.deepEqual(saved()[1], { value: "opencode:alpha", effort: "auto", fast: true });
assert.equal(host.querySelector('[data-loadout-section="effort"]'), null);
- const unavailableFast = button('[aria-label="Fast"][role="menuitemcheckbox"]');
- assert.equal(unavailableFast.disabled, true);
- assert.equal(unavailableFast.querySelector(".loadout-shortcut")?.textContent, "Not supported by this harness");
- assert.equal(unavailableFast.getAttribute("aria-checked"), "false");
- unavailableFast.click();
+ const openCodeFast = button('[aria-label="Fast"][role="menuitemcheckbox"]');
+ assert.equal(openCodeFast.disabled, false);
+ assert.equal(openCodeFast.getAttribute("aria-checked"), "true");
+ openCodeFast.click();
assert.equal(composer!.state.fastMode, false);
button('[data-loadout-section="harness"]').click();
diff --git a/plugins/web-ui/test/model-options.test.ts b/plugins/web-ui/test/model-options.test.ts
index f41e94bd3..ecd502c04 100644
--- a/plugins/web-ui/test/model-options.test.ts
+++ b/plugins/web-ui/test/model-options.test.ts
@@ -85,6 +85,7 @@ test("harness controls retain their supported surfaces", async () => {
assert.equal(harnessSupportsEffort("opencode"), false);
assert.equal(harnessSupportsFastMode("claude"), true);
assert.equal(harnessSupportsFastMode("codex"), true);
+ assert.equal(harnessSupportsFastMode("opencode"), true);
});
test("deleted selection retains identity and transcript rendering does not borrow a replacement", async () => {
diff --git a/src/harness/opencode-harness.ts b/src/harness/opencode-harness.ts
index aa9012c47..aa8741073 100644
--- a/src/harness/opencode-harness.ts
+++ b/src/harness/opencode-harness.ts
@@ -15,7 +15,13 @@ import { createOpencodeClient, type OpencodeClient } from "@opencode-ai/sdk";
import { CONFIG_DEFAULTS, type Config } from "../config.ts";
import { customProviderApi, isCustomModelId } from "../model/custom-providers.ts";
import type { CustomProviderProtocol, CustomProviderSpec } from "../model/custom-providers.ts";
-import { DEFAULT_AGENT_MODEL_ID, modelServiceable, modelSupportedByHarness, resolveModel } from "../model/pi-models.ts";
+import {
+ DEFAULT_AGENT_MODEL_ID,
+ modelServiceable,
+ modelSupportedByHarness,
+ modelSupportsFastMode,
+ resolveModel,
+} from "../model/pi-models.ts";
import { startSignalPoll, type RunSignalStore } from "../runs/run-signal-store.ts";
import type { LlmCallUsage } from "../sessions/session-store.ts";
import type { ScopeId } from "../types.ts";
@@ -583,14 +589,23 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
}
}
if (!state) return json(res, 404, { error: "inactive session" });
- if (sessionMatch[2] === "context")
+ if (sessionMatch[2] === "context") {
+ const modelId = url.searchParams.get("model");
+ const fast = state.turn.runtime?.fastMode === true && modelSupportsFastMode(modelId ?? undefined);
+ const api = modelId ? resolveModel(modelId)?.api : undefined;
+ const modelOptions: Record<string, string> = {};
+ if (fast && api === "anthropic-messages") modelOptions.speed = "fast";
+ if (fast && (api === "openai-responses" || api === "openai-completions"))
+ modelOptions.serviceTier = "priority";
return json(res, 200, {
...(state.child ? {} : { systemPrompt: state.system, history: state.history }),
+ modelOptions,
proxyHeaders: {
"x-qm-session": sessionMatch[1],
"x-qm-token": sessionToken(bridgeSecret, sessionMatch[1]!),
},
});
+ }
if (sessionMatch[2] === "capture") {
const request = JSON.parse((await body(req)).toString("utf8")) as Record<string, unknown>;
const model = state.model;
@@ -1150,7 +1165,7 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
controlTransport: "http",
toolTransport: "plugin",
transcriptFormat: "opencode",
- capabilities: new Set(["abort", "steer", "images", "provider-sessions"]),
+ capabilities: new Set(["abort", "steer", "images", "provider-sessions", "fast-mode"]),
},
{
runTurn: runPrompt,
diff --git a/src/harness/opencode-plugin.ts b/src/harness/opencode-plugin.ts
index 9525ea717..c0af93e55 100644
--- a/src/harness/opencode-plugin.ts
+++ b/src/harness/opencode-plugin.ts
@@ -34,6 +34,7 @@ type OpenCodeWithParts = {
};
type SessionContext = {
+ modelOptions?: Record<string, unknown>;
proxyHeaders?: Record<string, string>;
systemPrompt?: string;
history?: OpenCodeWithParts[];
@@ -242,11 +243,13 @@ const OpenCodeBridgePlugin: Plugin = async ({ client }) => {
]),
);
- const sessionContext = async (sessionID: string): Promise<SessionContext> => {
+ const sessionContext = async (sessionID: string, modelID?: string): Promise<SessionContext> => {
let error: unknown;
for (let attempt = 0; attempt < 20; attempt++) {
try {
- return await request(`session/${encodeURIComponent(sessionID)}/context`);
+ return await request(
+ `session/${encodeURIComponent(sessionID)}/context${modelID ? `?model=${encodeURIComponent(modelID)}` : ""}`,
+ );
} catch (next) {
error = next;
await new Promise<void>((resolveWait) => setTimeout(resolveWait, 25));
@@ -257,6 +260,10 @@ const OpenCodeBridgePlugin: Plugin = async ({ client }) => {
return {
tool: tools,
+ "chat.params": async (input, output) => {
+ const context = await sessionContext(input.sessionID, input.model.id);
+ Object.assign(output.options, context.modelOptions ?? {});
+ },
"chat.headers": async (input: { sessionID: string }, output: { headers: Record<string, string> }) => {
const context = await sessionContext(input.sessionID);
Object.assign(output.headers, context.proxyHeaders ?? {});
diff --git a/src/model/pi-models.ts b/src/model/pi-models.ts
index d91a34a15..6da2639bf 100644
--- a/src/model/pi-models.ts
+++ b/src/model/pi-models.ts
@@ -36,7 +36,7 @@ export function thinkingLevelsForHarness(harnessId: HarnessId): readonly string[
}
export function harnessSupportsFastMode(harnessId: HarnessId): boolean {
- return harnessId === "pi" || harnessId === "claude" || harnessId === "codex";
+ return harnessId === "pi" || harnessId === "claude" || harnessId === "codex" || harnessId === "opencode";
}
export const MODEL_PROVIDERS = ["anthropic", "openai", "openrouter"] as const;
export type ModelProvider = (typeof MODEL_PROVIDERS)[number];
diff --git a/test/admin-resources.test.ts b/test/admin-resources.test.ts
index 423accb0a..a4c42673c 100644
--- a/test/admin-resources.test.ts
+++ b/test/admin-resources.test.ts
@@ -682,13 +682,13 @@ test("admin runtime saves reasoning level and fast mode with the default model",
assert.equal(unsupported.status, 200);
assert.equal((await srv.built.config.getRuntimeSelectionDurable("org:default-org"))?.fastMode, false);
- const unsupportedHarness = await fetch(url, {
+ const openCode = await fetch(url, {
method: "PUT",
headers: ADMIN,
body: JSON.stringify({ harnessId: "opencode", modelId: "claude-opus-5", effortLevel: "auto", fastMode: true }),
});
- assert.equal(unsupportedHarness.status, 200);
- assert.equal((await srv.built.config.getRuntimeSelectionDurable("org:default-org"))?.fastMode, false);
+ assert.equal(openCode.status, 200);
+ assert.equal((await srv.built.config.getRuntimeSelectionDurable("org:default-org"))?.fastMode, true);
for (const body of [
{ harnessId: "pi", modelId: "claude-opus-5", effortLevel: "extreme", fastMode: true },
diff --git a/test/harness-adapter.test.ts b/test/harness-adapter.test.ts
index e33b9ffe6..5b1a9e151 100644
--- a/test/harness-adapter.test.ts
+++ b/test/harness-adapter.test.ts
@@ -38,7 +38,7 @@ test("harness adapters declare their native control and tool transports", async
["mock", "in-process", "plugin", "dynamic", "in-process-mcp"],
);
assert.equal(pi.profile.capabilities.has("fast-mode"), true);
- assert.equal(opencode.profile.capabilities.has("fast-mode"), false);
+ assert.equal(opencode.profile.capabilities.has("fast-mode"), true);
assert.equal(opencode.profile.capabilities.has("thinking-level"), false);
});
diff --git a/test/opencode-harness.test.ts b/test/opencode-harness.test.ts
index 243da221f..783eb209c 100644
--- a/test/opencode-harness.test.ts
+++ b/test/opencode-harness.test.ts
@@ -508,3 +508,79 @@ test("OpenCode includes steered PDF and extracted documents without copying echo
assert.ok(!JSON.stringify(tape).includes(pdf));
assert.ok(!JSON.stringify(tape).includes("DOCX-QUARTZ-731"));
});
+
+for (const [modelId, fastMode, expected] of [
+ ["claude-opus-5", true, { speed: "fast" }],
+ ["gpt-5.6-sol", true, { serviceTier: "priority" }],
+ ["claude-opus-5", false, {}],
+ ["claude-sonnet-5", true, {}],
+ ["unknown-model", true, {}],
+] as const) {
+ test(`OpenCode bridge resolves fast options for ${modelId} with fast=${fastMode}`, async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "qm-opencode-fast-"));
+ const harness = createOpenCodeHarness({
+ binaryPath: fakeSidecar(
+ dir,
+ "fast-options",
+ `
+ if (req.method === "GET" && message) return json(res, []);
+ if (req.method === "POST" && message) {
+ await readBody(req);
+ const context = await fetch(process.env.OPENCODE_BRIDGE_URL + "/session/" + message[1] + "/context?model=${modelId}", {
+ headers: { authorization: "Bearer " + process.env.OPENCODE_BRIDGE_SECRET },
+ }).then(r => r.json());
+ const assistant = ${okAssistant};
+ assistant.parts[0].text = JSON.stringify(context.modelOptions);
+ return json(res, assistant);
+ }
+ `,
+ ),
+ });
+ t.after(async () => {
+ await harness.turns.close?.();
+ rmSync(dir, { recursive: true, force: true });
+ });
+ const turn = turnInput([], []);
+ turn.runtime = { modelId: "claude-opus-5", fastMode };
+ const result = await harness.turns.runTurn(turn);
+ assert.deepEqual(JSON.parse(result.reply), expected);
+ });
+}
+
+test("OpenCode child requests inherit fast mode and a reused runtime honors switching it off", async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "qm-opencode-fast-child-"));
+ const harness = createOpenCodeHarness({
+ binaryPath: fakeSidecar(
+ dir,
+ "child-fast",
+ `
+ if (req.method === "GET" && url.pathname === "/session/ses_child") return json(res, { id: "ses_child", parentID: "ses_main" });
+ if (req.method === "GET" && message) return json(res, []);
+ if (req.method === "POST" && message) {
+ await readBody(req);
+ const options = [];
+ for (const model of ["gpt-5.6-sol", "claude-sonnet-5"]) {
+ const context = await fetch(process.env.OPENCODE_BRIDGE_URL + "/session/ses_child/context?model=" + model, {
+ headers: { authorization: "Bearer " + process.env.OPENCODE_BRIDGE_SECRET },
+ }).then(r => r.json());
+ if (context.history !== undefined || context.systemPrompt !== undefined) throw new Error("child borrowed parent prompt");
+ options.push(context.modelOptions);
+ }
+ const assistant = ${okAssistant};
+ assistant.parts[0].text = JSON.stringify(options);
+ return json(res, assistant);
+ }
+ `,
+ ),
+ });
+ t.after(async () => {
+ await harness.turns.close?.();
+ rmSync(dir, { recursive: true, force: true });
+ });
+ for (const fastMode of [true, false]) {
+ const turn = turnInput([], []);
+ turn.runtime = { modelId: "claude-opus-5", fastMode };
+ const result = await harness.turns.runTurn(turn);
+ assert.deepEqual(JSON.parse(result.reply), [fastMode ? { serviceTier: "priority" } : {}, {}]);
+ }
+});
diff --git a/test/opencode-plugin-fast-mode.test.ts b/test/opencode-plugin-fast-mode.test.ts
new file mode 100644
index 000000000..8fce649cd
--- /dev/null
+++ b/test/opencode-plugin-fast-mode.test.ts
@@ -0,0 +1,56 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import plugin from "../src/harness/opencode-plugin.ts";
+import type { PluginInput, Hooks } from "@opencode-ai/plugin";
+
+test("OpenCode plugin applies session-local fast options to the actual requested model", async (t) => {
+ const previous = { url: process.env.OPENCODE_BRIDGE_URL, secret: process.env.OPENCODE_BRIDGE_SECRET };
+ const requests: string[] = [];
+ const server = createServer((req, res) => {
+ assert.equal(req.headers.authorization, "Bearer test-secret");
+ requests.push(req.url!);
+ res.setHeader("content-type", "application/json");
+ res.end(
+ JSON.stringify(
+ req.url === "/definitions"
+ ? []
+ : {
+ modelOptions: req.url?.includes("/fast/") ? { serviceTier: "priority" } : {},
+ },
+ ),
+ );
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ assert.ok(address && typeof address !== "string");
+ process.env.OPENCODE_BRIDGE_URL = `http://127.0.0.1:${address.port}`;
+ process.env.OPENCODE_BRIDGE_SECRET = "test-secret";
+ t.after(async () => {
+ for (const [key, value] of [
+ ["OPENCODE_BRIDGE_URL", previous.url],
+ ["OPENCODE_BRIDGE_SECRET", previous.secret],
+ ]) {
+ if (value === undefined) delete process.env[key!];
+ else process.env[key!] = value;
+ }
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+ const hooks = await plugin({ client: {} } as PluginInput);
+ const input = (sessionID: string) =>
+ ({ sessionID, model: { id: "gpt/alias" } }) as Parameters<NonNullable<Hooks["chat.params"]>>[0];
+ const output = () => ({
+ temperature: 0,
+ topP: 1,
+ topK: 1,
+ maxOutputTokens: undefined,
+ options: { reasoningEffort: "high" },
+ });
+ const fast = output();
+ const standard = output();
+ await Promise.all([hooks["chat.params"]!(input("fast"), fast), hooks["chat.params"]!(input("standard"), standard)]);
+ assert.deepEqual(fast.options, { reasoningEffort: "high", serviceTier: "priority" });
+ assert.deepEqual(standard.options, { reasoningEffort: "high" });
+ assert.ok(requests.includes("/session/fast/context?model=gpt%2Falias"));
+ assert.ok(requests.includes("/session/standard/context?model=gpt%2Falias"));
+});
diff --git a/test/runtime-selection.test.ts b/test/runtime-selection.test.ts
index 74ed8524f..a57a0eb2c 100644
--- a/test/runtime-selection.test.ts
+++ b/test/runtime-selection.test.ts
@@ -97,7 +97,7 @@ test("runtime resolution carries reasoning and fast-mode defaults into turns", (
modelId: "claude-opus-5",
},
),
- { harnessId: "opencode", modelId: "claude-opus-5", fastMode: false },
+ { harnessId: "opencode", modelId: "claude-opus-5", fastMode: true },
);
});