@qlairoslabs/acp-client 0.13.5-alpha.1 → 0.13.7-e-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 +29 -0
- package/package.json +1 -1
- package/src/agent/config.ts +1 -0
- package/src/index.ts +1 -0
- package/src/native/connection.ts +1 -1
- package/src/native/controller.ts +4 -2
- package/src/native/host-config.ts +1 -0
- package/src/native/inference-relay.ts +35 -0
- package/src/native/recovery.ts +5 -4
- package/src/native-harness/src/capabilities/model/attempt.ts +2 -2
- package/src/native-harness/src/capabilities/model/inference-relay.ts +65 -0
- package/src/native-harness/src/capabilities/model/openrouter-stream.ts +10 -15
- package/src/native-harness/src/capabilities/model/runner.ts +50 -10
- package/src/native-harness/src/client.ts +1 -0
- package/src/native-harness/src/contracts/config-permissions.ts +1 -1
- package/src/native-harness/src/contracts/model-execution.ts +4 -3
- package/src/native-harness/src/contracts/operator-controls.ts +1 -0
- package/src/native-harness/src/contracts/protocol.ts +3 -0
- package/src/native-harness/src/contracts/storage.ts +3 -0
- package/src/native-harness/src/interfaces/protocol/server.ts +6 -6
- package/src/native-harness/src/kernel/channels.ts +2 -1
- package/src/native-harness/src/runtime/config/inference-key.ts +1 -1
- package/src/native-harness/src/state/storage/memory.ts +2 -0
- package/src/native-harness/src/state/storage/sqlite.ts +4 -0
- package/src/native-harness/src/testing.ts +23 -7
- package/src/native-harness/src/util/config.ts +16 -5
- package/src/native-harness/src/util/inference-relay.ts +46 -0
package/CONSUMER_GUIDE.md
CHANGED
|
@@ -1233,6 +1233,16 @@ The preset sends a stable routing header per channel and uses Go's Chat
|
|
|
1233
1233
|
Completions endpoint. DeepSeek V4.1 Flash may require allowing the Global
|
|
1234
1234
|
region in the Go workspace. [OpenCode Go model settings](https://opencode.ai/docs/console/go/#enable-restricted-models)
|
|
1235
1235
|
|
|
1236
|
+
For an operator-managed native inference relay, declare
|
|
1237
|
+
`credentialMode: "relay"` on the `openai-compatible` model and set its
|
|
1238
|
+
`baseUrl` to the exact relay URL. Omit `apiKeyEnv`. Supply a trusted
|
|
1239
|
+
`harness.inferenceRelayGrant` callback. On each executable create or reopen
|
|
1240
|
+
it receives `{ sessionId, signal }` and returns
|
|
1241
|
+
`{ baseUrl, bearerToken, expiresAtMs }` for that session. Use a short-lived
|
|
1242
|
+
relay credential and keep upstream provider keys on the relay side. Prefer
|
|
1243
|
+
HTTPS. The native control connection must be trusted, and plaintext requires
|
|
1244
|
+
an isolated hop.
|
|
1245
|
+
|
|
1236
1246
|
Set `harness.config.model.contextBudget` on OpenRouter, OpenCode Go or OpenAI-compatible models
|
|
1237
1247
|
to fit a larger inference request. For example, a model with a 128,000-token
|
|
1238
1248
|
window can use `contextBudget: { contextWindowTokens: 128_000, outputReserveTokens: 4096 }`.
|
|
@@ -1247,6 +1257,25 @@ A failed turn reports `context_limit` and leaves the channel usable. The
|
|
|
1247
1257
|
underlying `NativeTurnError.contextFailure` gives the applicable limit and,
|
|
1248
1258
|
for local token and byte limits, the measured budget.
|
|
1249
1259
|
|
|
1260
|
+
When a native inference attempt fails, the prompt rejection and
|
|
1261
|
+
`turn_failed` event include the harness diagnostic. A metered conversation
|
|
1262
|
+
rejects with `AgentSessionOperationError` whose `cause` is a
|
|
1263
|
+
`NativeTurnError`. Both errors carry the same message, for example
|
|
1264
|
+
`native turn 1 failed: Chat Completions HTTP 429`. Use
|
|
1265
|
+
`NativeTurnError.outcome` for the turn classification. `"interrupted"`
|
|
1266
|
+
records an external interruption. A provider deadline leaves the turn
|
|
1267
|
+
`"failed"` and records `"timeout"` on the model call.
|
|
1268
|
+
|
|
1269
|
+
Provider diagnostics identify HTTP status where available, for example
|
|
1270
|
+
`Chat Completions HTTP 429` or `OpenRouter HTTP 500`. Other diagnostics
|
|
1271
|
+
identify a transport failure, refused redirect, invalid response,
|
|
1272
|
+
configuration error, or model request deadline. The harness uses fixed
|
|
1273
|
+
fallback wording when it has no validated provider detail. Remote
|
|
1274
|
+
response bodies, headers and URLs are excluded from these failure
|
|
1275
|
+
diagnostics. Reconciliation preserves the recorded reason, and the next
|
|
1276
|
+
prompt can run when the provider recovers.
|
|
1277
|
+
|
|
1278
|
+
|
|
1250
1279
|
```ts
|
|
1251
1280
|
import { NativeInputStoppedError, type Agent, type ItemsReceipt } from "@qlairoslabs/acp-client";
|
|
1252
1281
|
|
package/package.json
CHANGED
package/src/agent/config.ts
CHANGED
|
@@ -117,6 +117,7 @@ export interface AgentHarnessConfig {
|
|
|
117
117
|
/** The harness configuration, sent on every open. */
|
|
118
118
|
readonly config: import("../native/reminders/routine-wire.ts").RoutineConfigInput;
|
|
119
119
|
/** Fresh secret material for each executable native harness open. */
|
|
120
|
+
readonly inferenceRelayGrant?: import("../native/inference-relay.ts").InferenceRelayGrantProvider;
|
|
120
121
|
readonly mcpRuntimeHeaders?: import("../native/mcp.ts").McpRuntimeHeadersProvider;
|
|
121
122
|
/** The harness home, a path in the harness's environment. It must survive process restarts. */
|
|
122
123
|
readonly home: string;
|
package/src/index.ts
CHANGED
|
@@ -806,4 +806,5 @@ export type { ReminderErrorCode, ReminderSchedule, ReminderScheduleInput } from
|
|
|
806
806
|
export type { Reminder } from "./persistence/reminders.ts";
|
|
807
807
|
export type { ReminderCreate, ReminderEdit, ReminderView, ReminderEvent } from "./native/reminders/service.ts";
|
|
808
808
|
|
|
809
|
+
export type { InferenceRelayGrant, InferenceRelayGrantProvider } from "./native/inference-relay.ts";
|
|
809
810
|
export type { McpRuntimeHeaders, McpRuntimeHeadersProvider, NativeInputPolicy, NativeMcpStatus } from "./native/mcp.ts";
|
package/src/native/connection.ts
CHANGED
|
@@ -30,7 +30,7 @@ export async function launchNativeConnection(config: NativeHarnessHostConfig, lo
|
|
|
30
30
|
void (async () => {
|
|
31
31
|
// Diagnostics only: the protocol is on stdout.
|
|
32
32
|
const text = await new Response(child.stderr).text().catch(() => "");
|
|
33
|
-
if (text.trim()) log.warn("native_harness_stderr", config.mcpRuntimeHeaders ? { redacted: true } : { text: text.slice(-4000) });
|
|
33
|
+
if (text.trim()) log.warn("native_harness_stderr", (config.mcpRuntimeHeaders || config.inferenceRelayGrant) ? { redacted: true } : { text: text.slice(-4000) });
|
|
34
34
|
})();
|
|
35
35
|
let notify: (event: ReminderNotification) => void = () => {};
|
|
36
36
|
const transport = createStdioTransport({
|
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;
|
|
@@ -30,6 +30,7 @@ export interface NativeHarnessHostConfig {
|
|
|
30
30
|
/** Sent on every open. Session configuration is fixed while the session is open. */
|
|
31
31
|
readonly config: RoutineConfigInput;
|
|
32
32
|
/** Fresh secret material for each executable native harness open. */
|
|
33
|
+
readonly inferenceRelayGrant?: import("./inference-relay.ts").InferenceRelayGrantProvider;
|
|
33
34
|
readonly mcpRuntimeHeaders?: import("./mcp.ts").McpRuntimeHeadersProvider;
|
|
34
35
|
/** The harness home, a path in the harness's environment. Must survive process restarts. */
|
|
35
36
|
readonly home: string;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { HarnessClientError, type InferenceRelayGrant } from "../native-harness/src/client.ts";
|
|
2
|
+
import { codeOf } from "./errors.ts";
|
|
3
|
+
|
|
4
|
+
export type { InferenceRelayGrant } from "../native-harness/src/client.ts";
|
|
5
|
+
|
|
6
|
+
/** Trusted host hook. Return fresh runtime authority for this executable open. */
|
|
7
|
+
export type InferenceRelayGrantProvider = (context: { sessionId: string; signal: AbortSignal }) =>
|
|
8
|
+
InferenceRelayGrant | undefined | Promise<InferenceRelayGrant | undefined>;
|
|
9
|
+
|
|
10
|
+
export async function executableRelayOpen<T>(provider: InferenceRelayGrantProvider | undefined,
|
|
11
|
+
sessionId: string, signal: AbortSignal, send: (grant?: InferenceRelayGrant) => Promise<T>): Promise<T> {
|
|
12
|
+
if (!provider) return send();
|
|
13
|
+
signal.throwIfAborted();
|
|
14
|
+
let grant: InferenceRelayGrant | undefined;
|
|
15
|
+
try { grant = await provider({ sessionId, signal }); }
|
|
16
|
+
catch {
|
|
17
|
+
signal.throwIfAborted();
|
|
18
|
+
throw new HarnessClientError("invalid_config", "Could not obtain native inference relay grant");
|
|
19
|
+
}
|
|
20
|
+
signal.throwIfAborted();
|
|
21
|
+
if (grant === undefined) return send();
|
|
22
|
+
// A custom harness can return arbitrary error strings. Keep the codes used
|
|
23
|
+
// by recovery, and expose only the fixed relay diagnostics we emit ourselves.
|
|
24
|
+
try {
|
|
25
|
+
return await send(grant);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
const code = codeOf(error);
|
|
28
|
+
const allowed = ["not_found", "timeout", "transport_closed", "closed", "storage_failure", "invalid_config",
|
|
29
|
+
"invalid_params", "incompatible", "busy", "already_exists"];
|
|
30
|
+
const message = error instanceof Error ? error.message : "";
|
|
31
|
+
const safe = /^(?:Error: )?Inference relay grant (?:is required|is invalid|has expired|does not match the configured endpoint|requires relay credential mode|requires executable access)$/.test(message);
|
|
32
|
+
throw new HarnessClientError(code && allowed.includes(code) ? code : "invalid_config",
|
|
33
|
+
safe ? message.replace(/^Error: /, "") : "Native inference relay open failed");
|
|
34
|
+
}
|
|
35
|
+
}
|
package/src/native/recovery.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { executableRelayOpen, type InferenceRelayGrantProvider } from "./inference-relay.ts";
|
|
1
2
|
import { executableMcpOpen, type McpRuntimeHeadersProvider } from "./mcp.ts";
|
|
2
3
|
import { activatesRoutine, RoutineAdmission } from "./reminders/routine-guard.ts";
|
|
3
4
|
import type { ReminderChange } from "../persistence/reminders.ts";
|
|
@@ -52,7 +53,7 @@ export async function readCompleteMessage(client: HarnessClient, messageId: stri
|
|
|
52
53
|
|
|
53
54
|
/** The catalog and startup edits are installed before recovered work can start. */
|
|
54
55
|
export async function openOrCreate(
|
|
55
|
-
client: HarnessClient, config: { sessionId: string; config?: RoutineConfigInput; mcpRuntimeHeaders?: McpRuntimeHeadersProvider },
|
|
56
|
+
client: HarnessClient, config: { sessionId: string; config?: RoutineConfigInput; mcpRuntimeHeaders?: McpRuntimeHeadersProvider; inferenceRelayGrant?: InferenceRelayGrantProvider },
|
|
56
57
|
batch: PendingChannelChange[], tools: Parameters<HarnessClient["openSession"]>[0]["tools"], signal: AbortSignal, reminders?: ReminderSync,
|
|
57
58
|
) {
|
|
58
59
|
const admission = reminders?.routineAdmission ?? new RoutineAdmission();
|
|
@@ -72,10 +73,10 @@ export async function openOrCreate(
|
|
|
72
73
|
sessionId: config.sessionId, config: admission.configForOpen(config.config), ...changes,
|
|
73
74
|
...(staged.length ? { reminderChanges: staged } : {}),
|
|
74
75
|
};
|
|
75
|
-
const send = (request: typeof params) => executableMcpOpen(config.mcpRuntimeHeaders, signal, material => {
|
|
76
|
-
const executable = { ...request, ...(material === undefined ? {} : { mcpRuntimeHeaders: material }) };
|
|
76
|
+
const send = (request: typeof params) => executableRelayOpen(config.inferenceRelayGrant, config.sessionId, signal, grant => executableMcpOpen(config.mcpRuntimeHeaders, signal, material => {
|
|
77
|
+
const executable = { ...request, ...(grant === undefined ? {} : { inferenceRelayGrant: grant }), ...(material === undefined ? {} : { mcpRuntimeHeaders: material }) };
|
|
77
78
|
return create ? client.createSession({ ...executable, participants: [], channels: {} }) : client.openSession(executable);
|
|
78
|
-
});
|
|
79
|
+
}));
|
|
79
80
|
try {
|
|
80
81
|
return await send(params);
|
|
81
82
|
} catch (error) {
|
|
@@ -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
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ModelAttempt } from "../../contracts/model-execution.ts";
|
|
2
|
+
import type { InferenceRelayGrant } from "../../contracts/protocol.ts";
|
|
3
|
+
import { openAICompatibleAttempt } from "./openrouter-stream.ts";
|
|
4
|
+
|
|
5
|
+
const expired = {
|
|
6
|
+
type: "failure", kind: "invalid_config", message: "Inference relay credential expired",
|
|
7
|
+
diagnostic: { provider: "chat_completions", category: "relay_expired" },
|
|
8
|
+
} as const;
|
|
9
|
+
|
|
10
|
+
/** A relay attempt owns its direct dispatcher and releases it on any terminal
|
|
11
|
+
* event, including cancellation by the model runner. */
|
|
12
|
+
export function inferenceRelayAttempt(model: string, grant: InferenceRelayGrant,
|
|
13
|
+
metadata?: Parameters<typeof openAICompatibleAttempt>[5]): ModelAttempt {
|
|
14
|
+
return async function* (request, signal) {
|
|
15
|
+
if (Date.now() >= grant.expiresAtMs) { yield expired; return; }
|
|
16
|
+
// Bun's package-name shim can use global, proxy-aware fetch. An explicit
|
|
17
|
+
// unshimmed dispatcher sends this request only to the validated origin.
|
|
18
|
+
const undici: typeof import("undici") = await import(new URL("index.js", import.meta.resolve("undici/package.json")).href);
|
|
19
|
+
const dispatcher = new undici.Agent({ connect: { rejectUnauthorized: true } });
|
|
20
|
+
let dispatchExpired = false;
|
|
21
|
+
const directFetch = (async (input: unknown, init?: RequestInit) => {
|
|
22
|
+
if (Date.now() >= grant.expiresAtMs) {
|
|
23
|
+
dispatchExpired = true;
|
|
24
|
+
throw new Error(expired.message);
|
|
25
|
+
}
|
|
26
|
+
return undici.fetch(String(input), {
|
|
27
|
+
method: "POST", body: String(init?.body),
|
|
28
|
+
headers: Object.fromEntries(new Headers(init?.headers)), signal: init?.signal ?? undefined,
|
|
29
|
+
redirect: "manual", dispatcher,
|
|
30
|
+
});
|
|
31
|
+
}) as unknown as typeof fetch;
|
|
32
|
+
const attempt = openAICompatibleAttempt(grant.baseUrl, model, grant.bearerToken, directFetch, undefined, metadata);
|
|
33
|
+
const token = grant.bearerToken;
|
|
34
|
+
const marker = "[relay credential hidden]";
|
|
35
|
+
const redact = (text: string) => text.replaceAll(token, marker.includes(token) ? "[ ]" : marker);
|
|
36
|
+
let pending = "";
|
|
37
|
+
try {
|
|
38
|
+
for await (const event of attempt(request, signal)) {
|
|
39
|
+
if (dispatchExpired) { yield expired; return; }
|
|
40
|
+
if (event.type === "text_delta") {
|
|
41
|
+
// Retain only a possible partial credential across provider frames.
|
|
42
|
+
pending = redact(pending + event.text);
|
|
43
|
+
let tail = Math.min(pending.length, token.length - 1);
|
|
44
|
+
while (tail > 0 && !token.startsWith(pending.slice(-tail))) tail--;
|
|
45
|
+
const visible = pending.slice(0, pending.length - tail);
|
|
46
|
+
pending = pending.slice(pending.length - tail);
|
|
47
|
+
if (visible) yield { type: "text_delta", text: visible };
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (event.type === "response") {
|
|
51
|
+
if (event.response.calls.some(call => [call.id, call.name, call.arguments].some(value => value.includes(token)))) {
|
|
52
|
+
yield { type: "failure", kind: "provider", message: "Unsafe inference relay response",
|
|
53
|
+
diagnostic: { provider: "chat_completions", category: "protocol" } };
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (pending) yield { type: "text_delta", text: pending };
|
|
57
|
+
yield { ...event, response: { ...event.response,
|
|
58
|
+
content: event.response.content === null ? null : redact(event.response.content) } };
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
yield event;
|
|
62
|
+
}
|
|
63
|
+
} finally { await dispatcher.destroy(); }
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -133,19 +133,20 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
|
|
|
133
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]"); }
|
|
134
134
|
return safe;
|
|
135
135
|
};
|
|
136
|
-
const
|
|
136
|
+
const diagnosticProvider = endpoint ? "chat_completions" as const : "openrouter" as const;
|
|
137
|
+
const errorText = () => endpoint ? "Chat Completions transport failed" : "OpenRouter transport failed";
|
|
137
138
|
onRequest?.(imageUrls.length ? redact(body) : body);
|
|
138
139
|
let response: Response;
|
|
139
140
|
try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: {
|
|
140
141
|
...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json",
|
|
141
142
|
...(goSession ? { "User-Agent": "acp-client/native-harness", "x-opencode-session": goSession } : {}),
|
|
142
143
|
}, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
|
|
143
|
-
catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(
|
|
144
|
+
catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(), diagnostic: { provider: diagnosticProvider, category: "transport" } }; return; }
|
|
144
145
|
if (!response.ok) {
|
|
145
146
|
if (endpoint) {
|
|
146
147
|
if (response.status >= 300 && response.status < 400) {
|
|
147
148
|
void response.body?.cancel().catch(() => {});
|
|
148
|
-
yield { type: "failure", kind: "provider", message: "redirect_refused",
|
|
149
|
+
yield { type: "failure", kind: "provider", message: "redirect_refused", diagnostic: { provider: diagnosticProvider, category: "redirect" },
|
|
149
150
|
...(goSession ? { providerFailure: `OpenCode Go HTTP ${response.status} (redirect_refused)` } : {}) }; return;
|
|
150
151
|
}
|
|
151
152
|
const upstream = await readErrorBody(response);
|
|
@@ -156,17 +157,11 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
|
|
|
156
157
|
yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message, providerFailure: message };
|
|
157
158
|
return;
|
|
158
159
|
}
|
|
159
|
-
yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}
|
|
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;
|
|
160
161
|
}
|
|
161
|
-
if (
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
message: `OpenRouter HTTP ${response.status}` }; return;
|
|
165
|
-
}
|
|
166
|
-
const raw = await response.text();
|
|
167
|
-
try { if (isProviderContextError(JSON.parse(raw))) { yield providerContextFailure; return; } } catch { /* Non-JSON error body. */ }
|
|
168
|
-
const text = redact(raw);
|
|
169
|
-
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;
|
|
170
165
|
}
|
|
171
166
|
const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
|
|
172
167
|
const requestId = safeRequestId(response.headers.get("x-request-id") ?? undefined);
|
|
@@ -209,14 +204,14 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
|
|
|
209
204
|
const ordered = [...fragments.entries()].sort((a, b) => a[0] - b[0]);
|
|
210
205
|
if (ordered.some(([n], i) => n !== i)) { yield { type: "failure", kind: "provider", message: "Non-contiguous tool fragments" }; return; }
|
|
211
206
|
const stopReason = stop === "stop" ? "complete" : stop === "tool_calls" ? "tool_calls" : stop === "length" ? "output_limit" : undefined;
|
|
212
|
-
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; }
|
|
213
208
|
const calls = ordered.map(([, value]) => value);
|
|
214
209
|
const message = { role: "assistant" as const, content: content || null, calls };
|
|
215
210
|
const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, ...(endpoint ? {} : { providerState: { role: "assistant", content: message.content,
|
|
216
211
|
...(reasoning ? { reasoning } : {}), ...(reasoningDetails.length ? { reasoning_details: reasoningDetails } : {}),
|
|
217
212
|
...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
|
|
218
213
|
yield event;
|
|
219
|
-
} 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" } }; }
|
|
220
215
|
finally { if (endpoint || profile) void reader.cancel().catch(() => {}); reader.releaseLock(); }
|
|
221
216
|
};
|
|
222
217
|
}
|
|
@@ -1,14 +1,41 @@
|
|
|
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
11
|
readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
|
|
10
|
-
readonly providerFailure?: string) {
|
|
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 === "relay_expired" && diagnostic.provider === "chat_completions") return "Inference relay credential expired";
|
|
27
|
+
if (diagnostic.category === "transport") return `${provider} transport failed`;
|
|
28
|
+
if (diagnostic.category === "redirect") return `${provider} redirect refused`;
|
|
29
|
+
if (diagnostic.category === "protocol") return `${provider} returned an invalid response`;
|
|
30
|
+
}
|
|
31
|
+
switch (event.kind) {
|
|
32
|
+
case "transient": return "Temporary model provider failure";
|
|
33
|
+
case "invalid_request": return "Model provider rejected the request";
|
|
34
|
+
case "invalid_config": return "Model provider configuration failed";
|
|
35
|
+
default: return "Model provider failed";
|
|
36
|
+
}
|
|
11
37
|
}
|
|
38
|
+
|
|
12
39
|
class ModelStorageError extends Error {}
|
|
13
40
|
function take<T>(result: StorageResult<T>): T {
|
|
14
41
|
if (!result.ok) throw new ModelStorageError(`Model call storage ${result.error.code}: ${result.error.message}`);
|
|
@@ -81,7 +108,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
81
108
|
if (event.type === "text_delta") { output = true; options.delta?.({ messageId: call.messageId, text: event.text }); }
|
|
82
109
|
} else if (event.type === "usage") take(options.store.recordUsage(call.callId, attempt.attemptId, event.usage));
|
|
83
110
|
}
|
|
84
|
-
} catch (error) { if (error instanceof ModelStorageError) throw error; terminal = { type: "failure", kind: "provider", message:
|
|
111
|
+
} catch (error) { if (error instanceof ModelStorageError) throw error; terminal = { type: "failure", kind: "provider", message: "Model attempt failed unexpectedly" }; }
|
|
85
112
|
finally { clearTimeout(timer); options.signal?.removeEventListener("abort", abort); controller.abort(); }
|
|
86
113
|
if (options.signal?.aborted || cancellation === "interrupted") {
|
|
87
114
|
// The lifecycle transaction may already have ended this call. In that
|
|
@@ -91,11 +118,11 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
91
118
|
take(ended); return finish("interrupted");
|
|
92
119
|
}
|
|
93
120
|
if (Date.now() >= deadline || cancellation === "timeout") {
|
|
94
|
-
take(options.store.finishAttempt(call.callId, attempt.attemptId, "timeout")); return finish("timeout");
|
|
121
|
+
take(options.store.finishAttempt(call.callId, attempt.attemptId, "timeout")); return finish("timeout", "Model request deadline exceeded");
|
|
95
122
|
}
|
|
96
123
|
if (terminal?.type === "response") {
|
|
97
124
|
if (terminal.providerRequestId) take(options.store.recordProviderRequestId(call.callId, attempt.attemptId, terminal.providerRequestId));
|
|
98
|
-
if (!validResponse(terminal.response)) { take(options.store.finishAttempt(call.callId, attempt.attemptId, "invalid_request")); return finish("failed"); }
|
|
125
|
+
if (!validResponse(terminal.response)) { take(options.store.finishAttempt(call.callId, attempt.attemptId, "invalid_request")); return finish("failed", "Invalid model response"); }
|
|
99
126
|
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);
|
|
100
127
|
if (terminal.response.stopReason === "output_limit") { take(options.store.finishAttempt(call.callId, attempt.attemptId, "output_limit")); return finish("output_limit"); }
|
|
101
128
|
const committed = options.store.commitResponse(call.callId, attempt.attemptId, terminal.response, terminal.providerRequestId);
|
|
@@ -108,20 +135,33 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
108
135
|
const attemptOutcome = failure === "transient" ? "transient_failure" : failure === "provider" ? "provider_failure" : failure;
|
|
109
136
|
take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
|
|
110
137
|
if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
|
|
111
|
-
if (terminal?.type === "failure" && terminal.code
|
|
112
|
-
|
|
138
|
+
if (terminal?.type === "failure" && (terminal.code === "unsupported_image" || terminal.code === "attachment_unavailable" || terminal.code === "transfer_limit")) {
|
|
139
|
+
const ids = new Set(request.messages.flatMap(message => "parts" in message
|
|
140
|
+
? (message.parts ?? []).flatMap(part => part.type === "attachment" ? [part.id] : []) : []));
|
|
141
|
+
return finish("failed", "Model attachment rejected", { code: terminal.code,
|
|
142
|
+
attachmentIds: [...new Set((terminal.attachmentIds ?? []).filter(id => ids.has(id)))] });
|
|
143
|
+
}
|
|
144
|
+
if (terminal?.type === "failure" && terminal.contextFailure) {
|
|
145
|
+
const context = parseContextLimitFailure(`context_limit:${JSON.stringify(terminal.contextFailure)}`);
|
|
146
|
+
if (context) return finish("failed", "Model context limit exceeded", undefined, context);
|
|
147
|
+
}
|
|
113
148
|
if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) {
|
|
114
|
-
const
|
|
115
|
-
|
|
149
|
+
const candidate = terminal?.type === "failure" ? terminal.providerFailure : undefined;
|
|
150
|
+
const providerFailure = typeof candidate === "string" &&
|
|
151
|
+
/^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)
|
|
152
|
+
? candidate : undefined;
|
|
153
|
+
return finish(failure === "incomplete" ? "incomplete" : "failed",
|
|
154
|
+
providerFailure ?? (terminal?.type === "failure" ? safeDiagnostic(terminal) : "Model response ended before completion"),
|
|
155
|
+
undefined, undefined, providerFailure);
|
|
116
156
|
}
|
|
117
|
-
if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
|
|
157
|
+
if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout", "Model request deadline exceeded");
|
|
118
158
|
const delay = await new Promise<"ready" | "interrupted">(resolve => {
|
|
119
159
|
const done = (result: "ready" | "interrupted") => { clearTimeout(wait); options.signal?.removeEventListener("abort", interrupted); resolve(result); };
|
|
120
160
|
const interrupted = () => done("interrupted"); const wait = setTimeout(() => done("ready"), settings.retryDelayMs);
|
|
121
161
|
options.signal?.addEventListener("abort", interrupted, { once: true }); if (options.signal?.aborted) interrupted();
|
|
122
162
|
});
|
|
123
163
|
if (delay === "interrupted") return finish("interrupted");
|
|
124
|
-
if (Date.now() >= deadline) return finish("timeout");
|
|
164
|
+
if (Date.now() >= deadline) return finish("timeout", "Model request deadline exceeded");
|
|
125
165
|
}
|
|
126
166
|
return finish("failed");
|
|
127
167
|
}
|
|
@@ -6,6 +6,7 @@ export { createStdioTransport } from "./interfaces/protocol/stdio-client.ts";
|
|
|
6
6
|
export type { StdioConnection } from "./contracts/protocol.ts";
|
|
7
7
|
export type { ChannelEvent } from "./contracts/events.ts";
|
|
8
8
|
export type { InitializeParams, CreateParams, PushParams, NotifyParams, ProtocolConfig, ClientTransport, PendingChannelChange, ChannelChangeResult, LoadResult, StatusResult, ChannelStatusResult, ItemStatus, TurnStatus, StoredMessage } from "./contracts/protocol.ts";
|
|
9
|
+
export type { InferenceRelayGrant } from "./contracts/protocol.ts";
|
|
9
10
|
export type { ManagedConfig, ManagedModel, ModelContextBudget, ToolPolicy, ToolDecision, ItemPolicy, ApprovalRequest, ApprovalAnswer, ApprovalCloseReason } from "./contracts/config-permissions.ts";
|
|
10
11
|
export type { ContextLimitFailure, ContextBudgetMeasurement } from "./contracts/context.ts";
|
|
11
12
|
|
|
@@ -14,7 +14,7 @@ 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;
|
|
17
|
+
| { protocol: "openai-compatible"; providerId: string; model: string; baseUrl: string; contextBudget?: ModelContextBudget } & ({ credentialMode?: never; apiKeyEnv?: string } | { credentialMode: "relay"; apiKeyEnv?: never })
|
|
18
18
|
| { protocol: "opencode-go"; model: string; apiKeyEnv?: string; contextBudget?: ModelContextBudget };
|
|
19
19
|
|
|
20
20
|
/** Both text-only managed sources use the same Chat Completions client. */
|
|
@@ -34,9 +34,10 @@ export type ModelAttemptEvent =
|
|
|
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
36
|
contextFailure?: import("./context.ts").ContextLimitFailure;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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" | "relay_expired" } };
|
|
40
41
|
/** One attempt emits exactly one terminal response or failure unless aborted;
|
|
41
42
|
* EOF without a terminal is incomplete. A consumer ignores events after the
|
|
42
43
|
* first terminal, timeout or abort. The adapter assembles and validates tools. */
|
|
@@ -71,6 +71,7 @@ export interface OperatorMethods {
|
|
|
71
71
|
|
|
72
72
|
export interface LoadResultOpenParams {
|
|
73
73
|
/** Executable owning launcher material, never saved. */
|
|
74
|
+
inferenceRelayGrant?: import("./protocol.ts").InferenceRelayGrant;
|
|
74
75
|
mcpRuntimeHeaders?: import("./mcp.ts").McpRuntimeHeaders;
|
|
75
76
|
sessionId: string;
|
|
76
77
|
config?: ProtocolConfig;
|
|
@@ -27,7 +27,10 @@ export interface ProtocolConfig {
|
|
|
27
27
|
defaultPolicy?: string;
|
|
28
28
|
policies?: Record<string, import("./config-permissions.ts").ToolPolicy>;
|
|
29
29
|
}
|
|
30
|
+
/** Executable-only grant from the trusted native control connection. */
|
|
31
|
+
export interface InferenceRelayGrant { baseUrl: string; bearerToken: string; expiresAtMs: number }
|
|
30
32
|
export interface CreateParams {
|
|
33
|
+
inferenceRelayGrant?: InferenceRelayGrant;
|
|
31
34
|
/** Executable owning launcher material, never saved. */
|
|
32
35
|
mcpRuntimeHeaders?: import("./mcp.ts").McpRuntimeHeaders;
|
|
33
36
|
sessionId: string;
|
|
@@ -66,6 +66,9 @@ export interface StorageOpenOptions {
|
|
|
66
66
|
* Changing only the system preserves open but blocks checkpoint resume.
|
|
67
67
|
* Callers that omit this option retain the existing behavior. */
|
|
68
68
|
requiredScriptDigest?: string;
|
|
69
|
+
/** Optional executable-open guard, checked under storage ownership before
|
|
70
|
+
* recovery. An error message denies the open without committing recovery. */
|
|
71
|
+
checkExecution?: () => string | undefined;
|
|
69
72
|
/** Validated policies for this owner; legacy callers use the legacy policy. */
|
|
70
73
|
config?: import("./config-permissions.ts").ManagedConfig;
|
|
71
74
|
}
|
|
@@ -34,7 +34,7 @@ class Fault extends Error {
|
|
|
34
34
|
export class SessionOpenError extends Error {
|
|
35
35
|
constructor(readonly code: DurableErrorCode, message: string) { super(message); }
|
|
36
36
|
}
|
|
37
|
-
export interface SessionRequest { mode: "create" | "open"; sessionId: string; config?: ProtocolConfig; mcpRuntimeHeaders?: unknown;
|
|
37
|
+
export interface SessionRequest { mode: "create" | "open"; sessionId: string; config?: ProtocolConfig; mcpRuntimeHeaders?: unknown; inferenceRelayGrant?: unknown;
|
|
38
38
|
/** Decision 0021: a catalog whose shape is valid. The factory checks its names
|
|
39
39
|
* against its built-in tools and passes it to the session. */
|
|
40
40
|
tools?: ToolCatalogInput }
|
|
@@ -260,7 +260,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
260
260
|
return { valid: true };
|
|
261
261
|
}
|
|
262
262
|
if (method === "session/create") {
|
|
263
|
-
keys(p, ["sessionId", "config", "participants", "channels", "channelChanges", "tools", "reminderChanges", "mcpRuntimeHeaders"]);
|
|
263
|
+
keys(p, ["sessionId", "config", "participants", "channels", "channelChanges", "tools", "reminderChanges", "mcpRuntimeHeaders", "inferenceRelayGrant"]);
|
|
264
264
|
const reminderBatch = parseReminderBatch(p.reminderChanges);
|
|
265
265
|
const tools = catalogOf(p.tools);
|
|
266
266
|
const sessionId = text(p.sessionId);
|
|
@@ -279,7 +279,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
279
279
|
// effective configuration is known.
|
|
280
280
|
const batch = p.channelChanges === undefined ? undefined : parseChannelChanges(p.channelChanges);
|
|
281
281
|
if (batch && p.config?.policies) checkPolicies(batch, Object.keys(p.config.policies));
|
|
282
|
-
const opened = await attach({ mode: "create", sessionId, config: p.config, mcpRuntimeHeaders: p.mcpRuntimeHeaders, ...(tools ? { tools } : {}) });
|
|
282
|
+
const opened = await attach({ mode: "create", sessionId, config: p.config, mcpRuntimeHeaders: p.mcpRuntimeHeaders, inferenceRelayGrant: p.inferenceRelayGrant, ...(tools ? { tools } : {}) });
|
|
283
283
|
let results: ChannelChangeResult[] | undefined;
|
|
284
284
|
let reminderResult: ReturnType<typeof reminderView>;
|
|
285
285
|
try {
|
|
@@ -297,7 +297,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
297
297
|
return { ...(opened.session.operatorReads ? ready(opened) : { sessionId }), ...reminderResult, ...(results ? { channelChanges: results } : {}) };
|
|
298
298
|
}
|
|
299
299
|
if (method === "session/open") {
|
|
300
|
-
keys(p, ["sessionId", "config", "channelChanges", "tools", "reminderChanges", "mcpRuntimeHeaders"]);
|
|
300
|
+
keys(p, ["sessionId", "config", "channelChanges", "tools", "reminderChanges", "mcpRuntimeHeaders", "inferenceRelayGrant"]);
|
|
301
301
|
const reminderBatch = parseReminderBatch(p.reminderChanges);
|
|
302
302
|
const tools = catalogOf(p.tools);
|
|
303
303
|
const sessionId = text(p.sessionId);
|
|
@@ -306,14 +306,14 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
306
306
|
// the batch was applied by the open and is only reported again. A new
|
|
307
307
|
// batch belongs to the live channel API.
|
|
308
308
|
if (current) {
|
|
309
|
-
if (p.mcpRuntimeHeaders !== undefined) bad("Runtime material requires a new executable open");
|
|
309
|
+
if (p.mcpRuntimeHeaders !== undefined || p.inferenceRelayGrant !== undefined) bad("Runtime material requires a new executable open");
|
|
310
310
|
if (ready(current).sessionId !== sessionId) throw new Fault("already_exists", "One session per endpoint");
|
|
311
311
|
if (batch && !sameBatch(startup?.batch ?? [], batch)) throw new Fault("invalid_state", "The session is already open; send newer channel changes through the channel methods");
|
|
312
312
|
if (tools && !(startupTools && sameCatalog(startupTools, tools))) throw new Fault("invalid_state", "The session is already open with another tool catalog; use the tool methods");
|
|
313
313
|
if (p.reminderChanges !== undefined && JSON.stringify(reminderBatch) !== JSON.stringify(reminderStartup?.batch ?? [])) throw new Fault("invalid_state", "The session is already open; send changes through reminder/change");
|
|
314
314
|
return { ...ready(current), ...reminderView(current.session, reminderStartup?.results), ...(startup ? { channelChanges: startup.results } : {}) };
|
|
315
315
|
}
|
|
316
|
-
const opened = await attach({ mode: "open", sessionId, config: p.config, mcpRuntimeHeaders: p.mcpRuntimeHeaders, ...(tools ? { tools } : {}) });
|
|
316
|
+
const opened = await attach({ mode: "open", sessionId, config: p.config, mcpRuntimeHeaders: p.mcpRuntimeHeaders, inferenceRelayGrant: p.inferenceRelayGrant, ...(tools ? { tools } : {}) });
|
|
317
317
|
try {
|
|
318
318
|
const finish = batch && await prepare(opened, batch);
|
|
319
319
|
// From here to the end of the block nothing is awaited: the resumes, the
|
|
@@ -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); }
|
|
@@ -4,6 +4,6 @@ import { OPENCODE_GO_BASE_URL, type CompatibleModel } from "../../contracts/conf
|
|
|
4
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];
|
|
7
|
+
: [model.protocol, model.providerId, model.baseUrl, ...(model.credentialMode === "relay" ? ["relay"] : [])];
|
|
8
8
|
return createHash("sha256").update(JSON.stringify([...source, model.model, system, tools])).digest("hex");
|
|
9
9
|
}
|
|
@@ -342,6 +342,8 @@ export function createMemoryStorageAdapter(adapterOptions: { mediaRoot?: string
|
|
|
342
342
|
tables.transaction(() => {
|
|
343
343
|
checkUnattendedGuard(tables, config?.limits?.unattendedTurns);
|
|
344
344
|
if (referencesCompatible(tables, config)) {
|
|
345
|
+
const denied = options.checkExecution?.();
|
|
346
|
+
if (denied !== undefined) throw new Fail("invalid_config", denied);
|
|
345
347
|
recover(tables, undefined, reminderEvents);
|
|
346
348
|
bindUnattendedGuard(tables, config?.limits?.unattendedTurns);
|
|
347
349
|
}
|
|
@@ -636,6 +636,10 @@ export function createSqliteStorageAdapter(path: string, adapterOptions: { media
|
|
|
636
636
|
refreshReplyIds(owner);
|
|
637
637
|
refreshModelCalls(owner);
|
|
638
638
|
const compatible = meta.formatVersion < 4 || referencesCompatible(tables, config);
|
|
639
|
+
if (compatible) {
|
|
640
|
+
const denied = options.checkExecution?.();
|
|
641
|
+
if (denied !== undefined) throw new Fail("invalid_config", denied);
|
|
642
|
+
}
|
|
639
643
|
if (meta.formatVersion >= 4 && meta.formatVersion < 6 && compatible) addExternalSource(owner);
|
|
640
644
|
if (compatible)
|
|
641
645
|
recover(tables, meta.formatVersion < 4 ? () => { if (meta.formatVersion === 2) upgradeFromFormat2(owner); upgradeFromFormat3(owner); addExternalSource(owner); } : undefined, reminderEvents);
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { inferenceRelayAttempt } from "./capabilities/model/inference-relay.ts";
|
|
2
|
+
import { resolveInferenceRelayGrant } from "./util/inference-relay.ts";
|
|
1
3
|
import { isCompatibleModel } from "./contracts/config-permissions.ts";
|
|
2
4
|
import { validateMcpRuntimeHeaders } from "./util/mcp-config.ts";
|
|
3
5
|
import { openMcpRegistry } from "./capabilities/tools/mcp/registry.ts";
|
|
@@ -133,7 +135,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
133
135
|
}
|
|
134
136
|
return memory;
|
|
135
137
|
};
|
|
136
|
-
const server = createProtocolServer(async ({ mode, sessionId, config: inline, tools, mcpRuntimeHeaders }) => {
|
|
138
|
+
const server = createProtocolServer(async ({ mode, sessionId, config: inline, tools, mcpRuntimeHeaders, inferenceRelayGrant }) => {
|
|
137
139
|
// Decision 0021: the catalog's names must not collide with the built-ins.
|
|
138
140
|
const catalog = tools && parseCatalog(tools, [...BUILTINS, ...webDefinitions].map(tool => tool.name));
|
|
139
141
|
const paths = options.home ? managedSessionPaths(sessionId, options.home) : undefined;
|
|
@@ -143,11 +145,14 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
143
145
|
const config = chooseManagedConfig({ mode, sidecar: paths?.config ?? noSidecar, inline, saved: stored?.ok ? stored.value : undefined });
|
|
144
146
|
const runtimeHeaders = mcpRuntimeHeaders === undefined ? undefined : validateMcpRuntimeHeaders(mcpRuntimeHeaders, config.mcpServers);
|
|
145
147
|
const script = config.model.protocol === "scripted" ? await (options.scenarioLoader ?? loadScenario)(config.model.script) : undefined;
|
|
148
|
+
const relayRequested = config.model.protocol === "openai-compatible" && config.model.credentialMode === "relay";
|
|
149
|
+
let relayGrant = mode === "create" || !relayRequested
|
|
150
|
+
? resolveInferenceRelayGrant(config.model, inferenceRelayGrant) : undefined;
|
|
146
151
|
const credential = config.model.protocol === "openrouter" ? resolveCredential(config.model, options.environment ?? process.env) : undefined;
|
|
147
152
|
let imageInput = !!paths && !options.adapter && !isCompatibleModel(config.model) && config.model.imageInput === true && (config.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
|
|
148
153
|
const compatible = isCompatibleModel(config.model) ? config.model : undefined;
|
|
149
154
|
const environment = options.environment ?? process.env;
|
|
150
|
-
let compatibleKey = compatible && mode === "create" ? resolveCompatibleCredential(compatible, environment) : undefined;
|
|
155
|
+
let compatibleKey = compatible && !relayGrant && mode === "create" ? resolveCompatibleCredential(compatible, environment) : undefined;
|
|
151
156
|
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]" : ""))
|
|
152
157
|
: createHash("sha256").update(JSON.stringify([config.system, config.model.protocol === "openrouter" && config.model.model,
|
|
153
158
|
[...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(!isCompatibleModel(config.model) && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
|
|
@@ -158,7 +163,11 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
158
163
|
return result.value;
|
|
159
164
|
};
|
|
160
165
|
let webTools = mode === "create" ? makeWebTools() : undefined;
|
|
161
|
-
const
|
|
166
|
+
const checkExecution = mode === "open" && relayRequested ? () => {
|
|
167
|
+
try { relayGrant = resolveInferenceRelayGrant(config.model, inferenceRelayGrant); }
|
|
168
|
+
catch (error) { return error instanceof Error ? error.message : "Inference relay grant is invalid"; }
|
|
169
|
+
} : undefined;
|
|
170
|
+
const opened = adapter.open({ mode, identity: { sessionId, compatibilityKey }, config, requiredScriptDigest: script?.modelDigest, checkExecution });
|
|
162
171
|
if (!opened.ok) {
|
|
163
172
|
const code = opened.error.code;
|
|
164
173
|
throw new SessionOpenError(code === "not_found" || code === "already_exists" || code === "owner_conflict" || code === "incompatible" || code === "invalid_config" ? code : "storage_failure", opened.error.message);
|
|
@@ -173,11 +182,13 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
173
182
|
const execution = storage.executionCompatible();
|
|
174
183
|
if (!execution.ok) throw new Error(execution.error.message);
|
|
175
184
|
if (!execution.value) {
|
|
185
|
+
if (inferenceRelayGrant !== undefined) throw new SessionOpenError("invalid_config", "Inference relay grant requires executable access");
|
|
176
186
|
if (runtimeHeaders !== undefined) throw new SessionOpenError("invalid_config", "Runtime MCP headers require executable access");
|
|
177
187
|
imageInput = false;
|
|
178
188
|
}
|
|
179
189
|
if (execution.value && mode === "open") {
|
|
180
|
-
if (
|
|
190
|
+
if (relayRequested && !relayGrant) relayGrant = resolveInferenceRelayGrant(config.model, inferenceRelayGrant);
|
|
191
|
+
if (compatible && !relayGrant) compatibleKey = resolveCompatibleCredential(compatible, environment);
|
|
181
192
|
webTools = makeWebTools();
|
|
182
193
|
}
|
|
183
194
|
if (execution.value && config.mcpServers) mcp = await openMcpRegistry(config, environment, runtimeHeaders, options.mcpFixtureCa);
|
|
@@ -197,9 +208,14 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
197
208
|
const model: Model = async () => { throw new Error("Chat Completions requires a model attempt"); };
|
|
198
209
|
bindModelAttempt(model, { scripted: false,
|
|
199
210
|
...(options.modelTimeoutMs === undefined ? {} : { settings: { timeoutMs: options.modelTimeoutMs } }),
|
|
200
|
-
create: () =>
|
|
201
|
-
const
|
|
202
|
-
|
|
211
|
+
create: () => {
|
|
212
|
+
const conversation = { sessionId, channelId: turn.channelId };
|
|
213
|
+
const metadata = attachments ? (id: string) => {
|
|
214
|
+
const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
|
|
215
|
+
} : undefined;
|
|
216
|
+
return relayGrant ? inferenceRelayAttempt(compatible.model, relayGrant, metadata)
|
|
217
|
+
: managedCompatibleAttempt(compatible, conversation, compatibleKey, undefined, metadata);
|
|
218
|
+
} });
|
|
203
219
|
return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
|
|
204
220
|
}
|
|
205
221
|
if (config.model.protocol === "openrouter") {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { canonicalRelayUrl } from "./inference-relay.ts";
|
|
1
2
|
import { validateMcpServers } from "./mcp-config.ts";
|
|
2
3
|
import { validateWebConfig } from "./web-config.ts";
|
|
3
4
|
import { OPENCODE_GO_KEY_ENV, type CompatibleModel, type ManagedConfig, type ModelContextBudget, type ToolDecision, type ToolPolicy } from "../contracts/config-permissions.ts";
|
|
@@ -71,11 +72,19 @@ export function validateManagedConfig(input: unknown, legacy = false): ManagedCo
|
|
|
71
72
|
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) fail("config.model.apiKeyEnv", "expected an environment variable name");
|
|
72
73
|
selectedModel = { protocol: "openrouter", model: model.model === undefined ? "deepseek/deepseek-v4.1-flash" : name(model.model, "config.model.model"), apiKeyEnv: reference, ...imageInput, ...modelContextBudget(model.contextBudget) };
|
|
73
74
|
} else if (model.protocol === "openai-compatible") {
|
|
74
|
-
keys(model, ["protocol", "providerId", "model", "baseUrl", "apiKeyEnv", "contextBudget"], "config.model");
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
75
|
+
keys(model, ["protocol", "providerId", "model", "baseUrl", "apiKeyEnv", "contextBudget", "credentialMode"], "config.model");
|
|
76
|
+
const shared = { protocol: "openai-compatible" as const, providerId: name(model.providerId, "config.model.providerId"),
|
|
77
|
+
model: name(model.model, "config.model.model"), ...modelContextBudget(model.contextBudget) };
|
|
78
|
+
if (model.credentialMode === "relay") {
|
|
79
|
+
if (Object.hasOwn(model, "apiKeyEnv")) return fail("config.model.apiKeyEnv", "relay mode requires runtime credentials");
|
|
80
|
+
try { selectedModel = { ...shared, credentialMode: "relay", baseUrl: canonicalRelayUrl(model.baseUrl) }; }
|
|
81
|
+
catch { return fail("config.model.baseUrl", "invalid inference relay URL"); }
|
|
82
|
+
} else {
|
|
83
|
+
if (model.credentialMode !== undefined) return fail("config.model.credentialMode", "expected relay");
|
|
84
|
+
const reference = model.apiKeyEnv === undefined ? undefined : name(model.apiKeyEnv, "config.model.apiKeyEnv");
|
|
85
|
+
if (reference !== undefined && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) fail("config.model.apiKeyEnv", "expected an environment variable name");
|
|
86
|
+
selectedModel = { ...shared, baseUrl: baseUrl(model.baseUrl), ...(reference === undefined ? {} : { apiKeyEnv: reference }) };
|
|
87
|
+
}
|
|
79
88
|
} else if (model.protocol === "opencode-go") {
|
|
80
89
|
keys(model, ["protocol", "model", "apiKeyEnv", "contextBudget"], "config.model");
|
|
81
90
|
const reference = model.apiKeyEnv === undefined ? OPENCODE_GO_KEY_ENV : name(model.apiKeyEnv, "config.model.apiKeyEnv");
|
|
@@ -130,6 +139,8 @@ export function resolveCredential(model: Extract<ManagedConfig["model"], { proto
|
|
|
130
139
|
|
|
131
140
|
export function resolveCompatibleCredential(model: CompatibleModel,
|
|
132
141
|
environment: Record<string, string | undefined>): string | undefined {
|
|
142
|
+
if (model.protocol === "openai-compatible" && model.credentialMode === "relay")
|
|
143
|
+
return fail("config.model.credentialMode", "relay mode requires an executable native control connection grant");
|
|
133
144
|
const reference = model.apiKeyEnv ?? (model.protocol === "opencode-go" ? OPENCODE_GO_KEY_ENV : undefined);
|
|
134
145
|
if (reference === undefined) return;
|
|
135
146
|
const value = environment[reference];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ManagedModel } from "../contracts/config-permissions.ts";
|
|
2
|
+
import type { InferenceRelayGrant } from "../contracts/protocol.ts";
|
|
3
|
+
|
|
4
|
+
/** Strict grammar for the execution exception, checked before URL rewrites. */
|
|
5
|
+
export function canonicalRelayUrl(raw: unknown): string {
|
|
6
|
+
const invalid = () => new Error("Invalid inference relay base URL");
|
|
7
|
+
if (typeof raw !== "string" || raw.length > 2048 || /[\s\\?#%\p{Cc}\p{Cf}]/u.test(raw)) throw invalid();
|
|
8
|
+
const match = /^(https?):\/\/([^/]+)(\/.*)?$/i.exec(raw);
|
|
9
|
+
if (!match || match[2]!.includes("@") || match[3]?.split("/").some(segment => segment === "." || segment === ".."))
|
|
10
|
+
throw invalid();
|
|
11
|
+
let url: URL;
|
|
12
|
+
try { url = new URL(raw); } catch { throw invalid(); }
|
|
13
|
+
// Anything encoded by URL parsing would fail the portable declaration's
|
|
14
|
+
// next validation pass, just like an explicit escape in the input.
|
|
15
|
+
if (url.pathname.includes("%")) throw invalid();
|
|
16
|
+
if (url.protocol === "http:") {
|
|
17
|
+
const authority = /^(\[[0-9a-f:]+\]|(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3})(?::(0|[1-9]\d{0,4}))?$/.exec(match[2]!);
|
|
18
|
+
if (!authority || authority[1] !== url.hostname || /^\[::ffff:/i.test(url.hostname)) throw invalid();
|
|
19
|
+
} else {
|
|
20
|
+
const authority = /^(\[[0-9a-f:]+\]|[a-z\d.-]+)(?::(?:0|[1-9]\d{0,4}))?$/i.exec(match[2]!);
|
|
21
|
+
if (!authority || (!authority[1]!.startsWith("[") && authority[1]!.toLowerCase() !== url.hostname))
|
|
22
|
+
throw invalid();
|
|
23
|
+
}
|
|
24
|
+
return url.origin + url.pathname.replace(/\/+$/, "");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The validated grant is detached from the request and held only in memory. */
|
|
28
|
+
export function resolveInferenceRelayGrant(model: ManagedModel, value: unknown,
|
|
29
|
+
now = Date.now()): InferenceRelayGrant | undefined {
|
|
30
|
+
const failure = (reason: string): never => { throw new Error(`Inference relay grant ${reason}`); };
|
|
31
|
+
if (model.protocol !== "openai-compatible" || model.credentialMode !== "relay") {
|
|
32
|
+
if (value !== undefined) failure("requires relay credential mode");
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (value === undefined) return failure("is required");
|
|
36
|
+
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
37
|
+
|| Object.keys(value).some(key => !["baseUrl", "bearerToken", "expiresAtMs"].includes(key))) return failure("is invalid");
|
|
38
|
+
const { baseUrl, bearerToken, expiresAtMs } = value as Partial<InferenceRelayGrant>;
|
|
39
|
+
if (typeof bearerToken !== "string" || !/^[A-Za-z0-9._~+/-]{1,2048}={0,2}$/.test(bearerToken)
|
|
40
|
+
|| typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs)) return failure("is invalid");
|
|
41
|
+
let endpoint: string;
|
|
42
|
+
try { endpoint = canonicalRelayUrl(baseUrl); } catch { return failure("is invalid"); }
|
|
43
|
+
if (endpoint !== model.baseUrl) return failure("does not match the configured endpoint");
|
|
44
|
+
if (expiresAtMs <= now) return failure("has expired");
|
|
45
|
+
return { baseUrl: endpoint, bearerToken, expiresAtMs };
|
|
46
|
+
}
|