@qlairoslabs/acp-client 0.13.4-alpha.1 → 0.13.6-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 +37 -2
- package/package.json +1 -1
- package/src/native/controller.ts +4 -2
- package/src/native-harness/src/capabilities/model/attempt.ts +2 -2
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +58 -24
- package/src/native-harness/src/capabilities/model/runner.ts +55 -11
- package/src/native-harness/src/contracts/config-permissions.ts +10 -1
- package/src/native-harness/src/contracts/model-execution.ts +5 -1
- package/src/native-harness/src/index.ts +4 -2
- package/src/native-harness/src/interfaces/cli/development.ts +7 -7
- package/src/native-harness/src/kernel/channels.ts +2 -1
- package/src/native-harness/src/runtime/config/inference-key.ts +5 -3
- package/src/native-harness/src/testing.ts +7 -6
- package/src/native-harness/src/util/config.ts +11 -5
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-
|
|
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
|
-
|
|
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
|
|
@@ -1231,6 +1247,25 @@ A failed turn reports `context_limit` and leaves the channel usable. The
|
|
|
1231
1247
|
underlying `NativeTurnError.contextFailure` gives the applicable limit and,
|
|
1232
1248
|
for local token and byte limits, the measured budget.
|
|
1233
1249
|
|
|
1250
|
+
When a native inference attempt fails, the prompt rejection and
|
|
1251
|
+
`turn_failed` event include the harness diagnostic. A metered conversation
|
|
1252
|
+
rejects with `AgentSessionOperationError` whose `cause` is a
|
|
1253
|
+
`NativeTurnError`. Both errors carry the same message, for example
|
|
1254
|
+
`native turn 1 failed: Chat Completions HTTP 429`. Use
|
|
1255
|
+
`NativeTurnError.outcome` for the turn classification. `"interrupted"`
|
|
1256
|
+
records an external interruption. A provider deadline leaves the turn
|
|
1257
|
+
`"failed"` and records `"timeout"` on the model call.
|
|
1258
|
+
|
|
1259
|
+
Provider diagnostics identify HTTP status where available, for example
|
|
1260
|
+
`Chat Completions HTTP 429` or `OpenRouter HTTP 500`. Other diagnostics
|
|
1261
|
+
identify a transport failure, refused redirect, invalid response,
|
|
1262
|
+
configuration error, or model request deadline. The harness uses fixed
|
|
1263
|
+
fallback wording when it has no validated provider detail. Remote
|
|
1264
|
+
response bodies, headers and URLs are excluded from these failure
|
|
1265
|
+
diagnostics. Reconciliation preserves the recorded reason, and the next
|
|
1266
|
+
prompt can run when the provider recovers.
|
|
1267
|
+
|
|
1268
|
+
|
|
1234
1269
|
```ts
|
|
1235
1270
|
import { NativeInputStoppedError, type Agent, type ItemsReceipt } from "@qlairoslabs/acp-client";
|
|
1236
1271
|
|
package/package.json
CHANGED
package/src/native/controller.ts
CHANGED
|
@@ -504,8 +504,10 @@ export class NativeController implements ConversationController, ChannelPort {
|
|
|
504
504
|
} else if (event.outcome === "interrupted" && turn.cancelRequested) {
|
|
505
505
|
cancelled(true);
|
|
506
506
|
} else {
|
|
507
|
-
const
|
|
508
|
-
|
|
507
|
+
const prefix = `${event.outcome}: `;
|
|
508
|
+
const reason = event.error?.startsWith(prefix) ? event.error.slice(prefix.length) : event.error;
|
|
509
|
+
const detail = reason && reason !== event.outcome ? `: ${reason}` : "";
|
|
510
|
+
finish(() => reject(new NativeTurnError(event.outcome as "failed" | "interrupted", `native turn ${turn.harnessId} ${event.outcome}${detail}`,
|
|
509
511
|
event.uncertainCalls, event.contextFailure)), true);
|
|
510
512
|
}
|
|
511
513
|
return;
|
|
@@ -9,8 +9,8 @@ export function completeModelAttempt(model: Model): ModelAttempt {
|
|
|
9
9
|
const answer = await model(request.messages, request.tools, signal);
|
|
10
10
|
if (signal.aborted) return;
|
|
11
11
|
yield { type: "response", response: { ...answer, stopReason: answer.calls.length ? "tool_calls" : "complete" } };
|
|
12
|
-
} catch
|
|
13
|
-
if (!signal.aborted) yield { type: "failure", kind: "provider", message:
|
|
12
|
+
} catch {
|
|
13
|
+
if (!signal.aborted) yield { type: "failure", kind: "provider", message: "Model provider failed" };
|
|
14
14
|
}
|
|
15
15
|
};
|
|
16
16
|
}
|
|
@@ -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
|
|
20
|
-
if (!response.body) return
|
|
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
|
|
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
|
|
31
|
-
} catch { return
|
|
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);
|
|
62
|
+
}
|
|
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";
|
|
45
71
|
}
|
|
46
|
-
|
|
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;
|
|
@@ -105,29 +133,35 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
|
|
|
105
133
|
for (const url of imageUrls) { safe = safe.replaceAll(url, "[REDACTED_IMAGE]"); const encoded = url.slice(url.indexOf(",") + 1); if (encoded) safe = safe.replaceAll(encoded, "[REDACTED_IMAGE]"); }
|
|
106
134
|
return safe;
|
|
107
135
|
};
|
|
108
|
-
const
|
|
136
|
+
const diagnosticProvider = endpoint ? "chat_completions" as const : "openrouter" as const;
|
|
137
|
+
const errorText = () => endpoint ? "Chat Completions transport failed" : "OpenRouter transport failed";
|
|
109
138
|
onRequest?.(imageUrls.length ? redact(body) : body);
|
|
110
139
|
let response: Response;
|
|
111
|
-
try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: {
|
|
112
|
-
|
|
140
|
+
try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: {
|
|
141
|
+
...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json",
|
|
142
|
+
...(goSession ? { "User-Agent": "acp-client/native-harness", "x-opencode-session": goSession } : {}),
|
|
143
|
+
}, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
|
|
144
|
+
catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(), diagnostic: { provider: diagnosticProvider, category: "transport" } }; return; }
|
|
113
145
|
if (!response.ok) {
|
|
114
146
|
if (endpoint) {
|
|
115
147
|
if (response.status >= 300 && response.status < 400) {
|
|
116
148
|
void response.body?.cancel().catch(() => {});
|
|
117
|
-
yield { type: "failure", kind: "provider", message: "redirect_refused" }
|
|
149
|
+
yield { type: "failure", kind: "provider", message: "redirect_refused", diagnostic: { provider: diagnosticProvider, category: "redirect" },
|
|
150
|
+
...(goSession ? { providerFailure: `OpenCode Go HTTP ${response.status} (redirect_refused)` } : {}) }; return;
|
|
118
151
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
152
|
+
const upstream = await readErrorBody(response);
|
|
153
|
+
if (isProviderContextError(upstream)) { yield providerContextFailure; return; }
|
|
154
|
+
if (goSession) {
|
|
155
|
+
const code = goFailureCode(response.status, upstream);
|
|
156
|
+
const message = `OpenCode Go HTTP ${response.status}${code ? ` (${code})` : ""}`;
|
|
157
|
+
yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message, providerFailure: message };
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}`, diagnostic: { provider: diagnosticProvider, category: "http", status: response.status } }; return;
|
|
126
161
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `OpenRouter HTTP ${response.status}: ${text}` }; return;
|
|
162
|
+
if (isProviderContextError(await readErrorBody(response))) { yield providerContextFailure; return; }
|
|
163
|
+
yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request",
|
|
164
|
+
message: `OpenRouter HTTP ${response.status}`, diagnostic: { provider: diagnosticProvider, category: "http", status: response.status } }; return;
|
|
131
165
|
}
|
|
132
166
|
const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
|
|
133
167
|
const requestId = safeRequestId(response.headers.get("x-request-id") ?? undefined);
|
|
@@ -170,14 +204,14 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
|
|
|
170
204
|
const ordered = [...fragments.entries()].sort((a, b) => a[0] - b[0]);
|
|
171
205
|
if (ordered.some(([n], i) => n !== i)) { yield { type: "failure", kind: "provider", message: "Non-contiguous tool fragments" }; return; }
|
|
172
206
|
const stopReason = stop === "stop" ? "complete" : stop === "tool_calls" ? "tool_calls" : stop === "length" ? "output_limit" : undefined;
|
|
173
|
-
if (!stopReason) { yield { type: "failure", kind: "provider", message: endpoint ? "Unsupported Chat Completions finish reason" :
|
|
207
|
+
if (!stopReason) { yield { type: "failure", kind: "provider", message: endpoint ? "Unsupported Chat Completions finish reason" : "Unsupported OpenRouter finish reason" }; return; }
|
|
174
208
|
const calls = ordered.map(([, value]) => value);
|
|
175
209
|
const message = { role: "assistant" as const, content: content || null, calls };
|
|
176
210
|
const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, ...(endpoint ? {} : { providerState: { role: "assistant", content: message.content,
|
|
177
211
|
...(reasoning ? { reasoning } : {}), ...(reasoningDetails.length ? { reasoning_details: reasoningDetails } : {}),
|
|
178
212
|
...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
|
|
179
213
|
yield event;
|
|
180
|
-
} catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(
|
|
214
|
+
} catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(), diagnostic: { provider: diagnosticProvider, category: "transport" } }; }
|
|
181
215
|
finally { if (endpoint || profile) void reader.cancel().catch(() => {}); reader.releaseLock(); }
|
|
182
216
|
};
|
|
183
217
|
}
|
|
@@ -1,13 +1,40 @@
|
|
|
1
|
+
import { parseContextLimitFailure } from "../../contracts/context.ts";
|
|
1
2
|
import type { ModelAttempt, ModelAttemptEvent, ModelCallStore, ModelExecutionSettings, ModelRequest, ModelResponse, CallOutcome } from "../../contracts/model-execution.ts";
|
|
2
3
|
import type { StorageResult, TimelineEntry } from "../../contracts/storage.ts";
|
|
3
4
|
|
|
4
5
|
/** One deadline covers the first attempt, retry wait and retry. */
|
|
5
6
|
export const MODEL_EXECUTION_DEFAULTS: Readonly<ModelExecutionSettings> = { timeoutMs: 120_000, retryDelayMs: 1_000, maxRetries: 1 };
|
|
6
7
|
export class ModelCallError extends Error {
|
|
8
|
+
readonly turnFailureDetail?: string;
|
|
7
9
|
constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string,
|
|
8
10
|
readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
|
|
9
|
-
readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure
|
|
11
|
+
readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
|
|
12
|
+
readonly providerFailure?: string) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "ModelCallError";
|
|
15
|
+
const detail = Array.from(message.replace(/[\p{Cc}\p{Cf}]/gu, " ").trim().slice(0, 480)).slice(0, 240).join("");
|
|
16
|
+
if (!providerFailure && detail && detail !== outcome) this.turnFailureDetail = detail;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function safeDiagnostic(event: Extract<ModelAttemptEvent, { type: "failure" }>): string {
|
|
20
|
+
const diagnostic = event.diagnostic;
|
|
21
|
+
const provider = diagnostic?.provider === "openrouter" ? "OpenRouter"
|
|
22
|
+
: diagnostic?.provider === "chat_completions" ? "Chat Completions" : undefined;
|
|
23
|
+
if (provider && diagnostic) {
|
|
24
|
+
if (diagnostic.category === "http" && Number.isInteger(diagnostic.status) && diagnostic.status >= 400 && diagnostic.status <= 599)
|
|
25
|
+
return `${provider} HTTP ${diagnostic.status}`;
|
|
26
|
+
if (diagnostic.category === "transport") return `${provider} transport failed`;
|
|
27
|
+
if (diagnostic.category === "redirect") return `${provider} redirect refused`;
|
|
28
|
+
if (diagnostic.category === "protocol") return `${provider} returned an invalid response`;
|
|
29
|
+
}
|
|
30
|
+
switch (event.kind) {
|
|
31
|
+
case "transient": return "Temporary model provider failure";
|
|
32
|
+
case "invalid_request": return "Model provider rejected the request";
|
|
33
|
+
case "invalid_config": return "Model provider configuration failed";
|
|
34
|
+
default: return "Model provider failed";
|
|
35
|
+
}
|
|
10
36
|
}
|
|
37
|
+
|
|
11
38
|
class ModelStorageError extends Error {}
|
|
12
39
|
function take<T>(result: StorageResult<T>): T {
|
|
13
40
|
if (!result.ok) throw new ModelStorageError(`Model call storage ${result.error.code}: ${result.error.message}`);
|
|
@@ -44,11 +71,12 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
44
71
|
let deadline = 0, output = false;
|
|
45
72
|
const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome,
|
|
46
73
|
attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
|
|
47
|
-
contextFailure?: import("../../contracts/context.ts").ContextLimitFailure
|
|
74
|
+
contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
|
|
75
|
+
providerFailure?: string): never => {
|
|
48
76
|
const result = options.store.finishCall(call.callId, outcome);
|
|
49
77
|
if (!result.ok && !(outcome === "interrupted" && result.error.code === "invalid_state")) take(result);
|
|
50
78
|
if (output) options.incomplete?.({ messageId: call.messageId, reason: outcome });
|
|
51
|
-
throw new ModelCallError(outcome, detail, attachmentFailure, contextFailure);
|
|
79
|
+
throw new ModelCallError(outcome, detail, attachmentFailure, contextFailure, providerFailure);
|
|
52
80
|
};
|
|
53
81
|
for (let ordinal = 0; ordinal <= Math.min(1, settings.maxRetries); ordinal++) {
|
|
54
82
|
if (options.signal?.aborted) return finish("interrupted");
|
|
@@ -79,7 +107,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
79
107
|
if (event.type === "text_delta") { output = true; options.delta?.({ messageId: call.messageId, text: event.text }); }
|
|
80
108
|
} else if (event.type === "usage") take(options.store.recordUsage(call.callId, attempt.attemptId, event.usage));
|
|
81
109
|
}
|
|
82
|
-
} catch (error) { if (error instanceof ModelStorageError) throw error; terminal = { type: "failure", kind: "provider", message:
|
|
110
|
+
} catch (error) { if (error instanceof ModelStorageError) throw error; terminal = { type: "failure", kind: "provider", message: "Model attempt failed unexpectedly" }; }
|
|
83
111
|
finally { clearTimeout(timer); options.signal?.removeEventListener("abort", abort); controller.abort(); }
|
|
84
112
|
if (options.signal?.aborted || cancellation === "interrupted") {
|
|
85
113
|
// The lifecycle transaction may already have ended this call. In that
|
|
@@ -89,11 +117,11 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
89
117
|
take(ended); return finish("interrupted");
|
|
90
118
|
}
|
|
91
119
|
if (Date.now() >= deadline || cancellation === "timeout") {
|
|
92
|
-
take(options.store.finishAttempt(call.callId, attempt.attemptId, "timeout")); return finish("timeout");
|
|
120
|
+
take(options.store.finishAttempt(call.callId, attempt.attemptId, "timeout")); return finish("timeout", "Model request deadline exceeded");
|
|
93
121
|
}
|
|
94
122
|
if (terminal?.type === "response") {
|
|
95
123
|
if (terminal.providerRequestId) take(options.store.recordProviderRequestId(call.callId, attempt.attemptId, terminal.providerRequestId));
|
|
96
|
-
if (!validResponse(terminal.response)) { take(options.store.finishAttempt(call.callId, attempt.attemptId, "invalid_request")); return finish("failed"); }
|
|
124
|
+
if (!validResponse(terminal.response)) { take(options.store.finishAttempt(call.callId, attempt.attemptId, "invalid_request")); return finish("failed", "Invalid model response"); }
|
|
97
125
|
const result = options.store.confirm(call.callId, attempt.attemptId, "seen"); const items = take(result); if (result.ok && items.length) options.receipt?.("seen", items, result.revision);
|
|
98
126
|
if (terminal.response.stopReason === "output_limit") { take(options.store.finishAttempt(call.callId, attempt.attemptId, "output_limit")); return finish("output_limit"); }
|
|
99
127
|
const committed = options.store.commitResponse(call.callId, attempt.attemptId, terminal.response, terminal.providerRequestId);
|
|
@@ -106,17 +134,33 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
106
134
|
const attemptOutcome = failure === "transient" ? "transient_failure" : failure === "provider" ? "provider_failure" : failure;
|
|
107
135
|
take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
|
|
108
136
|
if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
|
|
109
|
-
if (terminal?.type === "failure" && terminal.code
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
137
|
+
if (terminal?.type === "failure" && (terminal.code === "unsupported_image" || terminal.code === "attachment_unavailable" || terminal.code === "transfer_limit")) {
|
|
138
|
+
const ids = new Set(request.messages.flatMap(message => "parts" in message
|
|
139
|
+
? (message.parts ?? []).flatMap(part => part.type === "attachment" ? [part.id] : []) : []));
|
|
140
|
+
return finish("failed", "Model attachment rejected", { code: terminal.code,
|
|
141
|
+
attachmentIds: [...new Set((terminal.attachmentIds ?? []).filter(id => ids.has(id)))] });
|
|
142
|
+
}
|
|
143
|
+
if (terminal?.type === "failure" && terminal.contextFailure) {
|
|
144
|
+
const context = parseContextLimitFailure(`context_limit:${JSON.stringify(terminal.contextFailure)}`);
|
|
145
|
+
if (context) return finish("failed", "Model context limit exceeded", undefined, context);
|
|
146
|
+
}
|
|
147
|
+
if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) {
|
|
148
|
+
const candidate = terminal?.type === "failure" ? terminal.providerFailure : undefined;
|
|
149
|
+
const providerFailure = typeof candidate === "string" &&
|
|
150
|
+
/^OpenCode Go HTTP (?:[45][0-9]{2}(?: \((?:missing_session_id|invalid_api_key|access_denied|rate_limited)\))?|3[0-9]{2} \(redirect_refused\))$/.test(candidate)
|
|
151
|
+
? candidate : undefined;
|
|
152
|
+
return finish(failure === "incomplete" ? "incomplete" : "failed",
|
|
153
|
+
providerFailure ?? (terminal?.type === "failure" ? safeDiagnostic(terminal) : "Model response ended before completion"),
|
|
154
|
+
undefined, undefined, providerFailure);
|
|
155
|
+
}
|
|
156
|
+
if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout", "Model request deadline exceeded");
|
|
113
157
|
const delay = await new Promise<"ready" | "interrupted">(resolve => {
|
|
114
158
|
const done = (result: "ready" | "interrupted") => { clearTimeout(wait); options.signal?.removeEventListener("abort", interrupted); resolve(result); };
|
|
115
159
|
const interrupted = () => done("interrupted"); const wait = setTimeout(() => done("ready"), settings.retryDelayMs);
|
|
116
160
|
options.signal?.addEventListener("abort", interrupted, { once: true }); if (options.signal?.aborted) interrupted();
|
|
117
161
|
});
|
|
118
162
|
if (delay === "interrupted") return finish("interrupted");
|
|
119
|
-
if (Date.now() >= deadline) return finish("timeout");
|
|
163
|
+
if (Date.now() >= deadline) return finish("timeout", "Model request deadline exceeded");
|
|
120
164
|
}
|
|
121
165
|
return finish("failed");
|
|
122
166
|
}
|
|
@@ -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,11 @@ 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
|
+
providerFailure?: string;
|
|
38
|
+
/** Only validated provider/category/status values may enter durable diagnostics. */
|
|
39
|
+
diagnostic?: { provider: "openrouter" | "chat_completions"; category: "http"; status: number }
|
|
40
|
+
| { provider: "openrouter" | "chat_completions"; category: "transport" | "redirect" | "protocol" } };
|
|
37
41
|
/** One attempt emits exactly one terminal response or failure unless aborted;
|
|
38
42
|
* EOF without a terminal is incomplete. A consumer ignores events after the
|
|
39
43
|
* 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
|
|
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
|
|
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 {
|
|
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
|
|
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
|
|
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
|
|
109
|
-
const compatibilityKey = compatible ? compatibleInferenceKey(compatible, systemPrompt, tools.map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, systemPrompt + (managedConfig
|
|
110
|
-
: createHash("sha256").update(JSON.stringify([systemPrompt, providerModel!.model, tools.map(tool => tool.name), ...(managedConfig
|
|
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: () =>
|
|
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) });
|
|
@@ -188,7 +188,8 @@ export function createChannelScheduler(
|
|
|
188
188
|
// Record the failure unless stop already ended the turn; either way the
|
|
189
189
|
// channel stays usable.
|
|
190
190
|
const attachmentFailure = error && typeof error === "object" && "attachmentFailure" in error ? error.attachmentFailure as import("../contracts/attachments.ts").AttachmentFailure | undefined : undefined;
|
|
191
|
-
const outcome = attachmentFailure ? attachmentFailureReason(attachmentFailure) : error && typeof error === "object" && "outcome" in error && typeof error.outcome === "string" ? error.outcome :
|
|
191
|
+
const outcome = attachmentFailure ? attachmentFailureReason(attachmentFailure) : error && typeof error === "object" && "outcome" in error && typeof error.outcome === "string" ? ("turnFailureDetail" in error && typeof error.turnFailureDetail === "string" ? `${error.outcome}: ${error.turnFailureDetail}` : error.outcome)
|
|
192
|
+
: String(error);
|
|
192
193
|
const failed = storage.finishTurn(turnId, { status: "failed", reason: outcome });
|
|
193
194
|
release();
|
|
194
195
|
if (failed.ok && failed.value.finished) { ended(failed.value.turn, failed.revision); settleChannel(channelId, failed.revision); }
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import type
|
|
2
|
+
import { OPENCODE_GO_BASE_URL, type CompatibleModel } from "../../contracts/config-permissions.ts";
|
|
3
3
|
|
|
4
|
-
export function compatibleInferenceKey(model:
|
|
4
|
+
export function compatibleInferenceKey(model: CompatibleModel,
|
|
5
5
|
system: string, tools: readonly string[]): string {
|
|
6
|
-
|
|
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 {
|
|
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
|
|
147
|
-
const compatible = config.model
|
|
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
|
|
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
|
|
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: () =>
|
|
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
|
|
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
|
|
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:
|
|
131
|
+
export function resolveCompatibleCredential(model: CompatibleModel,
|
|
127
132
|
environment: Record<string, string | undefined>): string | undefined {
|
|
128
|
-
|
|
129
|
-
|
|
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
|
}
|