Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add Responses protocol for custom providers (#1178)

Sina Matianb52b1c17fd0e
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index 236c3126f..efd85826c 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -6232,7 +6232,7 @@
<div class="project-dialog-head">
<div>
<h2 id="custom-provider-title">Add custom provider</h2>
- <p>Connect any OpenAI- or Anthropic-compatible endpoint.</p>
+ <p>Connect an OpenAI Chat Completions, OpenAI Responses, or Anthropic Messages endpoint.</p>
</div>
<button class="project-icon-button" type="button" id="custom-provider-close" aria-label="Close">×</button>
</div>
@@ -6241,8 +6241,9 @@
<label>Display name<input id="custom-provider-name" autocomplete="off" placeholder="LiteLLM" /></label>
<label
>Protocol<select id="custom-provider-protocol">
- <option value="openai">OpenAI-compatible</option>
- <option value="anthropic">Anthropic-compatible</option>
+ <option value="openai">OpenAI Chat Completions</option>
+ <option value="openai-responses">OpenAI Responses</option>
+ <option value="anthropic">Anthropic Messages</option>
</select></label
>
<label
@@ -6290,6 +6291,11 @@
const $ = (id) => document.getElementById(id);
const EFFECTS = ["allow", "deny", "require_approval"];
const EFFECT_LABELS = { allow: "Allow", deny: "Deny", require_approval: "Require approval" };
+ const CUSTOM_PROVIDER_PROTOCOL_LABELS = {
+ openai: "OpenAI Chat Completions",
+ "openai-responses": "OpenAI Responses",
+ anthropic: "Anthropic Messages",
+ };
const SECTIONS = [
{ views: ["governance", "models", "credentials", "connectors", "customize", "users"] },
{ label: "Logs", views: ["history", "slack", "judgments", "errors", "audit", "egress", "metrics"] },
@@ -6336,7 +6342,7 @@
providers.className = "card sv-models";
providers.id = "card-custom-providers";
providers.innerHTML =
- '<div class="head"><h2>Custom providers</h2><p>Any OpenAI- or Anthropic-compatible endpoint. Its models join the pickers above and below.</p></div><div class="body"><div class="tablewrap" id="model-custom-provider-table"><table><thead><tr><th>Provider</th><th>Protocol</th><th>Endpoint</th><th>Models</th><th>Key</th><th></th></tr></thead><tbody id="model-custom-provider-rows"></tbody></table></div><div id="custom-provider-summary" class="hint">Loading providers…</div></div><div class="foot"><button type="button" id="add-custom-provider">+ Add provider</button></div>';
+ '<div class="head"><h2>Custom providers</h2><p>OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages endpoints. Their models join the pickers above and below.</p></div><div class="body"><div class="tablewrap" id="model-custom-provider-table"><table><thead><tr><th>Provider</th><th>Protocol</th><th>Endpoint</th><th>Models</th><th>Key</th><th></th></tr></thead><tbody id="model-custom-provider-rows"></tbody></table></div><div id="custom-provider-summary" class="hint">Loading providers…</div></div><div class="foot"><button type="button" id="add-custom-provider">+ Add provider</button></div>';
const governanceAmbient = document.createElement("section");
governanceAmbient.className = "card sv-governance hidden";
@@ -9657,7 +9663,7 @@
const tr = document.createElement("tr");
[
provider.name + " (" + provider.id + ")",
- provider.protocol === "anthropic" ? "Anthropic" : "OpenAI",
+ CUSTOM_PROVIDER_PROTOCOL_LABELS[provider.protocol] || provider.protocol,
provider.baseUrl,
String(provider.models.length),
provider.hasKey ? "Set (write-only)" : "None",
@@ -9682,7 +9688,7 @@
const tr = document.createElement("tr");
const cells = [
provider.name + " (" + provider.id + ")",
- provider.protocol === "anthropic" ? "Anthropic" : "OpenAI",
+ CUSTOM_PROVIDER_PROTOCOL_LABELS[provider.protocol] || provider.protocol,
provider.baseUrl,
provider.models.map((model) => model.id).join(", "),
provider.hasKey ? "set (write-only)" : "none",
diff --git a/plugins/admin/test/default-view.test.ts b/plugins/admin/test/default-view.test.ts
index 4d8100b93..c715193a2 100644
--- a/plugins/admin/test/default-view.test.ts
+++ b/plugins/admin/test/default-view.test.ts
@@ -503,6 +503,9 @@ test("custom providers share one in-place editor instead of linking to onboardin
assert.match(html, /\$\("add-custom-provider"\)\.onclick = \(\) => openCustomProviderEditor\(\)/);
assert.match(html, /\$\("onboarding-add-custom-provider"\)\.onclick = \(\) => openCustomProviderEditor\(\)/);
assert.match(html, /edit\.onclick = \(\) => openCustomProviderEditor\(provider\)/);
+ assert.match(html, /<option value="openai-responses">OpenAI Responses<\/option>/);
+ assert.match(html, /CUSTOM_PROVIDER_PROTOCOL_LABELS\[provider\.protocol\] \|\| provider\.protocol/);
+ assert.match(html, /\$\("custom-provider-protocol"\)\.value = provider\?\.protocol \|\| "openai"/);
assert.match(html, /actions\.append\(edit, customProviderRemoveButton\(provider\)\)/);
assert.match(html, /if \(view === "models"\) await loadScope\(\)/);
assert.doesNotMatch(html, /\$\("add-custom-provider"\)\.onclick = \(\) => \{[\s\S]*?setView\("onboarding"\)/);
diff --git a/src/harness/opencode-harness.ts b/src/harness/opencode-harness.ts
index 624933d49..947d5db32 100644
--- a/src/harness/opencode-harness.ts
+++ b/src/harness/opencode-harness.ts
@@ -7,8 +7,8 @@ import { pathToFileURL } from "node:url";
import { spawn, type ChildProcess } from "node:child_process";
import { createOpencodeClient, type OpencodeClient } from "@opencode-ai/sdk";
import { CONFIG_DEFAULTS, type Config } from "../config.ts";
-import { isCustomModelId } from "../model/custom-providers.ts";
-import type { CustomProviderSpec } from "../model/custom-providers.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 { startSignalPoll, type RunSignalStore } from "../runs/run-signal-store.ts";
import type { LlmCallUsage } from "../sessions/session-store.ts";
@@ -42,6 +42,13 @@ const OPENCODE_VERSION = "1.17.18";
const OPENCODE_IDLE_WAIT_MS = 30 * 60_000;
export const OPENCODE_STARTUP_TIMEOUT_MS = 90_000;
+function customProviderNpm(protocol: CustomProviderProtocol): string {
+ const api = customProviderApi(protocol);
+ if (api === "anthropic-messages") return "@ai-sdk/anthropic";
+ if (api === "openai-responses") return "@ai-sdk/openai";
+ return "@ai-sdk/openai-compatible";
+}
+
export interface OpenCodeHarnessOptions extends HarnessToolPlumbing {
modelId?: string | ((scope?: ScopeId) => string | undefined);
defaultModelId?: string;
@@ -643,7 +650,7 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes
custom.map(({ spec, apiKey }) => [
spec.id,
{
- npm: spec.protocol === "anthropic" ? "@ai-sdk/anthropic" : "@ai-sdk/openai-compatible",
+ npm: customProviderNpm(spec.protocol),
name: spec.name,
options: { baseURL: spec.baseUrl, ...(apiKey ? { apiKey } : {}) },
models: Object.fromEntries(
diff --git a/src/model/custom-providers.ts b/src/model/custom-providers.ts
index 8a70008f8..843211dd9 100644
--- a/src/model/custom-providers.ts
+++ b/src/model/custom-providers.ts
@@ -1,9 +1,9 @@
/**
* Custom model providers.
*
- * An org admin can register additional model providers that speak one of
- * the two wire protocols we already run — OpenAI-compatible or
- * Anthropic-compatible — by giving a base URL, an API key, and the model
+ * An org admin can register additional model providers that speak a wire
+ * protocol we already run — OpenAI Chat Completions, OpenAI Responses,
+ * or Anthropic Messages — by giving a base URL, an API key, and the model
* ids to expose. Registered models resolve like built-ins (the pi
* harness reaches them through the same request path), surface in the
* catalog, and are gated to harnesses that route through pi-ai.
@@ -16,7 +16,7 @@
import { modelIdReserved } from "./pi-models.ts";
import { parseProviderBaseUrl, PROVIDER_IDS } from "./provider-endpoints.ts";
-export const CUSTOM_PROVIDER_PROTOCOLS = ["openai", "anthropic"] as const;
+export const CUSTOM_PROVIDER_PROTOCOLS = ["openai", "openai-responses", "anthropic"] as const;
export type CustomProviderProtocol = (typeof CUSTOM_PROVIDER_PROTOCOLS)[number];
interface CustomModelSpec {
@@ -88,7 +88,7 @@ export interface CustomRuntimeModel {
id: string;
name: string;
provider: string;
- api: "openai-completions" | "anthropic-messages";
+ api: "openai-completions" | "openai-responses" | "anthropic-messages";
baseUrl: string;
reasoning: boolean;
input: ("text" | "image")[];
@@ -100,12 +100,18 @@ export interface CustomRuntimeModel {
const DEFAULT_CONTEXT_WINDOW = 128_000;
const DEFAULT_MAX_TOKENS = 8_192;
+export function customProviderApi(protocol: CustomProviderProtocol): CustomRuntimeModel["api"] {
+ if (protocol === "anthropic") return "anthropic-messages";
+ if (protocol === "openai-responses") return "openai-responses";
+ return "openai-completions";
+}
+
function toRuntimeModel(provider: CustomProviderSpec, m: CustomModelSpec): CustomRuntimeModel {
return {
id: m.id,
name: m.name?.trim() || m.id,
provider: provider.id,
- api: provider.protocol === "anthropic" ? "anthropic-messages" : "openai-completions",
+ api: customProviderApi(provider.protocol),
baseUrl: provider.baseUrl,
reasoning: false,
input: ["text"],
@@ -172,7 +178,7 @@ export function customModelsJson(): { providers: Record<string, unknown> } | und
{
name: spec.name,
baseUrl: spec.baseUrl,
- api: spec.protocol === "anthropic" ? "anthropic-messages" : "openai-completions",
+ api: customProviderApi(spec.protocol),
models: spec.models.map((m) => ({
id: m.id,
name: m.name ?? m.id,
diff --git a/test/custom-provider-e2e.test.ts b/test/custom-provider-e2e.test.ts
index cc51db83f..25884aa0b 100644
--- a/test/custom-provider-e2e.test.ts
+++ b/test/custom-provider-e2e.test.ts
@@ -19,6 +19,7 @@ import { setCustomProviders } from "../src/model/custom-providers.ts";
import { createCustomProviderStore } from "../src/model/custom-provider-store.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
import type { Api, Model } from "@earendil-works/pi-ai";
+import { verificationUpstream } from "./support/model-verification-upstream.ts";
const ADMIN = { "content-type": "application/json", "x-admin-actor": "admin-alice@default-org" };
@@ -196,6 +197,78 @@ test("QA: full custom-provider lifecycle against a live fake upstream", async ()
}
});
+test("QA: openai-responses custom provider serves a real turn through the generated Pi registry", async () => {
+ const upstream = await verificationUpstream();
+ const upstreamUrl = `${upstream.url}/v1`;
+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "qa-responses-")) }));
+ const server = createInsecureTestServer(built.app, {
+ config: built.config,
+ modelCredentials: built.modelCredentials,
+ customProviders: built.customProviders,
+ refreshCustomProviders: built.refreshCustomProviders,
+ admin: built.admin,
+ auditLog: built.auditLog,
+ harnessId: "pi",
+ });
+ server.listen(0);
+ const base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ const api = (path: string, init?: RequestInit) => fetch(`${base}${path}`, { headers: ADMIN, ...init });
+ const spec = {
+ name: "Responses Provider",
+ protocol: "openai-responses",
+ baseUrl: upstreamUrl,
+ models: [{ id: "responses-custom-model", name: "Responses Custom Model" }],
+ };
+ try {
+ let response = await api("/v1/admin/custom-providers/responses-provider", {
+ method: "PUT",
+ body: JSON.stringify({ ...spec, apiKey: "sk-responses-test" }),
+ });
+ assert.equal(response.status, 200);
+ const validation = upstream.requests.find((request) => request.path === "/v1/models");
+ assert.equal(validation?.authorization, "Bearer sk-responses-test");
+ assert.equal(((await response.json()) as { status: { protocol: string } }).status.protocol, "openai-responses");
+
+ const model = resolveModel("responses-custom-model");
+ assert.ok(model);
+ assert.equal(model.api, "openai-responses");
+ const reply = await oneShot(
+ "qa-responses",
+ model as Model<Api>,
+ { "responses-provider": "sk-responses-test" },
+ "be terse",
+ "reply",
+ );
+ assert.equal(reply, "VERIFIED MODEL REPLY");
+ const request = upstream.requests.find((item) => item.path === "/v1/responses");
+ assert.ok(request);
+ assert.equal(request.body.model, "responses-custom-model");
+ assert.equal(request.body.stream, true);
+ assert.ok(Array.isArray(request.body.input));
+ assert.equal(
+ upstream.requests.some((item) => item.path.endsWith("/chat/completions")),
+ false,
+ );
+
+ response = await api("/v1/admin/custom-providers/responses-provider", {
+ method: "PUT",
+ body: JSON.stringify({ ...spec, name: "Responses Provider Edited" }),
+ });
+ assert.equal(response.status, 200);
+ response = await api("/v1/admin/custom-providers");
+ const providers = (await response.json()) as {
+ providers: Array<{ id: string; name: string; protocol: string; hasKey: boolean }>;
+ };
+ const saved = providers.providers.find((provider) => provider.id === "responses-provider");
+ assert.equal(saved?.name, "Responses Provider Edited");
+ assert.equal(saved?.protocol, "openai-responses");
+ assert.equal(saved?.hasKey, true);
+ } finally {
+ server.close();
+ await upstream.close();
+ }
+});
+
test("QA: anthropic-protocol custom provider serves a real turn (correct wire shape + headers)", async () => {
const seen: Array<{ path: string; apiKeyHeader?: string; version?: string; model?: string }> = [];
const upstream = createServer((req, res) => {
diff --git a/test/custom-providers.test.ts b/test/custom-providers.test.ts
index 6621b64d9..dfe3726fa 100644
--- a/test/custom-providers.test.ts
+++ b/test/custom-providers.test.ts
@@ -5,6 +5,7 @@ import {
resolveCustomModel,
isCustomModelId,
customModelCatalog,
+ customModelsJson,
validateCustomProviderSpec,
} from "../src/model/custom-providers.ts";
import { builtInModelCatalog } from "../src/model/model-catalog.ts";
@@ -51,6 +52,21 @@ test("anthropic-protocol providers produce anthropic-messages models with defaul
assert.equal(model.cost.input, 0);
});
+test("openai-responses survives both custom model mappings", () => {
+ setCustomProviders([
+ {
+ id: "responses-gateway",
+ name: "Responses Gateway",
+ protocol: "openai-responses",
+ baseUrl: "https://responses.example.com/v1",
+ models: [{ id: "responses-model" }],
+ },
+ ]);
+ assert.equal(resolveCustomModel("responses-model")?.api, "openai-responses");
+ const generated = customModelsJson() as { providers: Record<string, { api: string }> };
+ assert.equal(generated.providers["responses-gateway"]?.api, "openai-responses");
+});
+
test("resolveModel falls back to custom models; built-ins shadow custom ids", () => {
setCustomProviders([{ ...GATEWAY, models: [{ id: "acme-large" }, { id: "claude-opus-5", name: "impostor" }] }]);
assert.equal(resolveModel("acme-large")?.provider, "acme-gateway");
diff --git a/test/opencode-harness.test.ts b/test/opencode-harness.test.ts
index 815619131..5156193d8 100644
--- a/test/opencode-harness.test.ts
+++ b/test/opencode-harness.test.ts
@@ -375,6 +375,16 @@ test("custom providers materialize into the opencode config (enabled + provider
},
apiKey: "sk-lite",
},
+ {
+ spec: {
+ id: "responses-proxy",
+ name: "Responses Proxy",
+ protocol: "openai-responses" as const,
+ baseUrl: "http://responses.internal/v1",
+ models: [{ id: "responses-model" }],
+ },
+ apiKey: "sk-responses",
+ },
],
});
const entries: SessionEntry[] = [];
@@ -383,11 +393,14 @@ test("custom providers materialize into the opencode config (enabled + provider
await harness.turns.runTurn(turnInput(entries, llmRows));
const config = JSON.parse(readFileSync(dump, "utf8"));
assert.ok(config.enabled_providers.includes("litellm"));
+ assert.ok(config.enabled_providers.includes("responses-proxy"));
const litellm = config.provider.litellm;
assert.equal(litellm.npm, "@ai-sdk/openai-compatible");
assert.equal(litellm.options.baseURL, "http://litellm.internal:4000/v1");
assert.equal(litellm.options.apiKey, "sk-lite");
assert.deepEqual(litellm.models["deepseek-chat"], { name: "DeepSeek", limit: { context: 128000, output: 8192 } });
+ assert.equal(config.provider["responses-proxy"].npm, "@ai-sdk/openai");
+ assert.equal(config.provider["responses-proxy"].options.apiKey, "sk-responses");
} finally {
await harness.turns.close?.();
rmSync(dir, { recursive: true, force: true });
diff --git a/test/support/model-verification-upstream.ts b/test/support/model-verification-upstream.ts
index 616dd60d7..8b6c89c06 100644
--- a/test/support/model-verification-upstream.ts
+++ b/test/support/model-verification-upstream.ts
@@ -17,7 +17,7 @@ export async function verificationUpstream() {
raw += chunk;
});
req.on("end", () => {
- const body = JSON.parse(raw);
+ const body = raw ? JSON.parse(raw) : {};
requests.push({
path: req.url!,
body,
@@ -36,6 +36,10 @@ export async function verificationUpstream() {
}),
);
}
+ if (req.method === "GET" && req.url?.endsWith("/models")) {
+ res.writeHead(200, { "content-type": "application/json" });
+ return res.end(JSON.stringify({ data: [] }));
+ }
res.writeHead(200, { "content-type": "text/event-stream" });
const text = behavior.empty ? "" : "VERIFIED MODEL REPLY";
const send = (type: string, data: object) =>