@qlairoslabs/acp-client 0.13.6-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 +10 -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/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/inference-relay.ts +65 -0
- package/src/native-harness/src/capabilities/model/runner.ts +1 -0
- 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 +1 -1
- 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/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 }`.
|
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({
|
|
@@ -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) {
|
|
@@ -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
|
+
}
|
|
@@ -23,6 +23,7 @@ function safeDiagnostic(event: Extract<ModelAttemptEvent, { type: "failure" }>):
|
|
|
23
23
|
if (provider && diagnostic) {
|
|
24
24
|
if (diagnostic.category === "http" && Number.isInteger(diagnostic.status) && diagnostic.status >= 400 && diagnostic.status <= 599)
|
|
25
25
|
return `${provider} HTTP ${diagnostic.status}`;
|
|
26
|
+
if (diagnostic.category === "relay_expired" && diagnostic.provider === "chat_completions") return "Inference relay credential expired";
|
|
26
27
|
if (diagnostic.category === "transport") return `${provider} transport failed`;
|
|
27
28
|
if (diagnostic.category === "redirect") return `${provider} redirect refused`;
|
|
28
29
|
if (diagnostic.category === "protocol") return `${provider} returned an invalid response`;
|
|
@@ -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. */
|
|
@@ -37,7 +37,7 @@ export type ModelAttemptEvent =
|
|
|
37
37
|
providerFailure?: string;
|
|
38
38
|
/** Only validated provider/category/status values may enter durable diagnostics. */
|
|
39
39
|
diagnostic?: { provider: "openrouter" | "chat_completions"; category: "http"; status: number }
|
|
40
|
-
| { provider: "openrouter" | "chat_completions"; category: "transport" | "redirect" | "protocol" } };
|
|
40
|
+
| { provider: "openrouter" | "chat_completions"; category: "transport" | "redirect" | "protocol" | "relay_expired" } };
|
|
41
41
|
/** One attempt emits exactly one terminal response or failure unless aborted;
|
|
42
42
|
* EOF without a terminal is incomplete. A consumer ignores events after the
|
|
43
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
|
|
@@ -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
|
+
}
|