@qlairoslabs/acp-client 0.13.7-e-alpha.1 → 0.13.9-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 +62 -10
- package/package.json +1 -1
- package/src/agent/config.ts +2 -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 -1
- package/src/native/errors.ts +1 -1
- package/src/native/functions.ts +8 -4
- package/src/native/host-config.ts +2 -0
- package/src/native/host.ts +6 -1
- package/src/native/inference-relay.ts +91 -26
- package/src/native/recovery.ts +6 -5
- package/src/native-harness/README.md +2 -1
- package/src/native-harness/src/capabilities/model/inference-relay.ts +70 -7
- package/src/native-harness/src/capabilities/model/runner.ts +4 -1
- package/src/native-harness/src/capabilities/tools/runtime/functions.ts +4 -3
- package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +30 -10
- package/src/native-harness/src/capabilities/tools/web/exa.ts +5 -1
- package/src/native-harness/src/capabilities/tools/web/registry.ts +14 -1
- package/src/native-harness/src/capabilities/tools/web/service-egress.ts +80 -0
- package/src/native-harness/src/client.ts +1 -0
- package/src/native-harness/src/contracts/model-execution.ts +3 -1
- package/src/native-harness/src/contracts/operator-controls.ts +1 -0
- package/src/native-harness/src/contracts/protocol.ts +3 -1
- package/src/native-harness/src/contracts/tools.ts +9 -0
- package/src/native-harness/src/contracts/web.ts +3 -0
- package/src/native-harness/src/interfaces/cli/development.ts +7 -4
- package/src/native-harness/src/interfaces/inspector/state.ts +3 -2
- package/src/native-harness/src/interfaces/protocol/server.ts +3 -1
- package/src/native-harness/src/testing.ts +11 -6
- package/src/native-harness/src/util/inference-relay.ts +11 -3
package/CONSUMER_GUIDE.md
CHANGED
|
@@ -1237,11 +1237,28 @@ For an operator-managed native inference relay, declare
|
|
|
1237
1237
|
`credentialMode: "relay"` on the `openai-compatible` model and set its
|
|
1238
1238
|
`baseUrl` to the exact relay URL. Omit `apiKeyEnv`. Supply a trusted
|
|
1239
1239
|
`harness.inferenceRelayGrant` callback. On each executable create or reopen
|
|
1240
|
-
it receives `{ sessionId, signal }` and returns
|
|
1241
|
-
`{
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1240
|
+
it receives `{ sessionId, signal }` and returns `{ baseUrl, bearerToken }`
|
|
1241
|
+
with exactly one lifetime field. Use `lifetime: { mode: "process" }` for a
|
|
1242
|
+
process-bound grant with no clock expiry, or `expiresAtMs` for a timed
|
|
1243
|
+
grant. The grant stays in memory. Keep upstream provider keys on the relay
|
|
1244
|
+
side. Prefer HTTPS. The native control connection must be trusted, and
|
|
1245
|
+
plaintext requires an isolated hop.
|
|
1246
|
+
|
|
1247
|
+
To clean up a grant after a failed executable open, return an optional opaque
|
|
1248
|
+
`grantRef` and configure `harness.onInferenceRelayOpenFailure`. The callback
|
|
1249
|
+
receives `{ grantRef, delivery }`. On `not_sent`, abandon the issuance. On
|
|
1250
|
+
`unknown`, revoke the grant because it may have reached the harness. Resolve
|
|
1251
|
+
the callback only after cleanup is confirmed. `harness.inferenceRelayCleanupMs`
|
|
1252
|
+
sets the independent deadline and defaults to 10 seconds. The reference
|
|
1253
|
+
stays on the host side.
|
|
1254
|
+
|
|
1255
|
+
If startup surfaces `relay_cleanup_unconfirmed` on the error or its cause,
|
|
1256
|
+
stop using that SDK host. Verify that the old harness execution has ended or
|
|
1257
|
+
been fenced before opening the saved session with a fresh host and process.
|
|
1258
|
+
A late cleanup acknowledgement leaves the old execution fenced. If the relay
|
|
1259
|
+
revokes the current grant, later inference needs a fresh executable open.
|
|
1260
|
+
ACP-client leaves that action to the host and never replays a relay request
|
|
1261
|
+
that may have been sent.
|
|
1245
1262
|
|
|
1246
1263
|
Set `harness.config.model.contextBudget` on OpenRouter, OpenCode Go or OpenAI-compatible models
|
|
1247
1264
|
to fit a larger inference request. For example, a model with a 128,000-token
|
|
@@ -1830,16 +1847,41 @@ harness: {
|
|
|
1830
1847
|
- **Deadlines.** `deadlineMs` on a tool overrides `defaultDeadlineMs`. When it
|
|
1831
1848
|
passes, the model receives a timeout result that says the effect is unknown,
|
|
1832
1849
|
and the turn continues.
|
|
1833
|
-
- **Large results.**
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
`
|
|
1837
|
-
|
|
1850
|
+
- **Large results.** Keep returning JSON values from handlers. ACP-client
|
|
1851
|
+
counts the UTF-8 bytes of the full inline success result, including the
|
|
1852
|
+
`{ ok: true, output }` wrapper. The default is 16 KiB. Use
|
|
1853
|
+
`harness.functions.inlineBytes` to store results earlier. Values above
|
|
1854
|
+
16 KiB are capped at 16 KiB. When a result exceeds the effective limit,
|
|
1855
|
+
ACP-client stores the output JSON in `resultDirectory` or a temporary
|
|
1856
|
+
directory removed on stop. The model receives a preview and an ID and can
|
|
1857
|
+
page through the result using `read_tool_result`. Only the producing
|
|
1858
|
+
conversation can read it. Results expire after `resultTtlMs` (24 hours by
|
|
1859
|
+
default).
|
|
1838
1860
|
- **Records.** `agent.nativeHarness.toolInvocation(id)` and
|
|
1839
1861
|
`toolInvocations(turn)` return each call's state. A call that was dispatched
|
|
1840
1862
|
but has no recorded result (crash, lost connection, interrupt) is
|
|
1841
1863
|
`interrupted` with `effect: "unknown"`. It is never run again automatically.
|
|
1842
1864
|
|
|
1865
|
+
#### Native web tools and proxy egress
|
|
1866
|
+
|
|
1867
|
+
Configure managed search and fetch with `harness.config.webSearch` and
|
|
1868
|
+
`harness.config.webFetch`. Exa resolves the configured `apiKeyEnv` from the
|
|
1869
|
+
harness environment and defaults to `EXA_API_KEY`.
|
|
1870
|
+
|
|
1871
|
+
For a hosted deployment that requires a proxy, set
|
|
1872
|
+
`HARNESS_WEB_EGRESS=proxy-required` and uppercase `HTTPS_PROXY` in the
|
|
1873
|
+
trusted harness launch environment. Use an HTTP or HTTPS proxy URL without
|
|
1874
|
+
credentials, such as `http://egress.internal:8080`. Supply the same environment
|
|
1875
|
+
on relaunch. Exa search and Exa-backed fetch use CONNECT to the fixed Exa
|
|
1876
|
+
origin, with the service credential sent inside origin TLS. Required mode
|
|
1877
|
+
ignores `NO_PROXY`, disables direct URL fetch, and never falls back to direct
|
|
1878
|
+
egress. With the mode omitted or set to `direct`, the harness connects directly
|
|
1879
|
+
and ignores ambient proxy variables.
|
|
1880
|
+
|
|
1881
|
+
An Exa result can still reach the model when the provider omits cost data.
|
|
1882
|
+
The harness reports the cost as unknown. A proxy failure produces a tool
|
|
1883
|
+
error and the turn can continue.
|
|
1884
|
+
|
|
1843
1885
|
#### Native MCP servers
|
|
1844
1886
|
|
|
1845
1887
|
Configure native servers in `harness.config.mcpServers`. The harness
|
|
@@ -2492,6 +2534,16 @@ const unsubscribe = session.subscribe((notification: AgentSessionNotification) =
|
|
|
2492
2534
|
});
|
|
2493
2535
|
```
|
|
2494
2536
|
|
|
2537
|
+
For external ACP adapters, read `session.state.sessionStartFailure` when a
|
|
2538
|
+
recoverable startup refusal leaves the connection open without a provider
|
|
2539
|
+
session. Direct controller callers can read `sessionStartFailure` on the
|
|
2540
|
+
result of `HarnessController.start()`. The optional detail carries a safe
|
|
2541
|
+
display message and the adapter's numeric JSON-RPC `rpcCode` when available.
|
|
2542
|
+
Show the message if you want to surface the failure in the app. For an
|
|
2543
|
+
adapter that reliably signals authentication is required, offer its login
|
|
2544
|
+
flow and let the caller retry on the open connection. Successful session
|
|
2545
|
+
creation or load clears the detail.
|
|
2546
|
+
|
|
2495
2547
|
`onResponseChunk` and activity callbacks are provisional live streams. A
|
|
2496
2548
|
`presentation_recorded` notification means the displayed item revision has been appended
|
|
2497
2549
|
to the V2 transcript. Its ID, first position, revision, record sequence, and operation ID
|
package/package.json
CHANGED
package/src/agent/config.ts
CHANGED
|
@@ -118,6 +118,8 @@ export interface AgentHarnessConfig {
|
|
|
118
118
|
readonly config: import("../native/reminders/routine-wire.ts").RoutineConfigInput;
|
|
119
119
|
/** Fresh secret material for each executable native harness open. */
|
|
120
120
|
readonly inferenceRelayGrant?: import("../native/inference-relay.ts").InferenceRelayGrantProvider;
|
|
121
|
+
readonly onInferenceRelayOpenFailure?: import("../native/inference-relay.ts").InferenceRelayOpenFailure;
|
|
122
|
+
readonly inferenceRelayCleanupMs?: number;
|
|
121
123
|
readonly mcpRuntimeHeaders?: import("../native/mcp.ts").McpRuntimeHeadersProvider;
|
|
122
124
|
/** The harness home, a path in the harness's environment. It must survive process restarts. */
|
|
123
125
|
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,5 +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
|
|
|
809
|
-
export type { InferenceRelayGrant, InferenceRelayGrantProvider } from "./native/inference-relay.ts";
|
|
810
|
+
export type { InferenceRelayGrant, InferenceRelayGrantProvider, InferenceRelayGrantProviderResult, InferenceRelayOpenFailure } from "./native/inference-relay.ts";
|
|
810
811
|
export type { McpRuntimeHeaders, McpRuntimeHeadersProvider, NativeInputPolicy, NativeMcpStatus } from "./native/mcp.ts";
|
package/src/native/errors.ts
CHANGED
|
@@ -31,5 +31,5 @@ export const ambiguous = (error: unknown) => { const code = codeOf(error); retur
|
|
|
31
31
|
|
|
32
32
|
export function terminalStartupError(error: unknown): error is Error {
|
|
33
33
|
return error instanceof HarnessIncompatibleError || (error instanceof Error && "code" in error &&
|
|
34
|
-
(error.code === "invalid_config" || error.code === "reminder_batch_retry_exhausted"));
|
|
34
|
+
(error.code === "invalid_config" || error.code === "reminder_batch_retry_exhausted" || error.code === "relay_cleanup_unconfirmed"));
|
|
35
35
|
}
|
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");
|
|
@@ -31,6 +31,8 @@ export interface NativeHarnessHostConfig {
|
|
|
31
31
|
readonly config: RoutineConfigInput;
|
|
32
32
|
/** Fresh secret material for each executable native harness open. */
|
|
33
33
|
readonly inferenceRelayGrant?: import("./inference-relay.ts").InferenceRelayGrantProvider;
|
|
34
|
+
readonly onInferenceRelayOpenFailure?: import("./inference-relay.ts").InferenceRelayOpenFailure;
|
|
35
|
+
readonly inferenceRelayCleanupMs?: number;
|
|
34
36
|
readonly mcpRuntimeHeaders?: import("./mcp.ts").McpRuntimeHeadersProvider;
|
|
35
37
|
/** The harness home, a path in the harness's environment. Must survive process restarts. */
|
|
36
38
|
readonly home: string;
|
package/src/native/host.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RelayIssuanceFence } from "./inference-relay.ts";
|
|
1
2
|
import type { NativeConnection, NativeHarnessHostConfig } from "./host-config.ts";
|
|
2
3
|
export type { NativeConnection, NativeHarnessHostConfig, NativeApprovalRequest, NativeApprovalResponder } from "./host-config.ts";
|
|
3
4
|
import { idleMilliseconds, ReminderIdleSupervisor } from "./reminders/idle.ts";
|
|
@@ -86,6 +87,7 @@ export class NativeHarnessHost {
|
|
|
86
87
|
readonly sessionId: string;
|
|
87
88
|
readonly records: NativeHostRecords;
|
|
88
89
|
#config: NativeHarnessHostConfig;
|
|
90
|
+
#relayFence: RelayIssuanceFence;
|
|
89
91
|
#restartTransition?: Promise<void>;
|
|
90
92
|
readonly #log: Logger;
|
|
91
93
|
reminderSync?: ReminderSync;
|
|
@@ -188,6 +190,7 @@ export class NativeHarnessHost {
|
|
|
188
190
|
|
|
189
191
|
constructor(config: NativeHarnessHostConfig, channels?: ChannelPersistence, workerDelivery?: WorkerDeliveryRepository) {
|
|
190
192
|
this.#config = config;
|
|
193
|
+
this.#relayFence = new RelayIssuanceFence(config.inferenceRelayCleanupMs);
|
|
191
194
|
this.sessionId = config.sessionId;
|
|
192
195
|
this.#log = config.logger ?? noopLogger;
|
|
193
196
|
this.#approvals = new NativeApprovals(config.approvalResponder, this.#log);
|
|
@@ -422,6 +425,7 @@ export class NativeHarnessHost {
|
|
|
422
425
|
const deadline = new AbortController();
|
|
423
426
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
424
427
|
try {
|
|
428
|
+
await this.#relayFence.awaitIdle();
|
|
425
429
|
const opening = (async () => {
|
|
426
430
|
connection = await (this.#config.connect ?? (() => launchNativeConnection(this.#config, this.#log)))();
|
|
427
431
|
this.launches += 1;
|
|
@@ -460,6 +464,7 @@ export class NativeHarnessHost {
|
|
|
460
464
|
// A failed start is reported to whoever needed the harness. It is not retried automatically:
|
|
461
465
|
// the next use tries again. Only a loss with work outstanding is reopened by the host itself.
|
|
462
466
|
this.#setState("stopped");
|
|
467
|
+
if (deadline.signal.aborted) await this.#relayFence.awaitIdle();
|
|
463
468
|
throw error;
|
|
464
469
|
} finally {
|
|
465
470
|
clearTimeout(timer);
|
|
@@ -514,7 +519,7 @@ export class NativeHarnessHost {
|
|
|
514
519
|
// can run. An edit made after this line is sent through the live channel methods once open.
|
|
515
520
|
const batch = await this.#changes.startupBatch(signal);
|
|
516
521
|
await this.reminderSync?.initialize(initialized.description);
|
|
517
|
-
const opened = await openOrCreate(client, this.#config, batch, functions?.catalog(), signal, this.reminderSync);
|
|
522
|
+
const opened = await openOrCreate(client, this.#config, batch, functions?.catalog(), signal, this.reminderSync, this.#relayFence);
|
|
518
523
|
for (const event of earlyReminders.splice(0)) reminderEvent(event);
|
|
519
524
|
await this.reminderSync?.settled();
|
|
520
525
|
signal.throwIfAborted();
|
|
@@ -2,34 +2,99 @@ import { HarnessClientError, type InferenceRelayGrant } from "../native-harness/
|
|
|
2
2
|
import { codeOf } from "./errors.ts";
|
|
3
3
|
|
|
4
4
|
export type { InferenceRelayGrant } from "../native-harness/src/client.ts";
|
|
5
|
-
|
|
6
|
-
/** Trusted host hook. Return fresh runtime authority for this executable open. */
|
|
5
|
+
export type InferenceRelayGrantProviderResult = InferenceRelayGrant & { grantRef?: string };
|
|
7
6
|
export type InferenceRelayGrantProvider = (context: { sessionId: string; signal: AbortSignal }) =>
|
|
8
|
-
|
|
7
|
+
InferenceRelayGrantProviderResult | undefined | Promise<InferenceRelayGrantProviderResult | undefined>;
|
|
8
|
+
export type InferenceRelayOpenFailure = (context: { grantRef: string; delivery: "not_sent" | "unknown" }) => void | Promise<void>;
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
10
|
+
const unconfirmed = () => new HarnessClientError("relay_cleanup_unconfirmed", "Inference relay cleanup unconfirmed");
|
|
11
|
+
function bounded<T>(promise: Promise<T>, ms: number): Promise<T> {
|
|
12
|
+
return new Promise((resolve, reject) => {
|
|
13
|
+
const timer = setTimeout(() => reject(unconfirmed()), ms);
|
|
14
|
+
promise.then(value => { clearTimeout(timer); resolve(value); }, error => { clearTimeout(timer); reject(error); });
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class RelayIssuanceFence {
|
|
19
|
+
readonly #pending = new Set<Promise<unknown>>();
|
|
20
|
+
readonly #cleanups = new Set<Promise<void>>();
|
|
21
|
+
#blocked = false;
|
|
22
|
+
readonly ms: number;
|
|
23
|
+
|
|
24
|
+
constructor(ms = 10_000) {
|
|
25
|
+
if (!Number.isInteger(ms) || ms < 1 || ms > 2_147_483_647)
|
|
26
|
+
throw new HarnessClientError("invalid_config", "Invalid inference relay cleanup deadline");
|
|
27
|
+
this.ms = ms;
|
|
19
28
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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");
|
|
29
|
+
|
|
30
|
+
track<T>(operation: Promise<T>): Promise<T> {
|
|
31
|
+
const tracked = operation.finally(() => this.#pending.delete(tracked));
|
|
32
|
+
this.#pending.add(tracked);
|
|
33
|
+
return tracked;
|
|
34
34
|
}
|
|
35
|
+
|
|
36
|
+
async awaitIdle() {
|
|
37
|
+
if (this.#blocked) throw unconfirmed();
|
|
38
|
+
try { await bounded(Promise.allSettled([...this.#pending]), this.ms); }
|
|
39
|
+
catch {
|
|
40
|
+
// A cleanup that began near the end of the issuance wait still owns
|
|
41
|
+
// its separate deadline. An acquisition that never returned is fenced.
|
|
42
|
+
if (this.#cleanups.size) await Promise.allSettled([...this.#cleanups]);
|
|
43
|
+
else this.#blocked = true;
|
|
44
|
+
}
|
|
45
|
+
if (this.#blocked) throw unconfirmed();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async cleanup(hook: InferenceRelayOpenFailure, grantRef: string, delivery: "not_sent" | "unknown") {
|
|
49
|
+
const task = bounded(Promise.resolve().then(() => hook({ grantRef, delivery })), this.ms);
|
|
50
|
+
this.#cleanups.add(task);
|
|
51
|
+
try { await task; }
|
|
52
|
+
catch { this.#blocked = true; throw unconfirmed(); }
|
|
53
|
+
finally { this.#cleanups.delete(task); }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function executableRelayOpen<T>(provider: InferenceRelayGrantProvider | undefined,
|
|
58
|
+
sessionId: string, signal: AbortSignal, send: (grant: InferenceRelayGrant | undefined, markSent: () => void) => Promise<T>,
|
|
59
|
+
cleanup?: InferenceRelayOpenFailure, fence = new RelayIssuanceFence()): Promise<T> {
|
|
60
|
+
if (!provider) return send(undefined, () => {});
|
|
61
|
+
await fence.awaitIdle();
|
|
62
|
+
signal.throwIfAborted();
|
|
63
|
+
return fence.track((async () => {
|
|
64
|
+
let result: InferenceRelayGrantProviderResult | undefined;
|
|
65
|
+
try { result = await provider({ sessionId, signal }); }
|
|
66
|
+
catch {
|
|
67
|
+
signal.throwIfAborted();
|
|
68
|
+
throw new HarnessClientError("invalid_config", "Could not obtain native inference relay grant");
|
|
69
|
+
}
|
|
70
|
+
if (result === undefined) { signal.throwIfAborted(); return send(undefined, () => {}); }
|
|
71
|
+
let delivery: "not_sent" | "unknown" = "not_sent";
|
|
72
|
+
const reference = result?.grantRef;
|
|
73
|
+
const validRef = typeof reference === "string" && !!reference.trim() && Buffer.byteLength(reference) <= 256 && !/[\p{Cc}\p{Cf}]/u.test(reference);
|
|
74
|
+
try {
|
|
75
|
+
signal.throwIfAborted();
|
|
76
|
+
if (reference !== undefined && !validRef)
|
|
77
|
+
throw new HarnessClientError("invalid_config", "Inference relay grant is invalid");
|
|
78
|
+
const { baseUrl, bearerToken } = result;
|
|
79
|
+
const numeric = Object.hasOwn(result, "expiresAtMs"), process = Object.hasOwn(result, "lifetime");
|
|
80
|
+
if (numeric === process || (numeric && !Number.isSafeInteger(result.expiresAtMs)) ||
|
|
81
|
+
(process && (!result.lifetime || Array.isArray(result.lifetime) || !Object.hasOwn(result.lifetime, "mode") || result.lifetime.mode !== "process" || Object.keys(result.lifetime).length !== 1)))
|
|
82
|
+
throw new HarnessClientError("invalid_config", "Inference relay grant is invalid");
|
|
83
|
+
const grant: InferenceRelayGrant = process ? { baseUrl, bearerToken, lifetime: { mode: "process" } }
|
|
84
|
+
: { baseUrl, bearerToken, expiresAtMs: result.expiresAtMs! };
|
|
85
|
+
const opened = await send(grant, () => { signal.throwIfAborted(); delivery = "unknown"; });
|
|
86
|
+
signal.throwIfAborted();
|
|
87
|
+
return opened;
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (cleanup && validRef) await fence.cleanup(cleanup, reference, delivery);
|
|
90
|
+
signal.throwIfAborted();
|
|
91
|
+
const code = codeOf(error);
|
|
92
|
+
const allowed = ["not_found", "timeout", "transport_closed", "closed", "storage_failure", "invalid_config",
|
|
93
|
+
"invalid_params", "incompatible", "busy", "already_exists"];
|
|
94
|
+
const message = error instanceof Error ? error.message : "";
|
|
95
|
+
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);
|
|
96
|
+
throw new HarnessClientError(code && allowed.includes(code) ? code : "invalid_config",
|
|
97
|
+
safe ? message.replace(/^Error: /, "") : "Native inference relay open failed");
|
|
98
|
+
}
|
|
99
|
+
})());
|
|
35
100
|
}
|
package/src/native/recovery.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { executableRelayOpen, type InferenceRelayGrantProvider } from "./inference-relay.ts";
|
|
1
|
+
import { executableRelayOpen, type InferenceRelayGrantProvider, type InferenceRelayOpenFailure, type RelayIssuanceFence } from "./inference-relay.ts";
|
|
2
2
|
import { executableMcpOpen, type McpRuntimeHeadersProvider } from "./mcp.ts";
|
|
3
3
|
import { activatesRoutine, RoutineAdmission } from "./reminders/routine-guard.ts";
|
|
4
4
|
import type { ReminderChange } from "../persistence/reminders.ts";
|
|
@@ -53,8 +53,8 @@ export async function readCompleteMessage(client: HarnessClient, messageId: stri
|
|
|
53
53
|
|
|
54
54
|
/** The catalog and startup edits are installed before recovered work can start. */
|
|
55
55
|
export async function openOrCreate(
|
|
56
|
-
client: HarnessClient, config: { sessionId: string; config?: RoutineConfigInput; mcpRuntimeHeaders?: McpRuntimeHeadersProvider; inferenceRelayGrant?: InferenceRelayGrantProvider },
|
|
57
|
-
batch: PendingChannelChange[], tools: Parameters<HarnessClient["openSession"]>[0]["tools"], signal: AbortSignal, reminders?: ReminderSync,
|
|
56
|
+
client: HarnessClient, config: { sessionId: string; config?: RoutineConfigInput; mcpRuntimeHeaders?: McpRuntimeHeadersProvider; inferenceRelayGrant?: InferenceRelayGrantProvider; onInferenceRelayOpenFailure?: InferenceRelayOpenFailure },
|
|
57
|
+
batch: PendingChannelChange[], tools: Parameters<HarnessClient["openSession"]>[0]["tools"], signal: AbortSignal, reminders?: ReminderSync, relayFence?: RelayIssuanceFence,
|
|
58
58
|
) {
|
|
59
59
|
const admission = reminders?.routineAdmission ?? new RoutineAdmission();
|
|
60
60
|
admission.configForOpen(config.config); // Validate before marking any journal entry maybe sent.
|
|
@@ -73,10 +73,11 @@ export async function openOrCreate(
|
|
|
73
73
|
sessionId: config.sessionId, config: admission.configForOpen(config.config), ...changes,
|
|
74
74
|
...(staged.length ? { reminderChanges: staged } : {}),
|
|
75
75
|
};
|
|
76
|
-
const send = (request: typeof params) => executableRelayOpen(config.inferenceRelayGrant, config.sessionId, signal, grant => executableMcpOpen(config.mcpRuntimeHeaders, signal, material => {
|
|
76
|
+
const send = (request: typeof params) => executableRelayOpen(config.inferenceRelayGrant, config.sessionId, signal, (grant, markSent) => executableMcpOpen(config.mcpRuntimeHeaders, signal, material => {
|
|
77
77
|
const executable = { ...request, ...(grant === undefined ? {} : { inferenceRelayGrant: grant }), ...(material === undefined ? {} : { mcpRuntimeHeaders: material }) };
|
|
78
|
+
if (grant) markSent();
|
|
78
79
|
return create ? client.createSession({ ...executable, participants: [], channels: {} }) : client.openSession(executable);
|
|
79
|
-
}));
|
|
80
|
+
}), config.onInferenceRelayOpenFailure, relayFence);
|
|
80
81
|
try {
|
|
81
82
|
return await send(params);
|
|
82
83
|
} 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`.
|
|
@@ -7,27 +7,86 @@ const expired = {
|
|
|
7
7
|
diagnostic: { provider: "chat_completions", category: "relay_expired" },
|
|
8
8
|
} as const;
|
|
9
9
|
|
|
10
|
+
export function createRelayAuthority(initial: InferenceRelayGrant) {
|
|
11
|
+
let current = { grant: initial, revoked: false };
|
|
12
|
+
return {
|
|
13
|
+
capture: () => current,
|
|
14
|
+
replace(grant: InferenceRelayGrant) { current = { grant, revoked: false }; },
|
|
15
|
+
revoke(captured: typeof current) { if (current === captured) current.revoked = true; },
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export type RelayAuthority = ReturnType<typeof createRelayAuthority>;
|
|
19
|
+
|
|
20
|
+
const refusals = new Map([
|
|
21
|
+
["native_grant_revoked", 401], ["native_authentication_required", 401],
|
|
22
|
+
["native_source_rejected", 403], ["native_admission_rejected", 403], ["native_policy_mismatch", 403],
|
|
23
|
+
["native_allowance_exhausted", 429], ["native_provider_authentication_failed", 502],
|
|
24
|
+
["native_provider_model_failed", 502], ["native_unavailable", 503],
|
|
25
|
+
]);
|
|
26
|
+
async function relayRefusal(response: { status: number; body: ReadableStream<Uint8Array> | null }) {
|
|
27
|
+
if (!response.body) return;
|
|
28
|
+
const reader = response.body.getReader();
|
|
29
|
+
const decoder = new TextDecoder();
|
|
30
|
+
let remaining = 16 * 1024, text = "";
|
|
31
|
+
const deadline = Promise.withResolvers<undefined>();
|
|
32
|
+
const timer = setTimeout(() => deadline.resolve(undefined), 1000);
|
|
33
|
+
try {
|
|
34
|
+
for (;;) {
|
|
35
|
+
const next = await Promise.race([reader.read(), deadline.promise]);
|
|
36
|
+
if (!next) return;
|
|
37
|
+
if (next.done) break;
|
|
38
|
+
remaining -= next.value.byteLength;
|
|
39
|
+
if (remaining < 0) return;
|
|
40
|
+
text += decoder.decode(next.value, { stream: true });
|
|
41
|
+
}
|
|
42
|
+
const type: unknown = JSON.parse(text + decoder.decode())?.error?.type;
|
|
43
|
+
if (typeof type === "string" && refusals.get(type) === response.status) return type;
|
|
44
|
+
} catch { return; }
|
|
45
|
+
finally { clearTimeout(timer); void reader.cancel().catch(() => {}); reader.releaseLock(); }
|
|
46
|
+
}
|
|
47
|
+
|
|
10
48
|
/** A relay attempt owns its direct dispatcher and releases it on any terminal
|
|
11
49
|
* event, including cancellation by the model runner. */
|
|
12
|
-
export function inferenceRelayAttempt(model: string,
|
|
50
|
+
export function inferenceRelayAttempt(model: string, authority: RelayAuthority,
|
|
13
51
|
metadata?: Parameters<typeof openAICompatibleAttempt>[5]): ModelAttempt {
|
|
14
52
|
return async function* (request, signal) {
|
|
15
|
-
|
|
53
|
+
const captured = authority.capture(), { grant } = captured;
|
|
54
|
+
const isExpired = () => grant.expiresAtMs !== undefined && Date.now() >= grant.expiresAtMs;
|
|
55
|
+
const refusalEvent = (reason: string) => ({
|
|
56
|
+
type: "failure", kind: "provider", message: "Inference relay refused",
|
|
57
|
+
diagnostic: { provider: "chat_completions", category: "relay_refusal", reason }, noRetry: true,
|
|
58
|
+
}) as const;
|
|
59
|
+
if (captured.revoked) { yield refusalEvent("native_grant_revoked"); return; }
|
|
60
|
+
if (isExpired()) { yield expired; return; }
|
|
16
61
|
// Bun's package-name shim can use global, proxy-aware fetch. An explicit
|
|
17
62
|
// unshimmed dispatcher sends this request only to the validated origin.
|
|
18
63
|
const undici: typeof import("undici") = await import(new URL("index.js", import.meta.resolve("undici/package.json")).href);
|
|
19
64
|
const dispatcher = new undici.Agent({ connect: { rejectUnauthorized: true } });
|
|
20
|
-
let
|
|
65
|
+
let closing: Promise<void> | undefined;
|
|
66
|
+
const close = () => closing ??= dispatcher.destroy().catch(() => {});
|
|
67
|
+
const abort = () => { void close(); };
|
|
68
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
69
|
+
if (signal.aborted) abort();
|
|
70
|
+
let dispatchExpired = false, dispatched = false;
|
|
71
|
+
let refusal: string | undefined;
|
|
21
72
|
const directFetch = (async (input: unknown, init?: RequestInit) => {
|
|
22
|
-
if (
|
|
73
|
+
if (isExpired()) {
|
|
23
74
|
dispatchExpired = true;
|
|
24
75
|
throw new Error(expired.message);
|
|
25
76
|
}
|
|
26
|
-
|
|
77
|
+
if (authority.capture() !== captured) { refusal = "native_unavailable"; throw new Error("Inference relay replaced"); }
|
|
78
|
+
if (captured.revoked) { refusal = "native_grant_revoked"; throw new Error("Inference relay revoked"); }
|
|
79
|
+
(init?.signal ?? signal).throwIfAborted();
|
|
80
|
+
dispatched = true;
|
|
81
|
+
const response = await undici.fetch(String(input), {
|
|
27
82
|
method: "POST", body: String(init?.body),
|
|
28
83
|
headers: Object.fromEntries(new Headers(init?.headers)), signal: init?.signal ?? undefined,
|
|
29
84
|
redirect: "manual", dispatcher,
|
|
30
85
|
});
|
|
86
|
+
if (response.ok) return response;
|
|
87
|
+
refusal = await relayRefusal(response);
|
|
88
|
+
if (refusal === "native_grant_revoked") authority.revoke(captured);
|
|
89
|
+
return new Response(null, { status: response.status });
|
|
31
90
|
}) as unknown as typeof fetch;
|
|
32
91
|
const attempt = openAICompatibleAttempt(grant.baseUrl, model, grant.bearerToken, directFetch, undefined, metadata);
|
|
33
92
|
const token = grant.bearerToken;
|
|
@@ -37,6 +96,7 @@ export function inferenceRelayAttempt(model: string, grant: InferenceRelayGrant,
|
|
|
37
96
|
try {
|
|
38
97
|
for await (const event of attempt(request, signal)) {
|
|
39
98
|
if (dispatchExpired) { yield expired; return; }
|
|
99
|
+
if (refusal) { yield refusalEvent(refusal); return; }
|
|
40
100
|
if (event.type === "text_delta") {
|
|
41
101
|
// Retain only a possible partial credential across provider frames.
|
|
42
102
|
pending = redact(pending + event.text);
|
|
@@ -58,8 +118,11 @@ export function inferenceRelayAttempt(model: string, grant: InferenceRelayGrant,
|
|
|
58
118
|
content: event.response.content === null ? null : redact(event.response.content) } };
|
|
59
119
|
return;
|
|
60
120
|
}
|
|
61
|
-
yield event;
|
|
121
|
+
yield event.type === "failure" && dispatched ? { ...event, noRetry: true } : event;
|
|
62
122
|
}
|
|
63
|
-
} finally {
|
|
123
|
+
} finally {
|
|
124
|
+
signal.removeEventListener("abort", abort);
|
|
125
|
+
await close();
|
|
126
|
+
}
|
|
64
127
|
};
|
|
65
128
|
}
|
|
@@ -23,6 +23,9 @@ 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_refusal" && typeof diagnostic.reason === "string" &&
|
|
27
|
+
/^(?:native_grant_revoked|native_authentication_required|native_source_rejected|native_admission_rejected|native_policy_mismatch|native_allowance_exhausted|native_provider_authentication_failed|native_provider_model_failed|native_unavailable)$/.test(diagnostic.reason))
|
|
28
|
+
return `Inference relay refused: ${diagnostic.reason}`;
|
|
26
29
|
if (diagnostic.category === "relay_expired" && diagnostic.provider === "chat_completions") return "Inference relay credential expired";
|
|
27
30
|
if (diagnostic.category === "transport") return `${provider} transport failed`;
|
|
28
31
|
if (diagnostic.category === "redirect") return `${provider} redirect refused`;
|
|
@@ -145,7 +148,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
|
|
|
145
148
|
const context = parseContextLimitFailure(`context_limit:${JSON.stringify(terminal.contextFailure)}`);
|
|
146
149
|
if (context) return finish("failed", "Model context limit exceeded", undefined, context);
|
|
147
150
|
}
|
|
148
|
-
if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) {
|
|
151
|
+
if (failure !== "transient" || (terminal?.type === "failure" && terminal.noRetry) || output || ordinal >= Math.min(1, settings.maxRetries)) {
|
|
149
152
|
const candidate = terminal?.type === "failure" ? terminal.providerFailure : undefined;
|
|
150
153
|
const providerFailure = typeof candidate === "string" &&
|
|
151
154
|
/^OpenCode Go HTTP (?:[45][0-9]{2}(?: \((?:missing_session_id|invalid_api_key|access_denied|rate_limited)\))?|3[0-9]{2} \(redirect_refused\))$/.test(candidate)
|
|
@@ -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,5 +1,6 @@
|
|
|
1
|
+
import { fixedServiceTransport, type ServiceEgress } from "./service-egress.ts";
|
|
1
2
|
import { request } from "node:https";
|
|
2
|
-
import { Transform, Writable, type TransformCallback } from "node:stream";
|
|
3
|
+
import { Transform, Writable, type Readable, type TransformCallback } from "node:stream";
|
|
3
4
|
import { pipeline } from "node:stream/promises";
|
|
4
5
|
import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
|
|
5
6
|
import type { ExaTransport } from "./exa.ts";
|
|
@@ -14,6 +15,19 @@ export function boundedBytes(max: number): Transform {
|
|
|
14
15
|
if (total > max) done(new ExaResponseLimit("Exa response exceeds size limit")); else done(null, chunk);
|
|
15
16
|
} });
|
|
16
17
|
}
|
|
18
|
+
async function readExaBody(stream: Readable, header: string | string[] | undefined, signal: AbortSignal) {
|
|
19
|
+
const encoding = typeof header === "string" ? header.trim().toLowerCase() : header === undefined ? "identity" : "";
|
|
20
|
+
const decoder = encoding === "gzip" ? createGunzip() : encoding === "deflate" ? createInflate()
|
|
21
|
+
: encoding === "br" ? createBrotliDecompress() : undefined;
|
|
22
|
+
if (!decoder && encoding !== "identity") { stream.destroy(); throw new Error("Unsupported Exa content encoding"); }
|
|
23
|
+
const chunks: Buffer[] = [];
|
|
24
|
+
const sink = new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done(); } });
|
|
25
|
+
if (decoder) await pipeline(stream, boundedBytes(cap), decoder, boundedBytes(cap), sink, { signal });
|
|
26
|
+
else await pipeline(stream, boundedBytes(cap), sink, { signal });
|
|
27
|
+
try { return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown; }
|
|
28
|
+
catch { return undefined; }
|
|
29
|
+
}
|
|
30
|
+
|
|
17
31
|
/** Fixed Exa origin: no redirects, proxy forwarding, cookies or source-site secrets. */
|
|
18
32
|
/** Injection is an assembly-only offline test seam, not managed configuration. */
|
|
19
33
|
export function createExaHttpsTransport(send: typeof request = request): ExaTransport {
|
|
@@ -22,16 +36,8 @@ export function createExaHttpsTransport(send: typeof request = request): ExaTran
|
|
|
22
36
|
const req = send({ protocol: "https:", hostname: "api.exa.ai", port: 443, method: "POST", path, signal,
|
|
23
37
|
headers: { "content-type": "application/json", "accept": "application/json", "accept-encoding": "gzip, deflate, br", "content-length": Buffer.byteLength(payload), "x-api-key": key } }, async response => {
|
|
24
38
|
const status = response.statusCode ?? 0;
|
|
25
|
-
const encoding = response.headers["content-encoding"]?.trim().toLowerCase() ?? "identity";
|
|
26
|
-
const decoder = encoding === "gzip" ? createGunzip() : encoding === "deflate" ? createInflate() : encoding === "br" ? createBrotliDecompress() : undefined;
|
|
27
|
-
if (!decoder && encoding !== "identity") { response.destroy(); reject(new Error("Unsupported Exa content encoding")); return; }
|
|
28
|
-
const chunks: Buffer[] = [];
|
|
29
|
-
const sink = new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done(); } });
|
|
30
39
|
try {
|
|
31
|
-
|
|
32
|
-
else await pipeline(response, boundedBytes(cap), boundedBytes(cap), sink, { signal });
|
|
33
|
-
let parsed: unknown; try { parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { parsed = undefined; }
|
|
34
|
-
resolve({ status, body: parsed });
|
|
40
|
+
resolve({ status, body: await readExaBody(response, response.headers["content-encoding"], signal) });
|
|
35
41
|
} catch (error) { reject(error); }
|
|
36
42
|
});
|
|
37
43
|
req.on("error", reject);
|
|
@@ -39,3 +45,17 @@ export function createExaHttpsTransport(send: typeof request = request): ExaTran
|
|
|
39
45
|
});
|
|
40
46
|
}
|
|
41
47
|
export const exaHttpsTransport = createExaHttpsTransport();
|
|
48
|
+
|
|
49
|
+
export function exaServiceTransport(egress: ServiceEgress, origin = "https://api.exa.ai", fixtureCa?: string): ExaTransport {
|
|
50
|
+
const send = fixedServiceTransport(origin, egress, fixtureCa);
|
|
51
|
+
return async ({ path, key, body, signal }) => {
|
|
52
|
+
const payload = JSON.stringify(body);
|
|
53
|
+
const { response, close } = await send(path, {
|
|
54
|
+
"content-type": "application/json", accept: "application/json", "accept-encoding": "gzip, deflate, br",
|
|
55
|
+
"content-length": String(Buffer.byteLength(payload)), "x-api-key": key,
|
|
56
|
+
}, payload, signal);
|
|
57
|
+
try {
|
|
58
|
+
return { status: response.statusCode, body: await readExaBody(response.body, response.headers["content-encoding"], signal) };
|
|
59
|
+
} finally { await close(); }
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ServiceTransportError } from "./service-egress.ts";
|
|
1
2
|
import { ExaResponseLimit } from "./exa-transport.ts";
|
|
2
3
|
import { directUrl } from "./direct-address.ts";
|
|
3
4
|
import { fetchPreview, searchPreview, type WebHit } from "./preview.ts";
|
|
@@ -66,6 +67,9 @@ export async function runExa(input: { operation: "web_search" | "web_fetch"; arg
|
|
|
66
67
|
if (input.key && url!.includes(input.key)) return failed("page_unavailable", usage);
|
|
67
68
|
const content = fetchPreview({ url: url!, title: typeof results[0].title === "string" ? redact(results[0].title) : null, text: redact(results[0].text), truncated: false, coverage: "unknown" });
|
|
68
69
|
return content === undefined ? failed("result_too_large", usage) : { ok: true, content, usage };
|
|
69
|
-
} catch (error) {
|
|
70
|
+
} catch (error) {
|
|
71
|
+
const result = failed(cause ?? (error instanceof ExaResponseLimit ? "response_too_large" : "provider_error"));
|
|
72
|
+
return !result.ok && !cause && error instanceof ServiceTransportError ? { ...result, message: error.message } : result;
|
|
73
|
+
}
|
|
70
74
|
finally { clearTimeout(timeout); input.signal?.removeEventListener("abort", abort); }
|
|
71
75
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ServiceEgress } from "./service-egress.ts";
|
|
1
2
|
import { fetchDirect } from "./direct.ts";
|
|
2
3
|
import { DirectHttpError } from "./direct-address.ts";
|
|
3
4
|
import type { CheckedWebRegistration } from "../../../contracts/web.ts";
|
|
@@ -8,9 +9,21 @@ import { runExa, type ExaTransport, type WebResponse } from "./exa.ts";
|
|
|
8
9
|
|
|
9
10
|
/** Adapter implementations are supplied by the trusted assembly, never config. */
|
|
10
11
|
export type DirectFetch = (url: string, signal: AbortSignal, deadlineMs: number) => Promise<WebResponse>;
|
|
12
|
+
export function webUnavailable(config: WebConfig, egress: ServiceEgress): import("../../../contracts/web.ts").WebUnavailable {
|
|
13
|
+
if (egress.mode === "unavailable") return {
|
|
14
|
+
...(config.webSearch ? { web_search: egress.reason } : {}),
|
|
15
|
+
...(config.webFetch ? { web_fetch: egress.reason } : {}),
|
|
16
|
+
};
|
|
17
|
+
return egress.mode === "proxy-required" && config.webFetch?.backend === "http"
|
|
18
|
+
? { web_fetch: "direct_fetch_requires_direct_egress" } : {};
|
|
19
|
+
}
|
|
20
|
+
|
|
11
21
|
/** Build once per executable open; credentials remain inside executor closures. */
|
|
12
22
|
export function createWebRegistry(config: WebConfig, env: Readonly<Record<string, string | undefined>>,
|
|
13
|
-
providers: { exa: ExaTransport; http?: DirectFetch }): Validated<readonly CheckedWebRegistration[]> {
|
|
23
|
+
providers: { exa: ExaTransport; http?: DirectFetch }, egress: ServiceEgress = { mode: "direct" }): Validated<readonly CheckedWebRegistration[]> {
|
|
24
|
+
if (egress.mode === "unavailable") config = {};
|
|
25
|
+
else if (egress.mode === "proxy-required" && config.webFetch?.backend === "http")
|
|
26
|
+
config = { ...config, webFetch: undefined };
|
|
14
27
|
const credentials = resolveWebCredentials(config, env);
|
|
15
28
|
if (!credentials.ok) return credentials;
|
|
16
29
|
if (config.webFetch?.backend === "http" && !providers.http) return { ok: false, error: { code: "invalid_config", message: "HTTP fetch adapter is unavailable" } };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { Socket, isIP } from "node:net";
|
|
2
|
+
import { checkServerIdentity } from "node:tls";
|
|
3
|
+
export type ServiceEgress =
|
|
4
|
+
| { mode: "direct" }
|
|
5
|
+
| { mode: "proxy-required"; proxy: string }
|
|
6
|
+
| { mode: "unavailable"; reason: "invalid_egress_mode" | "invalid_egress_proxy" };
|
|
7
|
+
|
|
8
|
+
export function resolveServiceEgress(environment: Readonly<Record<string, string | undefined>>): ServiceEgress {
|
|
9
|
+
const mode = environment.HARNESS_WEB_EGRESS;
|
|
10
|
+
if (mode === undefined || mode === "direct") return { mode: "direct" };
|
|
11
|
+
if (mode !== "proxy-required") return { mode: "unavailable", reason: "invalid_egress_mode" };
|
|
12
|
+
const raw = environment.HTTPS_PROXY;
|
|
13
|
+
if (raw && /^https?:\/\/[a-z\d.:[\]-]+\/?$/i.test(raw)) {
|
|
14
|
+
const url = URL.parse(raw);
|
|
15
|
+
if (url?.hostname && url.pathname === "/" && !url.username && !url.password) {
|
|
16
|
+
const rawHost = raw.replace(/^https?:\/\//i, "").replace(/\/$/, "").replace(/:\d+$/, "");
|
|
17
|
+
if (isIP(url.hostname) !== 4 || rawHost === url.hostname) return { mode, proxy: url.origin };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return { mode: "unavailable", reason: "invalid_egress_proxy" };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class ServiceTransportError extends Error {}
|
|
24
|
+
export function fixedServiceTransport(origin: string, egress: ServiceEgress, fixtureCa?: string) {
|
|
25
|
+
const destination = new URL(origin);
|
|
26
|
+
if (destination.protocol !== "https:" || destination.origin !== origin) throw new Error("Expected fixed HTTPS origin");
|
|
27
|
+
return async (path: string, headers: Record<string, string>, body: string, signal: AbortSignal) => {
|
|
28
|
+
if (!/^\/[a-z\d/_-]+$/i.test(path) || path.includes("//") ||
|
|
29
|
+
Object.keys(headers).some(name => /^(host|connection|upgrade|transfer-encoding|forwarded|x-forwarded-.*|proxy-.*)$/i.test(name)))
|
|
30
|
+
throw new ServiceTransportError("Service request routing refused");
|
|
31
|
+
if (egress.mode === "unavailable") throw new ServiceTransportError("Service egress unavailable");
|
|
32
|
+
signal.throwIfAborted();
|
|
33
|
+
const undici: typeof import("undici") = await import(new URL("index.js", import.meta.resolve("undici/package.json")).href);
|
|
34
|
+
const tls = (url: URL) => ({
|
|
35
|
+
rejectUnauthorized: true, ca: fixtureCa,
|
|
36
|
+
checkServerIdentity: (_: string, peer: Parameters<typeof checkServerIdentity>[1]) =>
|
|
37
|
+
checkServerIdentity(url.hostname.replace(/^\[|\]$/g, ""), peer),
|
|
38
|
+
});
|
|
39
|
+
const proxy = egress.mode === "proxy-required" ? new undici.Client(egress.proxy, {
|
|
40
|
+
maxHeaderSize: 16 * 1024, connect: tls(new URL(egress.proxy)), allowH2: false,
|
|
41
|
+
}) : undefined;
|
|
42
|
+
let tunnel: Awaited<ReturnType<typeof proxySocket>> | undefined;
|
|
43
|
+
async function proxySocket(client: NonNullable<typeof proxy>) {
|
|
44
|
+
try {
|
|
45
|
+
const authority = `${destination.hostname}:${destination.port || "443"}`;
|
|
46
|
+
const connected = await client.connect({ path: authority, headers: { host: authority }, signal });
|
|
47
|
+
connected.socket.on("error", () => {});
|
|
48
|
+
if (connected.statusCode < 200 || connected.statusCode >= 300) {
|
|
49
|
+
connected.socket.destroy();
|
|
50
|
+
throw new ServiceTransportError("Service CONNECT refused");
|
|
51
|
+
}
|
|
52
|
+
if (!(connected.socket instanceof Socket)) { connected.socket.destroy(); throw new ServiceTransportError("Service CONNECT socket invalid"); }
|
|
53
|
+
return connected.socket;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (error instanceof ServiceTransportError) throw error;
|
|
56
|
+
throw new ServiceTransportError("Service proxy connection or TLS failed");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
let dispatcher: InstanceType<typeof undici.Client> | undefined;
|
|
60
|
+
async function close() {
|
|
61
|
+
tunnel?.destroy();
|
|
62
|
+
await Promise.allSettled([dispatcher?.destroy(), proxy?.destroy()]);
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
if (proxy) tunnel = await proxySocket(proxy);
|
|
66
|
+
signal.throwIfAborted();
|
|
67
|
+
const connector = undici.buildConnector({ ...tls(destination), allowH2: false });
|
|
68
|
+
dispatcher = new undici.Client(origin, { connect: (options, callback) =>
|
|
69
|
+
connector({ ...options, httpSocket: tunnel }, callback) });
|
|
70
|
+
const response = await dispatcher.request({ path, method: "POST", headers, body, signal });
|
|
71
|
+
response.body.on("error", () => {});
|
|
72
|
+
if (response.statusCode >= 300 && response.statusCode < 400) throw new ServiceTransportError("Service redirect refused");
|
|
73
|
+
return { response, close };
|
|
74
|
+
} catch (error) {
|
|
75
|
+
await close();
|
|
76
|
+
if (error instanceof ServiceTransportError) throw error;
|
|
77
|
+
throw new ServiceTransportError("Service connection or TLS failed");
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
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";
|
|
@@ -35,9 +35,11 @@ export type ModelAttemptEvent =
|
|
|
35
35
|
code?: "unsupported_image" | "attachment_unavailable" | "transfer_limit"; attachmentIds?: readonly string[];
|
|
36
36
|
contextFailure?: import("./context.ts").ContextLimitFailure;
|
|
37
37
|
providerFailure?: string;
|
|
38
|
+
noRetry?: true;
|
|
38
39
|
/** Only validated provider/category/status values may enter durable diagnostics. */
|
|
39
40
|
diagnostic?: { provider: "openrouter" | "chat_completions"; category: "http"; status: number }
|
|
40
|
-
| { provider: "openrouter" | "chat_completions"; category: "transport" | "redirect" | "protocol" | "relay_expired" }
|
|
41
|
+
| { provider: "openrouter" | "chat_completions"; category: "transport" | "redirect" | "protocol" | "relay_expired" }
|
|
42
|
+
| { provider: "chat_completions"; category: "relay_refusal"; reason: string } };
|
|
41
43
|
/** One attempt emits exactly one terminal response or failure unless aborted;
|
|
42
44
|
* EOF without a terminal is incomplete. A consumer ignores events after the
|
|
43
45
|
* first terminal, timeout or abort. The adapter assembles and validates tools. */
|
|
@@ -2,6 +2,7 @@ import type { ApprovalCloseReason, ApprovalRequest } from "./config-permissions.
|
|
|
2
2
|
import type { ChannelChangeResult, ChannelStatusResult, ItemStatus, StoredMessage, PendingChannelChange, ProtocolConfig, TurnStatus } from "./protocol.ts";
|
|
3
3
|
|
|
4
4
|
export interface OpenResult {
|
|
5
|
+
webUnavailable?: import("./web.ts").WebUnavailable;
|
|
5
6
|
mcpServers?: Record<string, import("./mcp.ts").McpServerStatus>;
|
|
6
7
|
sessionId: string;
|
|
7
8
|
lifecycle: import("./storage.ts").SessionLifecycle;
|
|
@@ -28,7 +28,8 @@ export interface ProtocolConfig {
|
|
|
28
28
|
policies?: Record<string, import("./config-permissions.ts").ToolPolicy>;
|
|
29
29
|
}
|
|
30
30
|
/** Executable-only grant from the trusted native control connection. */
|
|
31
|
-
export
|
|
31
|
+
export type InferenceRelayGrant = { baseUrl: string; bearerToken: string } &
|
|
32
|
+
({ lifetime: { mode: "process" }; expiresAtMs?: never } | { expiresAtMs: number; lifetime?: never });
|
|
32
33
|
export interface CreateParams {
|
|
33
34
|
inferenceRelayGrant?: InferenceRelayGrant;
|
|
34
35
|
/** Executable owning launcher material, never saved. */
|
|
@@ -140,6 +141,7 @@ export interface TurnStatus {
|
|
|
140
141
|
/** `idle`, `suspended` and unresolved interrupted work are distinguishable:
|
|
141
142
|
* see SessionStatus in the session contract for the exact derivation. */
|
|
142
143
|
export interface StatusResult {
|
|
144
|
+
webUnavailable?: import("./web.ts").WebUnavailable;
|
|
143
145
|
mcpServers?: Record<string, import("./mcp.ts").McpServerStatus>;
|
|
144
146
|
sessionId: string; revision: number;
|
|
145
147
|
lifecycle: "running" | "suspending" | "suspended";
|
|
@@ -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 }
|
|
@@ -14,3 +14,6 @@ export interface CheckedWebRegistration {
|
|
|
14
14
|
dispatch: WebDispatchEvidence;
|
|
15
15
|
execute(args: unknown, signal: AbortSignal): Promise<WebToolResponse>;
|
|
16
16
|
}
|
|
17
|
+
|
|
18
|
+
/** Entry-local startup refusal, without proxy authority or credential material. */
|
|
19
|
+
export type WebUnavailable = Partial<Record<"web_search" | "web_fetch", "invalid_egress_mode" | "invalid_egress_proxy" | "direct_fetch_requires_direct_egress">>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { resolveServiceEgress } from "../../capabilities/tools/web/service-egress.ts";
|
|
1
2
|
import { openMcpRegistry } from "../../capabilities/tools/mcp/registry.ts";
|
|
2
|
-
import { createWebRegistry, directWebFetch } from "../../capabilities/tools/web/registry.ts";
|
|
3
|
-
import {
|
|
3
|
+
import { createWebRegistry, directWebFetch, webUnavailable } from "../../capabilities/tools/web/registry.ts";
|
|
4
|
+
import { exaServiceTransport } from "../../capabilities/tools/web/exa-transport.ts";
|
|
4
5
|
import { compatibleInferenceKey } from "../../runtime/config/inference-key.ts";
|
|
5
6
|
import { createHash } from "node:crypto";
|
|
6
7
|
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
@@ -96,6 +97,8 @@ export async function openDevelopment(options: DevelopmentOptions) {
|
|
|
96
97
|
const compatible = isCompatibleModel(managedConfig?.model) ? managedConfig.model : undefined;
|
|
97
98
|
const creating = !options.database || !!options.create;
|
|
98
99
|
const environment = options.environment ?? process.env;
|
|
100
|
+
const webEgress = resolveServiceEgress(environment);
|
|
101
|
+
const exa = exaServiceTransport(webEgress);
|
|
99
102
|
let compatibleKey = compatible && creating ? resolveCompatibleCredential(compatible, environment) : undefined;
|
|
100
103
|
const providerModel = managedConfig?.model.protocol === "openrouter" ? managedConfig.model : undefined;
|
|
101
104
|
const apiKey = providerModel ? (useLegacyCredential ? options.provider!.apiKey : resolveCredential(providerModel, options.environment ?? process.env)) : undefined;
|
|
@@ -112,7 +115,7 @@ export async function openDevelopment(options: DevelopmentOptions) {
|
|
|
112
115
|
const mediaRoot = options.database ? options.mediaRoot ?? `${options.database}.media` : join(tempMedia!, "media");
|
|
113
116
|
if (!sqlite) adapter = createMemoryStorageAdapter({ mediaRoot });
|
|
114
117
|
const makeWebTools = () => {
|
|
115
|
-
const result = createWebRegistry(managedConfig ?? {}, environment, { exa: options.webTransport ??
|
|
118
|
+
const result = createWebRegistry(managedConfig ?? {}, environment, { exa: options.webTransport ?? exa, http: directWebFetch }, webEgress);
|
|
116
119
|
if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
|
|
117
120
|
return result.value;
|
|
118
121
|
};
|
|
@@ -140,7 +143,7 @@ export async function openDevelopment(options: DevelopmentOptions) {
|
|
|
140
143
|
let session: PersistentSession;
|
|
141
144
|
const inspection = createInspection(systemPrompt, [...tools, ...(webTools ?? []).map(value => value.definition),
|
|
142
145
|
...[...(mcp?.bindings.values() ?? [])].map(value => value.definition)], storage, options.database ?? "memory",
|
|
143
|
-
turnId => session.tools?.invocations(turnId) ?? []);
|
|
146
|
+
turnId => session.tools?.invocations(turnId) ?? [], webUnavailable(managedConfig ?? {}, webEgress));
|
|
144
147
|
const captureScript = (options.environment ?? process.env).HARNESS_CAPTURE_SCRIPT_REQUESTS === "1";
|
|
145
148
|
session = createSession({
|
|
146
149
|
systemPrompt, storage, config: managedConfig, imageInput, webTools, mcpTools: mcp?.bindings, captureContext: (!script || captureScript) ? inspection.capture : undefined,
|
|
@@ -26,7 +26,8 @@ function read<T>(result: StorageResult<T>) {
|
|
|
26
26
|
* dirty. Only HTTP reads request data from storage. */
|
|
27
27
|
export function createInspection(systemPrompt: string, tools: readonly ToolDefinition[],
|
|
28
28
|
reads: InspectionStorageReads, storage: string,
|
|
29
|
-
webInvocations?: (turnId: number) => import("../../contracts/tools.ts").ToolInvocation[]
|
|
29
|
+
webInvocations?: (turnId: number) => import("../../contracts/tools.ts").ToolInvocation[],
|
|
30
|
+
webUnavailable: import("../../contracts/web.ts").WebUnavailable = {}) {
|
|
30
31
|
const instructions = composeSystemPrompt(systemPrompt);
|
|
31
32
|
const captures = new Map<string, { turnId: number; metadata: NonNullable<InspectedInference["context"]> }>();
|
|
32
33
|
const channels = new Map<string, InspectedInference[]>();
|
|
@@ -40,7 +41,7 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
|
|
|
40
41
|
const { revision, session, channels: status } = read(reads.readInspectionStatus());
|
|
41
42
|
const execution = stopped ? "stopped" : session.lifecycle !== "running" ? session.lifecycle
|
|
42
43
|
: status.some(channel => channel.turn === "running" || (channel.lifecycle === "open" && channel.pending > 0)) ? "working" : "idle";
|
|
43
|
-
return { session: { sessionId: session.sessionId, lifecycle: session.lifecycle, execution, revision, storage },
|
|
44
|
+
return { session: { sessionId: session.sessionId, lifecycle: session.lifecycle, execution, revision, storage, ...(Object.keys(webUnavailable).length ? { webUnavailable } : {}) },
|
|
44
45
|
channels: status.map(channel => {
|
|
45
46
|
const contextFailure = channel.unresolved && parseContextLimitFailure(channel.unresolved.reason);
|
|
46
47
|
return { ...channel, running: channel.turn === "running",
|
|
@@ -49,6 +49,7 @@ export interface OpenedSession {
|
|
|
49
49
|
exportArchive?(): StorageResult<SessionArchive>;
|
|
50
50
|
attachments?: ReturnType<typeof createManagedAttachmentService>;
|
|
51
51
|
imageInput?: boolean;
|
|
52
|
+
webUnavailable?: import("../../contracts/web.ts").WebUnavailable;
|
|
52
53
|
mcpStatus?(): Record<string, import("../../contracts/mcp.ts").McpServerStatus>;
|
|
53
54
|
stopMcp?(): Promise<void>;
|
|
54
55
|
}
|
|
@@ -199,7 +200,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
199
200
|
const image = opened.imageInput && (opened.session.reminders?.executable() ?? true)
|
|
200
201
|
? { imageInput: true as const, imageLimits: { formats: ["image/png", "image/jpeg", "image/webp"], fileBytes: ATTACHMENT_LIMITS.fileBytes,
|
|
201
202
|
turnBytes: ATTACHMENT_LIMITS.imageBytesPerTurn, maxImages: ATTACHMENT_LIMITS.references, maxSide: ATTACHMENT_LIMITS.imageSide, maxPixels: ATTACHMENT_LIMITS.imagePixels } } : {};
|
|
202
|
-
return { sessionId: value.sessionId, lifecycle: value.lifecycle, revision, ...image, ...(opened.mcpStatus ? { mcpServers: opened.mcpStatus() } : {}) };
|
|
203
|
+
return { sessionId: value.sessionId, lifecycle: value.lifecycle, revision, ...image, ...(opened.webUnavailable ? { webUnavailable: opened.webUnavailable } : {}), ...(opened.mcpStatus ? { mcpServers: opened.mcpStatus() } : {}) };
|
|
203
204
|
}
|
|
204
205
|
|
|
205
206
|
function holdAfterResponse(start?: () => void) {
|
|
@@ -459,6 +460,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
459
460
|
if (method === "session/status") {
|
|
460
461
|
keys(p, []);
|
|
461
462
|
return { ...wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()),
|
|
463
|
+
...(current.webUnavailable ? { webUnavailable: current.webUnavailable } : {}),
|
|
462
464
|
...(current.mcpStatus ? { mcpServers: current.mcpStatus() } : {}) };
|
|
463
465
|
}
|
|
464
466
|
if (method === "session/suspend" || method === "session/resume") {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { inferenceRelayAttempt } from "./capabilities/model/inference-relay.ts";
|
|
1
|
+
import { createRelayAuthority, inferenceRelayAttempt } from "./capabilities/model/inference-relay.ts";
|
|
2
2
|
import { resolveInferenceRelayGrant } from "./util/inference-relay.ts";
|
|
3
|
+
import { resolveServiceEgress } from "./capabilities/tools/web/service-egress.ts";
|
|
3
4
|
import { isCompatibleModel } from "./contracts/config-permissions.ts";
|
|
4
5
|
import { validateMcpRuntimeHeaders } from "./util/mcp-config.ts";
|
|
5
6
|
import { openMcpRegistry } from "./capabilities/tools/mcp/registry.ts";
|
|
6
|
-
import { createWebRegistry, directWebFetch } from "./capabilities/tools/web/registry.ts";
|
|
7
|
-
import {
|
|
7
|
+
import { createWebRegistry, directWebFetch, webUnavailable } from "./capabilities/tools/web/registry.ts";
|
|
8
|
+
import { exaServiceTransport } from "./capabilities/tools/web/exa-transport.ts";
|
|
8
9
|
import { webDefinitions } from "./capabilities/tools/web/definitions.ts";
|
|
9
10
|
import { compatibleInferenceKey } from "./runtime/config/inference-key.ts";
|
|
10
11
|
import { wallReminderClock } from "./runtime/reminder-timer.ts";
|
|
@@ -103,6 +104,8 @@ function withFaults(storage: SessionStorage, hit: (point: string) => void): Sess
|
|
|
103
104
|
* protocol. In memory by default; durable when given a home or an adapter. */
|
|
104
105
|
const BUILTINS = [echoDefinition, recordDefinition, holdDefinition];
|
|
105
106
|
export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
107
|
+
const webEgress = resolveServiceEgress(options.environment ?? process.env);
|
|
108
|
+
const exa = exaServiceTransport(webEgress);
|
|
106
109
|
let fixtureEndpoint: string | undefined;
|
|
107
110
|
if (options.providerEndpoint) {
|
|
108
111
|
const url = new URL(options.providerEndpoint);
|
|
@@ -158,7 +161,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
158
161
|
[...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(!isCompatibleModel(config.model) && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
|
|
159
162
|
if (mode === "create" && paths) mkdirSync(paths.directory, { recursive: true });
|
|
160
163
|
const makeWebTools = () => {
|
|
161
|
-
const result = createWebRegistry(config, environment, { exa: options.webTransport ?? webFixture ??
|
|
164
|
+
const result = createWebRegistry(config, environment, { exa: options.webTransport ?? webFixture ?? exa, http: options.webHttp ?? directWebFetch }, webEgress);
|
|
162
165
|
if (!result.ok) throw new SessionOpenError("invalid_config", result.error.message);
|
|
163
166
|
return result.value;
|
|
164
167
|
};
|
|
@@ -200,6 +203,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
200
203
|
return result;
|
|
201
204
|
};
|
|
202
205
|
const revisions = new Map<string, number>();
|
|
206
|
+
const relayAuthority = relayGrant && createRelayAuthority(relayGrant);
|
|
203
207
|
const session = createSession({
|
|
204
208
|
...(script && options.reminderTime !== undefined && Number.isSafeInteger(options.reminderTime)
|
|
205
209
|
? { reminderClock: { ...wallReminderClock, now: () => options.reminderTime! } } : {}), ...(options.requests ? { captureContext: ({ context }: import("./contracts/context.ts").ContextCapture) =>
|
|
@@ -213,7 +217,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
213
217
|
const metadata = attachments ? (id: string) => {
|
|
214
218
|
const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
|
|
215
219
|
} : undefined;
|
|
216
|
-
return
|
|
220
|
+
return relayAuthority ? inferenceRelayAttempt(compatible.model, relayAuthority, metadata)
|
|
217
221
|
: managedCompatibleAttempt(compatible, conversation, compatibleKey, undefined, metadata);
|
|
218
222
|
} });
|
|
219
223
|
return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
|
|
@@ -264,7 +268,8 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
264
268
|
} });
|
|
265
269
|
return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
|
|
266
270
|
} });
|
|
267
|
-
|
|
271
|
+
const unavailable = webUnavailable(config, webEgress);
|
|
272
|
+
return { session, config, imageInput, ...(Object.keys(unavailable).length ? { webUnavailable: unavailable } : {}), ...(mcp ? { mcpStatus: mcp.status, stopMcp: mcp.close } : {}), ...(attachments ? { attachments } : {}), close() { void mcp?.close(); attachments?.close(); opened.value.close(); }, commitConfig() {
|
|
268
273
|
const saved = storage.saveConfig(config);
|
|
269
274
|
if (!saved.ok && saved.error.code !== "incompatible") throw new SessionOpenError("storage_failure", saved.error.message);
|
|
270
275
|
}, exportArchive: () => storage.exportArchive() };
|
|
@@ -34,13 +34,21 @@ export function resolveInferenceRelayGrant(model: ManagedModel, value: unknown,
|
|
|
34
34
|
}
|
|
35
35
|
if (value === undefined) return failure("is required");
|
|
36
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
|
|
37
|
+
|| Object.keys(value).some(key => !["baseUrl", "bearerToken", "expiresAtMs", "lifetime"].includes(key))) return failure("is invalid");
|
|
38
|
+
const record = value as Record<string, unknown>;
|
|
39
|
+
const { baseUrl, bearerToken, expiresAtMs, lifetime } = record;
|
|
39
40
|
if (typeof bearerToken !== "string" || !/^[A-Za-z0-9._~+/-]{1,2048}={0,2}$/.test(bearerToken)
|
|
40
|
-
||
|
|
41
|
+
|| Object.hasOwn(record, "expiresAtMs") === Object.hasOwn(record, "lifetime")) return failure("is invalid");
|
|
42
|
+
const processBound = Object.hasOwn(record, "lifetime");
|
|
43
|
+
if (processBound) {
|
|
44
|
+
if (!lifetime || Array.isArray(lifetime) || typeof lifetime !== "object" || !("mode" in lifetime) || lifetime.mode !== "process" ||
|
|
45
|
+
Object.keys(lifetime).length !== 1 || !Object.hasOwn(lifetime, "mode")) return failure("is invalid");
|
|
46
|
+
} else if (typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs)) return failure("is invalid");
|
|
41
47
|
let endpoint: string;
|
|
42
48
|
try { endpoint = canonicalRelayUrl(baseUrl); } catch { return failure("is invalid"); }
|
|
43
49
|
if (endpoint !== model.baseUrl) return failure("does not match the configured endpoint");
|
|
50
|
+
if (processBound) return { baseUrl: endpoint, bearerToken, lifetime: { mode: "process" } };
|
|
51
|
+
if (typeof expiresAtMs !== "number") return failure("is invalid");
|
|
44
52
|
if (expiresAtMs <= now) return failure("has expired");
|
|
45
53
|
return { baseUrl: endpoint, bearerToken, expiresAtMs };
|
|
46
54
|
}
|