@qlairoslabs/acp-client 0.13.6-alpha.1 → 0.13.8-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/agent-conversation-contracts.ts +2 -0
- package/src/agent-session.ts +4 -0
- package/src/client.ts +8 -0
- package/src/controller-connection.ts +8 -3
- package/src/controller.ts +14 -1
- package/src/conversation-controller/contracts.ts +2 -1
- package/src/index.ts +2 -0
- package/src/native/connection.ts +1 -1
- package/src/native/functions.ts +8 -4
- 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/README.md +2 -1
- 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/capabilities/tools/runtime/functions.ts +4 -3
- package/src/native-harness/src/client.ts +2 -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/contracts/tools.ts +9 -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;
|
|
@@ -4,6 +4,7 @@ import type { ConversationPermissionEvent } from "./permissions/conversation.ts"
|
|
|
4
4
|
import type { OperationActivity } from "./operations/contracts.ts";
|
|
5
5
|
import type { ItemsReceipt, TurnCause } from "./conversation-controller/contracts.ts";
|
|
6
6
|
import type { AgentMode } from "./controller.ts";
|
|
7
|
+
import type { AcpSessionStartFailure } from "./client.ts";
|
|
7
8
|
import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
|
|
8
9
|
import type { Adapter } from "./adapters.ts";
|
|
9
10
|
import type { ContextWindowStatus, ProviderCostSnapshot } from "./metering/context.ts";
|
|
@@ -35,6 +36,7 @@ export interface AgentSessionState {
|
|
|
35
36
|
readonly operation: OperationActivity | null;
|
|
36
37
|
readonly pendingHold: { readonly failedTurnId: string } | null;
|
|
37
38
|
readonly providerConnection: "connected" | "disconnected" | "reconnecting";
|
|
39
|
+
readonly sessionStartFailure?: AcpSessionStartFailure;
|
|
38
40
|
readonly phase: AgentSessionPhase;
|
|
39
41
|
/** True only while an operation is executing; queued work is reported separately. */
|
|
40
42
|
readonly isBusy: boolean;
|
package/src/agent-session.ts
CHANGED
|
@@ -1827,12 +1827,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
1827
1827
|
}
|
|
1828
1828
|
/** Immutable current state. Late subscribers read this before listening for deltas. */
|
|
1829
1829
|
get state(): AgentSessionState {
|
|
1830
|
+
const sessionStartFailure = this.controller.sessionStartFailure;
|
|
1830
1831
|
return Object.freeze({
|
|
1831
1832
|
pendingHold: this.steering.hold,
|
|
1832
1833
|
operation: this.activeSupervisor?.activity ?? null,
|
|
1833
1834
|
providerConnection: this.reconnecting
|
|
1834
1835
|
? "reconnecting"
|
|
1835
1836
|
: this.controller.isConnected ? "connected" : "disconnected",
|
|
1837
|
+
...(sessionStartFailure ? { sessionStartFailure } : {}),
|
|
1836
1838
|
phase: this.phase,
|
|
1837
1839
|
isBusy: this.isBusy,
|
|
1838
1840
|
queuedOperationCount: this.queuedOperationCount,
|
|
@@ -4330,6 +4332,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
|
|
|
4330
4332
|
const key = [
|
|
4331
4333
|
state.pendingHold?.failedTurnId ?? "",
|
|
4332
4334
|
state.providerConnection,
|
|
4335
|
+
state.sessionStartFailure?.rpcCode ?? "",
|
|
4336
|
+
state.sessionStartFailure?.message ?? "",
|
|
4333
4337
|
state.operation?.stage ?? "",
|
|
4334
4338
|
state.operation?.operationId ?? "",
|
|
4335
4339
|
state.phase,
|
package/src/client.ts
CHANGED
|
@@ -120,10 +120,18 @@ export interface ListSessionsOptions {
|
|
|
120
120
|
cursor?: string;
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
/** A recoverable ACP startup refusal on an initialized connection. */
|
|
124
|
+
export interface AcpSessionStartFailure {
|
|
125
|
+
/** The adapter's original JSON-RPC error code, when available. */
|
|
126
|
+
readonly rpcCode?: number;
|
|
127
|
+
readonly message: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
123
130
|
export interface ConnectResult {
|
|
124
131
|
sessionId: string;
|
|
125
132
|
/** true = resumed an existing session; false = started fresh (incl. resume fallback). */
|
|
126
133
|
resumed: boolean;
|
|
134
|
+
sessionStartFailure?: AcpSessionStartFailure;
|
|
127
135
|
}
|
|
128
136
|
|
|
129
137
|
export interface SwitchSessionOptions {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AcpClient, type ConnectResult } from "./client.ts";
|
|
1
|
+
import { AcpClient, type AcpSessionStartFailure, type ConnectResult } from "./client.ts";
|
|
2
2
|
import type { AgentClient } from "./agent-client.ts";
|
|
3
3
|
import type { ConnectionAttempt } from "./connection-attempt.ts";
|
|
4
4
|
import type { AgentControllerConfig, AgentMode, ControllerStartEvent } from "./controller.ts";
|
|
@@ -89,8 +89,13 @@ export async function bringUp(
|
|
|
89
89
|
await client.stop();
|
|
90
90
|
throw err;
|
|
91
91
|
}
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
const code = typeof err === "object" && err !== null && "code" in err ? err.code : undefined;
|
|
93
|
+
const sessionStartFailure: AcpSessionStartFailure = Object.freeze({
|
|
94
|
+
...(typeof code === "number" && Number.isSafeInteger(code) ? { rpcCode: code } : {}),
|
|
95
|
+
message: "The ACP adapter refused to start a session.",
|
|
96
|
+
});
|
|
97
|
+
config.logger?.warn("session_start_failed", { ...sessionStartFailure });
|
|
98
|
+
result = { sessionId: "", resumed: false, sessionStartFailure };
|
|
94
99
|
}
|
|
95
100
|
attempt.throwIfCancelled();
|
|
96
101
|
if (result.sessionId) {
|
package/src/controller.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type {
|
|
|
12
12
|
import {
|
|
13
13
|
type AcpClient,
|
|
14
14
|
type AcpClientConfig,
|
|
15
|
+
type AcpSessionStartFailure,
|
|
15
16
|
type ConnectResult,
|
|
16
17
|
type SessionLoadFailure,
|
|
17
18
|
type SwitchSessionOptions,
|
|
@@ -146,6 +147,7 @@ export class HarnessController implements AgentClient, ConversationController {
|
|
|
146
147
|
private readonly connections = new ConnectionAttempts<ConnectResult, ControllerStartEvent>();
|
|
147
148
|
private current: AgentClient | null = null;
|
|
148
149
|
private acp: AcpClient | null = null;
|
|
150
|
+
private startupFailure: AcpSessionStartFailure | undefined;
|
|
149
151
|
private mode: AgentMode;
|
|
150
152
|
private readonly availableCommandListeners = new Set<
|
|
151
153
|
(commands: readonly InternalSessionCommand[]) => void
|
|
@@ -223,6 +225,10 @@ export class HarnessController implements AgentClient, ConversationController {
|
|
|
223
225
|
return this.acp?.currentSessionId ?? null;
|
|
224
226
|
}
|
|
225
227
|
|
|
228
|
+
get sessionStartFailure(): AcpSessionStartFailure | undefined {
|
|
229
|
+
if (this.acp?.isConnected && !this.acp.hasSession) return this.startupFailure;
|
|
230
|
+
}
|
|
231
|
+
|
|
226
232
|
get capabilities(): Capabilities {
|
|
227
233
|
return this.requireAcp().capabilities;
|
|
228
234
|
}
|
|
@@ -297,13 +303,19 @@ export class HarnessController implements AgentClient, ConversationController {
|
|
|
297
303
|
}
|
|
298
304
|
|
|
299
305
|
private existingConnection(): ConnectResult {
|
|
300
|
-
|
|
306
|
+
const sessionStartFailure = this.sessionStartFailure;
|
|
307
|
+
return {
|
|
308
|
+
sessionId: this.currentSessionId ?? "",
|
|
309
|
+
resumed: this.acp?.hasSession ?? false,
|
|
310
|
+
...(sessionStartFailure ? { sessionStartFailure } : {}),
|
|
311
|
+
};
|
|
301
312
|
}
|
|
302
313
|
|
|
303
314
|
private installConnection(attempt: ConnectionAttempt<ControllerStartEvent>, brought: ReadyConnection, mode = this.mode): ConnectResult {
|
|
304
315
|
attempt.throwIfCancelled();
|
|
305
316
|
this.current = brought.client;
|
|
306
317
|
this.acp = brought.acp;
|
|
318
|
+
this.startupFailure = brought.result.sessionStartFailure;
|
|
307
319
|
this.mode = mode;
|
|
308
320
|
this.attachAvailableCommandSource();
|
|
309
321
|
return brought.result;
|
|
@@ -433,6 +445,7 @@ export class HarnessController implements AgentClient, ConversationController {
|
|
|
433
445
|
const client = this.current;
|
|
434
446
|
this.current = null;
|
|
435
447
|
this.acp = null;
|
|
448
|
+
this.startupFailure = undefined;
|
|
436
449
|
this.detachDisconnect?.();
|
|
437
450
|
this.detachDisconnect = null;
|
|
438
451
|
this.connectionChanged();
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import type { NativeTurnMetering } from "../metering/native/source.ts";
|
|
16
16
|
import type { ClientPrompt } from "../agent-client.ts";
|
|
17
|
-
import type { ConnectResult } from "../client.ts";
|
|
17
|
+
import type { AcpSessionStartFailure, ConnectResult } from "../client.ts";
|
|
18
18
|
import type { AgentMode, ControllerStartEvent, HarnessController } from "../controller.ts";
|
|
19
19
|
import type { ConfigOptions } from "../config-options.ts";
|
|
20
20
|
import type { ConversationCapabilities } from "./capabilities.ts";
|
|
@@ -93,6 +93,7 @@ export interface ConversationController {
|
|
|
93
93
|
startFresh(onProgress?: (event: ControllerStartEvent) => void): Promise<StartResult>;
|
|
94
94
|
stop(): Promise<void>;
|
|
95
95
|
readonly isConnected: boolean;
|
|
96
|
+
readonly sessionStartFailure?: AcpSessionStartFailure;
|
|
96
97
|
subscribeConnection(listener: () => void): () => void;
|
|
97
98
|
/** How long a cancelled turn gets before the supervisor escalates; undefined when the adapter sets none. */
|
|
98
99
|
readonly cancelGraceMs: number | undefined;
|
package/src/index.ts
CHANGED
|
@@ -11,6 +11,7 @@ export type { WorkerPersistence, WorkerRow } from "./persistence/workers.ts";
|
|
|
11
11
|
export { AcpClient } from "./client.ts";
|
|
12
12
|
export type {
|
|
13
13
|
AcpClientConfig,
|
|
14
|
+
AcpSessionStartFailure,
|
|
14
15
|
StartSessionOptions,
|
|
15
16
|
ListSessionsOptions,
|
|
16
17
|
SwitchSessionOptions,
|
|
@@ -806,4 +807,5 @@ export type { ReminderErrorCode, ReminderSchedule, ReminderScheduleInput } from
|
|
|
806
807
|
export type { Reminder } from "./persistence/reminders.ts";
|
|
807
808
|
export type { ReminderCreate, ReminderEdit, ReminderView, ReminderEvent } from "./native/reminders/service.ts";
|
|
808
809
|
|
|
810
|
+
export type { InferenceRelayGrant, InferenceRelayGrantProvider } from "./native/inference-relay.ts";
|
|
809
811
|
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/functions.ts
CHANGED
|
@@ -15,6 +15,8 @@ import { closeSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, statSync
|
|
|
15
15
|
import { tmpdir } from "node:os";
|
|
16
16
|
import { join } from "node:path";
|
|
17
17
|
import {
|
|
18
|
+
DEFAULT_INLINE_FUNCTION_RESULT_BYTES,
|
|
19
|
+
encodeInlineFunctionResult,
|
|
18
20
|
FunctionError,
|
|
19
21
|
type FunctionCall,
|
|
20
22
|
type FunctionResult,
|
|
@@ -62,7 +64,7 @@ export interface NativeFunctionsConfig {
|
|
|
62
64
|
readonly defaultDeadlineMs?: number;
|
|
63
65
|
/** Where oversized results are kept. Default: a new private directory under the OS temp dir, removed on stop. */
|
|
64
66
|
readonly resultDirectory?: string;
|
|
65
|
-
/**
|
|
67
|
+
/** UTF-8 bytes of the complete inline success result. Capped at 16 384 bytes. */
|
|
66
68
|
readonly inlineBytes?: number;
|
|
67
69
|
/** How long a stored result can be read. Default 86 400 000 ms (24 hours). */
|
|
68
70
|
readonly resultTtlMs?: number;
|
|
@@ -71,7 +73,7 @@ export interface NativeFunctionsConfig {
|
|
|
71
73
|
}
|
|
72
74
|
|
|
73
75
|
/** Adjustable defaults (native harness BUSINESS_RULES.md, tools and host callbacks). */
|
|
74
|
-
export const NATIVE_FUNCTION_DEFAULTS = { inlineBytes:
|
|
76
|
+
export const NATIVE_FUNCTION_DEFAULTS = { inlineBytes: DEFAULT_INLINE_FUNCTION_RESULT_BYTES, previewChars: 512, resultTtlMs: 86_400_000 } as const;
|
|
75
77
|
|
|
76
78
|
const RESULT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
77
79
|
|
|
@@ -90,7 +92,7 @@ export interface NativeFunctionHost {
|
|
|
90
92
|
}
|
|
91
93
|
|
|
92
94
|
export function createNativeFunctionHost(config: NativeFunctionsConfig): NativeFunctionHost {
|
|
93
|
-
const inlineBytes = config.inlineBytes ?? NATIVE_FUNCTION_DEFAULTS.inlineBytes;
|
|
95
|
+
const inlineBytes = Math.min(config.inlineBytes ?? NATIVE_FUNCTION_DEFAULTS.inlineBytes, NATIVE_FUNCTION_DEFAULTS.inlineBytes);
|
|
94
96
|
const ttl = config.resultTtlMs ?? NATIVE_FUNCTION_DEFAULTS.resultTtlMs;
|
|
95
97
|
const enabled = new Set(Object.entries(config.tools).filter(([, tool]) => tool.group === "runtime" && tool.enabled).map(([name]) => name));
|
|
96
98
|
const active = new Set<string>();
|
|
@@ -116,8 +118,10 @@ export function createNativeFunctionHost(config: NativeFunctionsConfig): NativeF
|
|
|
116
118
|
try {
|
|
117
119
|
const output = await tool.handler(call.arguments, { invocationId: call.invocationId, channel: call.channel, turnId: call.turnId, tool: call.tool, policyNames: [...call.policyNames], signal, ...(takenSender ? { takenSender } : {}) });
|
|
118
120
|
const text = JSON.stringify(output ?? null);
|
|
121
|
+
if (text === undefined) throw new TypeError("The function result must be a JSON value");
|
|
122
|
+
// Send the measured JSON value so wire serialization cannot invoke the handler's toJSON again.
|
|
123
|
+
if (encodeInlineFunctionResult(text).bytes <= inlineBytes) return { output: JSON.parse(text) };
|
|
119
124
|
const bytes = Buffer.byteLength(text);
|
|
120
|
-
if (bytes <= inlineBytes) return { output: output ?? null };
|
|
121
125
|
// Too large to send inline: keep the bytes here and hand the harness a preview and an ID.
|
|
122
126
|
const resultId = (config.newResultId ?? randomUUID)();
|
|
123
127
|
if (!RESULT_ID.test(resultId)) throw new FunctionError("result_store_failed", "The result could not be stored");
|
|
@@ -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) {
|
|
@@ -688,7 +688,8 @@ await client.openSession({ sessionId, tools: { catalog: [
|
|
|
688
688
|
repeated. `tool_call` events carry `invocationId`.
|
|
689
689
|
- **Phase.** `session/status` reports `activeTurn.phase`: `model`, `approval`
|
|
690
690
|
or `tool`, since when, and the model call, approval request or invocation ID.
|
|
691
|
-
- **Large results.**
|
|
691
|
+
- **Large results.** The default inline limit is 16384 UTF-8 bytes, including
|
|
692
|
+
the success envelope. Above that limit the host stores the output JSON
|
|
692
693
|
and returns a preview and a reference. The model reads parts with
|
|
693
694
|
`read_tool_result`; the harness accepts only IDs recorded for the requesting
|
|
694
695
|
channel and forwards the read to the host as `results/read`.
|
|
@@ -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`;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { StorageSnapshot } from "../../../contracts/storage.ts";
|
|
2
2
|
import type { FunctionCall, FunctionExecutor, ResultReference, ToolLimits, ToolOutcome, ToolRegistration } from "../../../contracts/tools.ts";
|
|
3
|
+
import { DEFAULT_INLINE_FUNCTION_RESULT_BYTES, encodeInlineFunctionResult } from "../../../contracts/tools.ts";
|
|
3
4
|
|
|
4
5
|
/** Adjustable defaults (BUSINESS_RULES.md, tools and callbacks). */
|
|
5
|
-
export const TOOL_LIMITS: Readonly<ToolLimits> = { inlineBytes:
|
|
6
|
+
export const TOOL_LIMITS: Readonly<ToolLimits> = { inlineBytes: DEFAULT_INLINE_FUNCTION_RESULT_BYTES, previewBytes: 1_024, readBytes: 16_384 };
|
|
6
7
|
|
|
7
8
|
/** The wait for a callback ended for a reason that says nothing about its
|
|
8
9
|
* effect on the host: the connection is gone. The call stays dispatched with
|
|
@@ -70,10 +71,10 @@ export async function runFunction(options: {
|
|
|
70
71
|
note: "The full result is stored. Read it in parts with read_tool_result and this result_id." }),
|
|
71
72
|
outcome: { status: "succeeded", reference: structuredClone(answer.reference) } };
|
|
72
73
|
}
|
|
73
|
-
const content = JSON.stringify(
|
|
74
|
+
const { content, bytes: inlineBytes } = encodeInlineFunctionResult(JSON.stringify((answer as { output?: unknown })?.output ?? null) ?? "null");
|
|
74
75
|
// A producer stores what does not fit and sends a reference. Bytes that
|
|
75
76
|
// arrive inline anyway cannot be kept or shown in full.
|
|
76
|
-
if (
|
|
77
|
+
if (inlineBytes > limits.inlineBytes) return failure("failed", "result_too_large", `The tool's result exceeds ${limits.inlineBytes} bytes and was not stored by its producer.`);
|
|
77
78
|
return { content, outcome: { status: "succeeded" } };
|
|
78
79
|
} catch (error) {
|
|
79
80
|
if (signal.aborted) throw signal.reason instanceof Error ? signal.reason : new Error("Turn interrupted");
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
export { HarnessClient, HarnessClientError, FunctionError } from "./interfaces/client.ts";
|
|
2
2
|
export type { FunctionHandler, ResultReader } from "./interfaces/client.ts";
|
|
3
3
|
export type { ToolRegistration, ToolCatalogInput, ToolAvailability, ToolInvocation, ToolInvocationState, ToolOutcome, ResultReference, TurnPhase, FunctionCall, FunctionResult, ResultRead, ResultPage } from "./contracts/tools.ts";
|
|
4
|
+
export { DEFAULT_INLINE_FUNCTION_RESULT_BYTES, encodeInlineFunctionResult } from "./contracts/tools.ts";
|
|
4
5
|
export { createInProcessTransport } from "./interfaces/protocol/in-process.ts";
|
|
5
6
|
export { createStdioTransport } from "./interfaces/protocol/stdio-client.ts";
|
|
6
7
|
export type { StdioConnection } from "./contracts/protocol.ts";
|
|
7
8
|
export type { ChannelEvent } from "./contracts/events.ts";
|
|
8
9
|
export type { InitializeParams, CreateParams, PushParams, NotifyParams, ProtocolConfig, ClientTransport, PendingChannelChange, ChannelChangeResult, LoadResult, StatusResult, ChannelStatusResult, ItemStatus, TurnStatus, StoredMessage } from "./contracts/protocol.ts";
|
|
10
|
+
export type { InferenceRelayGrant } from "./contracts/protocol.ts";
|
|
9
11
|
export type { ManagedConfig, ManagedModel, ModelContextBudget, ToolPolicy, ToolDecision, ItemPolicy, ApprovalRequest, ApprovalAnswer, ApprovalCloseReason } from "./contracts/config-permissions.ts";
|
|
10
12
|
export type { ContextLimitFailure, ContextBudgetMeasurement } from "./contracts/context.ts";
|
|
11
13
|
|
|
@@ -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
|
}
|
|
@@ -118,6 +118,15 @@ export type FunctionResult =
|
|
|
118
118
|
| { output: unknown; preview?: never; reference?: never }
|
|
119
119
|
| { output?: never; preview: string; reference: ResultReference };
|
|
120
120
|
|
|
121
|
+
/** Default UTF-8 byte limit for the complete inline success envelope. */
|
|
122
|
+
export const DEFAULT_INLINE_FUNCTION_RESULT_BYTES = 16_384;
|
|
123
|
+
|
|
124
|
+
/** Wrap an already serialized JSON output and measure the content the harness stores. */
|
|
125
|
+
export function encodeInlineFunctionResult(outputJson: string): { content: string; bytes: number } {
|
|
126
|
+
const content = `{"ok":true,"output":${outputJson}}`;
|
|
127
|
+
return { content, bytes: new TextEncoder().encode(content).length };
|
|
128
|
+
}
|
|
129
|
+
|
|
121
130
|
/** `results/read` parameters and result. The harness has already checked that
|
|
122
131
|
* `channel` produced `resultId`; the host serves bytes it holds. */
|
|
123
132
|
export interface ResultRead { resultId: string; invocationId: string; channel: string; offset: number; length: number }
|
|
@@ -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
|
+
}
|