@qlairoslabs/acp-client 0.13.4-alpha.1 → 0.13.5-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONSUMER_GUIDE.md CHANGED
@@ -1172,7 +1172,7 @@ import { Agent, ADAPTERS, type AgentHarnessConfig } from "@qlairoslabs/acp-clien
1172
1172
  export async function openNative(
1173
1173
  directory: string,
1174
1174
  model: AgentHarnessConfig["config"]["model"] = {
1175
- protocol: "openrouter", model: "openai/gpt-4.1-mini", apiKeyEnv: "OPENROUTER_API_KEY",
1175
+ protocol: "openrouter", model: "openai/gpt-6-luna", apiKeyEnv: "OPENROUTER_API_KEY",
1176
1176
  },
1177
1177
  ) {
1178
1178
  return Agent.open({
@@ -1217,7 +1217,23 @@ Harness policies grant `allow`, `ask` or `deny` by tool name and define a
1217
1217
  fallback. This host responder grants one call to the read-only lookup.
1218
1218
  Subscribe to `items_receipt` when you need delivery evidence.
1219
1219
 
1220
- Set `harness.config.model.contextBudget` on OpenRouter or OpenAI-compatible models
1220
+ To use an OpenCode Go API key with the native harness, make the key
1221
+ available in the harness process and pass the Go preset to `openNative`.
1222
+
1223
+ ```ts
1224
+ const agent = await openNative(directory, {
1225
+ protocol: "opencode-go",
1226
+ model: "deepseek-v4.1-flash",
1227
+ });
1228
+ ```
1229
+
1230
+ The harness reads `OPENCODE_API_KEY` by default. Set `apiKeyEnv` if your
1231
+ launcher supplies a different variable, such as `OPENCODE_GO_API_KEY`.
1232
+ The preset sends a stable routing header per channel and uses Go's Chat
1233
+ Completions endpoint. DeepSeek V4.1 Flash may require allowing the Global
1234
+ region in the Go workspace. [OpenCode Go model settings](https://opencode.ai/docs/console/go/#enable-restricted-models)
1235
+
1236
+ Set `harness.config.model.contextBudget` on OpenRouter, OpenCode Go or OpenAI-compatible models
1221
1237
  to fit a larger inference request. For example, a model with a 128,000-token
1222
1238
  window can use `contextBudget: { contextWindowTokens: 128_000, outputReserveTokens: 4096 }`.
1223
1239
  The reserve only affects local fitting. Set `maxOutputTokens` to also request an
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.4-alpha.1",
3
+ "version": "0.13.5-alpha.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -1,4 +1,6 @@
1
1
  import type { ModelAttempt, ModelAttemptEvent } from "../../contracts/model-execution.ts";
2
+ import { createHash } from "node:crypto";
3
+ import { OPENCODE_GO_BASE_URL, type CompatibleModel } from "../../contracts/config-permissions.ts";
2
4
  import { imageDataPrefix, readVerifiedImage, VisionInputError, type AttachmentLookup } from "../attachments/vision.ts";
3
5
  import { ATTACHMENT_LIMITS, type AttachmentMetadata } from "../../contracts/attachments.ts";
4
6
  import { chatRequestSizer, prepareChatRequest } from "./chat-request.ts";
@@ -16,19 +18,19 @@ function isProviderContextError(value: unknown): boolean {
16
18
 
17
19
  /** Error bodies are only needed for classification. Read a small prefix and
18
20
  * release the response even if the endpoint sends an unbounded body. */
19
- async function readContextError(response: Response): Promise<boolean> {
20
- if (!response.body) return false;
21
+ async function readErrorBody(response: Response): Promise<unknown> {
22
+ if (!response.body) return;
21
23
  const reader = response.body.getReader(), decoder = new TextDecoder();
22
24
  let value = "", remaining = 16 * 1024;
23
25
  try {
24
26
  while (remaining > 0) {
25
27
  const chunk = await reader.read();
26
- if (chunk.done) return isProviderContextError(JSON.parse(value + decoder.decode()));
28
+ if (chunk.done) return JSON.parse(value + decoder.decode());
27
29
  value += decoder.decode(chunk.value.subarray(0, remaining), { stream: true });
28
30
  remaining -= chunk.value.byteLength;
29
31
  }
30
- return isProviderContextError(JSON.parse(value + decoder.decode()));
31
- } catch { return false; }
32
+ return JSON.parse(value + decoder.decode());
33
+ } catch { return; }
32
34
  finally { void reader.cancel().catch(() => {}); reader.releaseLock(); }
33
35
  }
34
36
 
@@ -40,10 +42,36 @@ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof
40
42
  return chatAttempt(apiKey, model, fetcher, onRequest, undefined, vision);
41
43
  }
42
44
  export function openAICompatibleAttempt(baseUrl: string, model: string, apiKey?: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, metadata?: Vision["metadata"]): ModelAttempt {
45
+ return compatibleAttempt(baseUrl, model, apiKey, fetcher, onRequest, metadata);
46
+ }
47
+
48
+ export function managedCompatibleAttempt(model: CompatibleModel, conversation: { sessionId: string; channelId: string },
49
+ apiKey?: string, onRequest?: (body: string) => void, metadata?: Vision["metadata"], fetcher: typeof fetch = fetch): ModelAttempt {
50
+ if (model.protocol === "openai-compatible")
51
+ return compatibleAttempt(model.baseUrl, model.model, apiKey, fetcher, onRequest, metadata);
52
+ // Restarts and retries share the same cache affinity. Separate channels
53
+ // never send each other's identifiers to the provider.
54
+ const affinity = createHash("sha256").update(JSON.stringify(["acp-client/opencode-go/v1", conversation.sessionId, conversation.channelId])).digest("hex");
55
+ return compatibleAttempt(OPENCODE_GO_BASE_URL, model.model, apiKey, fetcher, onRequest, metadata, "ses_" + affinity);
56
+ }
57
+
58
+ function compatibleAttempt(baseUrl: string, model: string, apiKey: string | undefined, fetcher: typeof fetch,
59
+ onRequest?: (body: string) => void, metadata?: Vision["metadata"], goSession?: string): ModelAttempt {
43
60
  const references: Vision | undefined = metadata ? { supported: false, metadata, read: () => { throw new Error("Image bytes unavailable for text-only model"); } } : undefined;
44
- return chatAttempt(apiKey, model, fetcher, onRequest, `${baseUrl}/chat/completions`, references);
61
+ return chatAttempt(apiKey, model, fetcher, onRequest, `${baseUrl}/chat/completions`, references, goSession);
45
62
  }
46
- function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void, endpoint?: string, vision?: Vision): ModelAttempt {
63
+
64
+ function goFailureCode(status: number, body: unknown) {
65
+ const error = body && typeof body === "object" && "error" in body ? body.error : body;
66
+ const fields = error && typeof error === "object" ? error as { code?: unknown; type?: unknown } : undefined;
67
+ if (fields?.code === "MissingSessionID" || fields?.type === "MissingSessionID") return "missing_session_id";
68
+ if (status === 401 || fields?.code === "InvalidAPIKey" || fields?.type === "InvalidAPIKey") return "invalid_api_key";
69
+ if (status === 403) return "access_denied";
70
+ if (status === 429) return "rate_limited";
71
+ }
72
+
73
+ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void,
74
+ endpoint?: string, vision?: Vision, goSession?: string): ModelAttempt {
47
75
  return async function* (request, signal) {
48
76
  const imageUrls: string[] = [];
49
77
  const compatible = endpoint !== undefined;
@@ -108,19 +136,30 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
108
136
  const errorText = (error: unknown) => endpoint ? "Chat Completions transport failed" : redact(String(error));
109
137
  onRequest?.(imageUrls.length ? redact(body) : body);
110
138
  let response: Response;
111
- try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: { ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json" }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
139
+ try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: {
140
+ ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json",
141
+ ...(goSession ? { "User-Agent": "acp-client/native-harness", "x-opencode-session": goSession } : {}),
142
+ }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
112
143
  catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; return; }
113
144
  if (!response.ok) {
114
145
  if (endpoint) {
115
146
  if (response.status >= 300 && response.status < 400) {
116
147
  void response.body?.cancel().catch(() => {});
117
- yield { type: "failure", kind: "provider", message: "redirect_refused" }; return;
148
+ yield { type: "failure", kind: "provider", message: "redirect_refused",
149
+ ...(goSession ? { providerFailure: `OpenCode Go HTTP ${response.status} (redirect_refused)` } : {}) }; return;
150
+ }
151
+ const upstream = await readErrorBody(response);
152
+ if (isProviderContextError(upstream)) { yield providerContextFailure; return; }
153
+ if (goSession) {
154
+ const code = goFailureCode(response.status, upstream);
155
+ const message = `OpenCode Go HTTP ${response.status}${code ? ` (${code})` : ""}`;
156
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message, providerFailure: message };
157
+ return;
118
158
  }
119
- if (await readContextError(response)) { yield providerContextFailure; return; }
120
159
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}` }; return;
121
160
  }
122
161
  if (profile) {
123
- if (await readContextError(response)) { yield providerContextFailure; return; }
162
+ if (isProviderContextError(await readErrorBody(response))) { yield providerContextFailure; return; }
124
163
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request",
125
164
  message: `OpenRouter HTTP ${response.status}` }; return;
126
165
  }
@@ -6,7 +6,8 @@ export const MODEL_EXECUTION_DEFAULTS: Readonly<ModelExecutionSettings> = { time
6
6
  export class ModelCallError extends Error {
7
7
  constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string,
8
8
  readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
9
- readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure) { super(message); this.name = "ModelCallError"; }
9
+ readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
10
+ readonly providerFailure?: string) { super(message); this.name = "ModelCallError"; }
10
11
  }
11
12
  class ModelStorageError extends Error {}
12
13
  function take<T>(result: StorageResult<T>): T {
@@ -44,11 +45,12 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
44
45
  let deadline = 0, output = false;
45
46
  const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome,
46
47
  attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
47
- contextFailure?: import("../../contracts/context.ts").ContextLimitFailure): never => {
48
+ contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
49
+ providerFailure?: string): never => {
48
50
  const result = options.store.finishCall(call.callId, outcome);
49
51
  if (!result.ok && !(outcome === "interrupted" && result.error.code === "invalid_state")) take(result);
50
52
  if (output) options.incomplete?.({ messageId: call.messageId, reason: outcome });
51
- throw new ModelCallError(outcome, detail, attachmentFailure, contextFailure);
53
+ throw new ModelCallError(outcome, detail, attachmentFailure, contextFailure, providerFailure);
52
54
  };
53
55
  for (let ordinal = 0; ordinal <= Math.min(1, settings.maxRetries); ordinal++) {
54
56
  if (options.signal?.aborted) return finish("interrupted");
@@ -108,7 +110,10 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
108
110
  if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
109
111
  if (terminal?.type === "failure" && terminal.code) return finish("failed", terminal.message, { code: terminal.code, attachmentIds: [...terminal.attachmentIds ?? []] });
110
112
  if (terminal?.type === "failure" && terminal.contextFailure) return finish("failed", terminal.message, undefined, terminal.contextFailure);
111
- if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) return finish(failure === "incomplete" ? "incomplete" : "failed");
113
+ if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) {
114
+ const providerFailure = terminal?.type === "failure" ? terminal.providerFailure : undefined;
115
+ return finish(failure === "incomplete" ? "incomplete" : "failed", providerFailure, undefined, undefined, providerFailure);
116
+ }
112
117
  if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
113
118
  const delay = await new Promise<"ready" | "interrupted">(resolve => {
114
119
  const done = (result: "ready" | "interrupted") => { clearTimeout(wait); options.signal?.removeEventListener("abort", interrupted); resolve(result); };
@@ -14,7 +14,16 @@ export interface ModelContextBudget {
14
14
  }
15
15
  export type ManagedModel = { protocol: "scripted"; script: string; imageInput?: boolean }
16
16
  | { protocol: "openrouter"; model: string; apiKeyEnv: string; imageInput?: boolean; contextBudget?: ModelContextBudget }
17
- | { protocol: "openai-compatible"; providerId: string; model: string; baseUrl: string; apiKeyEnv?: string; contextBudget?: ModelContextBudget };
17
+ | { protocol: "openai-compatible"; providerId: string; model: string; baseUrl: string; apiKeyEnv?: string; contextBudget?: ModelContextBudget }
18
+ | { protocol: "opencode-go"; model: string; apiKeyEnv?: string; contextBudget?: ModelContextBudget };
19
+
20
+ /** Both text-only managed sources use the same Chat Completions client. */
21
+ export type CompatibleModel = Extract<ManagedModel, { protocol: "openai-compatible" | "opencode-go" }>;
22
+ export const OPENCODE_GO_BASE_URL = "https://opencode.ai/inference/go/openai/v1";
23
+ export const OPENCODE_GO_KEY_ENV = "OPENCODE_API_KEY";
24
+ export function isCompatibleModel(model: ManagedModel | undefined): model is CompatibleModel {
25
+ return model?.protocol === "openai-compatible" || model?.protocol === "opencode-go";
26
+ }
18
27
  /** Decision 0035: independent portable web backends, with credential names only. */
19
28
  export interface ExaSearchConfig { backend: "exa"; apiKeyEnv?: string; maxResults?: number; excerptBytes?: number; deadlineMs?: number }
20
29
  export type WebFetchConfig = { backend: "exa"; apiKeyEnv?: string; deadlineMs?: number } | { backend: "http"; deadlineMs?: number };
@@ -33,7 +33,10 @@ export type ModelAttemptEvent =
33
33
  | { type: "response"; response: ModelResponse; providerRequestId?: string }
34
34
  | { type: "failure"; kind: "transient" | "invalid_request" | "invalid_config" | "provider"; message: string; providerRequestId?: string;
35
35
  code?: "unsupported_image" | "attachment_unavailable" | "transfer_limit"; attachmentIds?: readonly string[];
36
- contextFailure?: import("./context.ts").ContextLimitFailure };
36
+ contextFailure?: import("./context.ts").ContextLimitFailure;
37
+ /** Safe provider diagnosis for the turn outcome. Adapters must construct
38
+ * this from fixed labels and status codes, never from the response body. */
39
+ providerFailure?: string };
37
40
  /** One attempt emits exactly one terminal response or failure unless aborted;
38
41
  * EOF without a terminal is incomplete. A consumer ignores events after the
39
42
  * first terminal, timeout or abort. The adapter assembles and validates tools. */
@@ -1,3 +1,4 @@
1
+ import { isCompatibleModel } from "./contracts/config-permissions.ts";
1
2
  import { isWebTool } from "./capabilities/tools/web/definitions.ts";
2
3
  import { guardedReminderDefinitions, executeReminderTool, isReminderTool, reminderAction, reminderDefinitions } from "./capabilities/tools/reminders/index.ts";
3
4
  import { createReminderRuntime } from "./runtime/reminders.ts";
@@ -74,7 +75,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
74
75
  const modelConfig = owner.value?.model;
75
76
  const contextBudget = modelConfig?.protocol !== "scripted" ? modelConfig?.contextBudget : undefined;
76
77
  const sizeRequest = modelConfig && modelConfig.protocol !== "scripted" && contextBudget
77
- ? chatRequestSizer(modelConfig.model, modelConfig.protocol === "openai-compatible", contextBudget, id => {
78
+ ? chatRequestSizer(modelConfig.model, isCompatibleModel(modelConfig), contextBudget, id => {
78
79
  const attachment = store.readManagedAttachment?.(id);
79
80
  return attachment?.ok ? attachment.value?.metadata : undefined;
80
81
  }) : undefined;
@@ -91,7 +92,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
91
92
  };
92
93
  const config = owner.value ?? { version: 1 as const, system: options.systemPrompt, model: { protocol: "scripted" as const, script: "legacy" },
93
94
  defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow" as const, tools: {} } } };
94
- if (options.imageInput && (config.model.protocol === "openai-compatible" || config.model.imageInput !== true)) throw new Error("Image input requires explicit model configuration");
95
+ if (options.imageInput && (isCompatibleModel(config.model) || config.model.imageInput !== true)) throw new Error("Image input requires explicit model configuration");
95
96
  if (options.config?.mcpServers !== undefined) {
96
97
  const canonical = (value: unknown) => JSON.stringify(value, (_key, object) =>
97
98
  object && typeof object === "object" && !Array.isArray(object)
@@ -270,6 +271,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
270
271
  // runner can write a normal terminal outcome. The draft must still end.
271
272
  if (error instanceof ModelCallError && error.message === "script_exhausted") throw Object.assign(new Error(error.message), { outcome: "script_exhausted" });
272
273
  if (error instanceof ModelCallError && error.contextFailure) throw limitError(error.contextFailure);
274
+ if (error instanceof ModelCallError && error.providerFailure) throw Object.assign(error, { outcome: error.providerFailure });
273
275
  if (draftId && !(error instanceof ModelCallError)) emit({ channel: turn.channelId,
274
276
  event: { type: "text_incomplete", turnId: String(turn.turnId), messageId: draftId, reason: "failed" } });
275
277
  throw error;
@@ -13,7 +13,7 @@ import { openRouter } from "../../capabilities/model/openrouter.ts";
13
13
  import { loadScenario, scriptedCompatibilityKey } from "../../capabilities/model/scenario-file.ts";
14
14
  import { scenarioAttempt } from "../../capabilities/model/scenario-attempt.ts";
15
15
  import { bindModelAttempt } from "../../capabilities/model/attempt.ts";
16
- import { openAICompatibleAttempt, openRouterAttempt } from "../../capabilities/model/openrouter-stream.ts";
16
+ import { managedCompatibleAttempt, openRouterAttempt } from "../../capabilities/model/openrouter-stream.ts";
17
17
  import { currentTimeDefinition, executeCurrentTime } from "../../capabilities/tools/builtin/current-time.ts";
18
18
  import { debugToolDefinitions, debugToolHandlers } from "../../capabilities/tools/debug/index.ts";
19
19
  import { notifyChannelDefinition } from "../../capabilities/tools/builtin/notify-channel.ts";
@@ -21,7 +21,7 @@ import { createMemoryStorageAdapter } from "../../state/storage/memory.ts";
21
21
  import { createSqliteStorageAdapter } from "../../state/storage/sqlite.ts";
22
22
  import { createInspection } from "../inspector/state.ts";
23
23
  import { observeModel, observeSession } from "../inspector/observe.ts";
24
- import type { ManagedConfig } from "../../contracts/config-permissions.ts";
24
+ import { isCompatibleModel, type ManagedConfig } from "../../contracts/config-permissions.ts";
25
25
  import { chooseManagedConfig } from "../../runtime/config/paths.ts";
26
26
  import { resolveCompatibleCredential, resolveCredential, validateManagedConfig } from "../../runtime/config/managed.ts";
27
27
  import { createManagedAttachmentService } from "../../capabilities/attachments/service.ts";
@@ -93,7 +93,7 @@ export async function openDevelopment(options: DevelopmentOptions) {
93
93
  managedConfig = { ...managedConfig, system: options.debugInstructions };
94
94
  const systemPrompt = options.instructions ?? options.debugInstructions ?? managedConfig?.system ?? options.systemPrompt;
95
95
  const scriptPath = managedConfig?.model.protocol === "scripted" ? managedConfig.model.script : undefined;
96
- const compatible = managedConfig?.model.protocol === "openai-compatible" ? managedConfig.model : undefined;
96
+ const compatible = isCompatibleModel(managedConfig?.model) ? managedConfig.model : undefined;
97
97
  const creating = !options.database || !!options.create;
98
98
  const environment = options.environment ?? process.env;
99
99
  let compatibleKey = compatible && creating ? resolveCompatibleCredential(compatible, environment) : undefined;
@@ -105,9 +105,9 @@ export async function openDevelopment(options: DevelopmentOptions) {
105
105
  const scriptedTools = script ? options.scriptedTools : undefined;
106
106
  const tools = [currentTimeDefinition, ...(scriptedTools?.tools ?? []),
107
107
  ...(options.debugTools ? debugToolDefinitions : []), notifyChannelDefinition];
108
- let imageInput = managedConfig?.model.protocol !== "openai-compatible" && managedConfig?.model.imageInput === true && (managedConfig.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
109
- const compatibilityKey = compatible ? compatibleInferenceKey(compatible, systemPrompt, tools.map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, systemPrompt + (managedConfig?.model.protocol !== "openai-compatible" && managedConfig?.model.imageInput === true ? "\n[image-input-enabled]" : ""))
110
- : createHash("sha256").update(JSON.stringify([systemPrompt, providerModel!.model, tools.map(tool => tool.name), ...(managedConfig?.model.protocol !== "openai-compatible" && managedConfig?.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
108
+ let imageInput = !!managedConfig && !isCompatibleModel(managedConfig.model) && managedConfig.model.imageInput === true && (managedConfig.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
109
+ const compatibilityKey = compatible ? compatibleInferenceKey(compatible, systemPrompt, tools.map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, systemPrompt + (managedConfig && !isCompatibleModel(managedConfig.model) && managedConfig.model.imageInput === true ? "\n[image-input-enabled]" : ""))
110
+ : createHash("sha256").update(JSON.stringify([systemPrompt, providerModel!.model, tools.map(tool => tool.name), ...(managedConfig && !isCompatibleModel(managedConfig.model) && managedConfig.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
111
111
  const tempMedia = sqlite ? undefined : mkdtempSync(join(tmpdir(), "harness-media-"));
112
112
  const mediaRoot = options.database ? options.mediaRoot ?? `${options.database}.media` : join(tempMedia!, "media");
113
113
  if (!sqlite) adapter = createMemoryStorageAdapter({ mediaRoot });
@@ -161,7 +161,7 @@ export async function openDevelopment(options: DevelopmentOptions) {
161
161
  };
162
162
  } });
163
163
  } else if (compatible) {
164
- bindModelAttempt(model, { scripted: false, create: () => openAICompatibleAttempt(compatible.baseUrl, compatible.model, compatibleKey, fetch,
164
+ bindModelAttempt(model, { scripted: false, create: () => managedCompatibleAttempt(compatible, { sessionId, channelId: turn.channelId }, compatibleKey,
165
165
  body => inspection.request(turn.channelId, body, turn.turnId), attachments ? id => {
166
166
  const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
167
167
  } : undefined) });
@@ -1,7 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { ManagedModel } from "../../contracts/config-permissions.ts";
2
+ import { OPENCODE_GO_BASE_URL, type CompatibleModel } from "../../contracts/config-permissions.ts";
3
3
 
4
- export function compatibleInferenceKey(model: Extract<ManagedModel, { protocol: "openai-compatible" }>,
4
+ export function compatibleInferenceKey(model: CompatibleModel,
5
5
  system: string, tools: readonly string[]): string {
6
- return createHash("sha256").update(JSON.stringify([model.protocol, model.providerId, model.baseUrl, model.model, system, tools])).digest("hex");
6
+ const source = model.protocol === "opencode-go" ? ["opencode-go", OPENCODE_GO_BASE_URL]
7
+ : [model.protocol, model.providerId, model.baseUrl];
8
+ return createHash("sha256").update(JSON.stringify([...source, model.model, system, tools])).digest("hex");
7
9
  }
@@ -1,3 +1,4 @@
1
+ import { isCompatibleModel } from "./contracts/config-permissions.ts";
1
2
  import { validateMcpRuntimeHeaders } from "./util/mcp-config.ts";
2
3
  import { openMcpRegistry } from "./capabilities/tools/mcp/registry.ts";
3
4
  import { createWebRegistry, directWebFetch } from "./capabilities/tools/web/registry.ts";
@@ -19,7 +20,7 @@ import type { LoadedScenario } from "./contracts/scenario.ts";
19
20
  export type { LoadedScenario, ScenarioHeader, ScenarioModelRecord, ScenarioRecord, ScenarioSend } from "./contracts/scenario.ts";
20
21
  export { loadScenario, parseScenario } from "./capabilities/model/scenario-file.ts";
21
22
  import { bindModelAttempt } from "./capabilities/model/attempt.ts";
22
- import { openAICompatibleAttempt, openRouterAttempt } from "./capabilities/model/openrouter-stream.ts";
23
+ import { managedCompatibleAttempt, openRouterAttempt } from "./capabilities/model/openrouter-stream.ts";
23
24
  import { openRouter } from "./capabilities/model/openrouter.ts";
24
25
  import { notifyChannelDefinition } from "./capabilities/tools/builtin/notify-channel.ts";
25
26
  import { echoDefinition, executeEcho } from "./capabilities/tools/testing/echo.ts";
@@ -143,13 +144,13 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
143
144
  const runtimeHeaders = mcpRuntimeHeaders === undefined ? undefined : validateMcpRuntimeHeaders(mcpRuntimeHeaders, config.mcpServers);
144
145
  const script = config.model.protocol === "scripted" ? await (options.scenarioLoader ?? loadScenario)(config.model.script) : undefined;
145
146
  const credential = config.model.protocol === "openrouter" ? resolveCredential(config.model, options.environment ?? process.env) : undefined;
146
- let imageInput = !!paths && !options.adapter && config.model.protocol !== "openai-compatible" && config.model.imageInput === true && (config.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
147
- const compatible = config.model.protocol === "openai-compatible" ? config.model : undefined;
147
+ let imageInput = !!paths && !options.adapter && !isCompatibleModel(config.model) && config.model.imageInput === true && (config.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
148
+ const compatible = isCompatibleModel(config.model) ? config.model : undefined;
148
149
  const environment = options.environment ?? process.env;
149
150
  let compatibleKey = compatible && mode === "create" ? resolveCompatibleCredential(compatible, environment) : undefined;
150
- const compatibilityKey = compatible ? compatibleInferenceKey(compatible, config.system, [...BUILTINS, notifyChannelDefinition].map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, config.system + (config.model.protocol !== "openai-compatible" && config.model.imageInput === true ? "\n[image-input-enabled]" : ""))
151
+ const compatibilityKey = compatible ? compatibleInferenceKey(compatible, config.system, [...BUILTINS, notifyChannelDefinition].map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, config.system + (!isCompatibleModel(config.model) && config.model.imageInput === true ? "\n[image-input-enabled]" : ""))
151
152
  : createHash("sha256").update(JSON.stringify([config.system, config.model.protocol === "openrouter" && config.model.model,
152
- [...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(config.model.protocol !== "openai-compatible" && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
153
+ [...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(!isCompatibleModel(config.model) && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
153
154
  if (mode === "create" && paths) mkdirSync(paths.directory, { recursive: true });
154
155
  const makeWebTools = () => {
155
156
  const result = createWebRegistry(config, environment, { exa: options.webTransport ?? webFixture ?? exaHttpsTransport, http: options.webHttp ?? directWebFetch });
@@ -196,7 +197,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
196
197
  const model: Model = async () => { throw new Error("Chat Completions requires a model attempt"); };
197
198
  bindModelAttempt(model, { scripted: false,
198
199
  ...(options.modelTimeoutMs === undefined ? {} : { settings: { timeoutMs: options.modelTimeoutMs } }),
199
- create: () => openAICompatibleAttempt(compatible.baseUrl, compatible.model, compatibleKey, fetch, undefined, attachments ? id => {
200
+ create: () => managedCompatibleAttempt(compatible, { sessionId, channelId: turn.channelId }, compatibleKey, undefined, attachments ? id => {
200
201
  const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
201
202
  } : undefined) });
202
203
  return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
@@ -1,6 +1,6 @@
1
1
  import { validateMcpServers } from "./mcp-config.ts";
2
2
  import { validateWebConfig } from "./web-config.ts";
3
- import type { ManagedConfig, ModelContextBudget, ToolDecision, ToolPolicy } from "../contracts/config-permissions.ts";
3
+ import { OPENCODE_GO_KEY_ENV, type CompatibleModel, type ManagedConfig, type ModelContextBudget, type ToolDecision, type ToolPolicy } from "../contracts/config-permissions.ts";
4
4
  import { effectiveContextBudget, MAX_MODEL_REQUEST_BYTES } from "./context-budget.ts";
5
5
 
6
6
  /** The upgrade preserves the behavior of sessions created before policies existed. */
@@ -76,7 +76,12 @@ export function validateManagedConfig(input: unknown, legacy = false): ManagedCo
76
76
  if (reference !== undefined && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) fail("config.model.apiKeyEnv", "expected an environment variable name");
77
77
  selectedModel = { protocol: "openai-compatible", providerId: name(model.providerId, "config.model.providerId"),
78
78
  model: name(model.model, "config.model.model"), baseUrl: baseUrl(model.baseUrl), ...(reference === undefined ? {} : { apiKeyEnv: reference }), ...modelContextBudget(model.contextBudget) };
79
- } else return fail("config.model.protocol", "expected scripted, openrouter or openai-compatible");
79
+ } else if (model.protocol === "opencode-go") {
80
+ keys(model, ["protocol", "model", "apiKeyEnv", "contextBudget"], "config.model");
81
+ const reference = model.apiKeyEnv === undefined ? OPENCODE_GO_KEY_ENV : name(model.apiKeyEnv, "config.model.apiKeyEnv");
82
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) return fail("config.model.apiKeyEnv", "expected an environment variable name");
83
+ selectedModel = { protocol: "opencode-go", model: name(model.model, "config.model.model"), apiKeyEnv: reference, ...modelContextBudget(model.contextBudget) };
84
+ } else return fail("config.model.protocol", "expected scripted, openrouter, openai-compatible or opencode-go");
80
85
  const isLegacy = legacy && raw.defaultPolicy === undefined && raw.policies === undefined;
81
86
  const defaultPolicy = isLegacy ? LEGACY_POLICY : name(raw.defaultPolicy, "config.defaultPolicy");
82
87
  const policiesInput = isLegacy ? { [LEGACY_POLICY]: { fallback: "allow", tools: {} } } : record(raw.policies, "config.policies");
@@ -123,10 +128,11 @@ export function resolveCredential(model: Extract<ManagedConfig["model"], { proto
123
128
  }
124
129
 
125
130
 
126
- export function resolveCompatibleCredential(model: Extract<ManagedConfig["model"], { protocol: "openai-compatible" }>,
131
+ export function resolveCompatibleCredential(model: CompatibleModel,
127
132
  environment: Record<string, string | undefined>): string | undefined {
128
- if (model.apiKeyEnv === undefined) return;
129
- const value = environment[model.apiKeyEnv];
133
+ const reference = model.apiKeyEnv ?? (model.protocol === "opencode-go" ? OPENCODE_GO_KEY_ENV : undefined);
134
+ if (reference === undefined) return;
135
+ const value = environment[reference];
130
136
  if (!value?.trim() || /[\r\n]/.test(value)) return fail("config.model.apiKeyEnv", "configured credential is missing, empty or invalid");
131
137
  return value;
132
138
  }