@qlairoslabs/acp-client 0.13.8-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 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
- `{ 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.
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.** A result over 16 384 bytes is written to a private
1834
- directory (`resultDirectory`, or a temporary one removed on stop) and the
1835
- model receives a preview and an ID. It reads parts with the built-in
1836
- `read_tool_result` tool. Only the conversation that produced a result can
1837
- read it. Results expire after `resultTtlMs` (24 hours by default).
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.8e-alpha.1",
3
+ "version": "0.13.9e-alpha.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -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;
package/src/index.ts CHANGED
@@ -807,5 +807,5 @@ export type { ReminderErrorCode, ReminderSchedule, ReminderScheduleInput } from
807
807
  export type { Reminder } from "./persistence/reminders.ts";
808
808
  export type { ReminderCreate, ReminderEdit, ReminderView, ReminderEvent } from "./native/reminders/service.ts";
809
809
 
810
- export type { InferenceRelayGrant, InferenceRelayGrantProvider } from "./native/inference-relay.ts";
810
+ export type { InferenceRelayGrant, InferenceRelayGrantProvider, InferenceRelayGrantProviderResult, InferenceRelayOpenFailure } from "./native/inference-relay.ts";
811
811
  export type { McpRuntimeHeaders, McpRuntimeHeadersProvider, NativeInputPolicy, NativeMcpStatus } from "./native/mcp.ts";
@@ -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
  }
@@ -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;
@@ -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
- InferenceRelayGrant | undefined | Promise<InferenceRelayGrant | undefined>;
7
+ InferenceRelayGrantProviderResult | undefined | Promise<InferenceRelayGrantProviderResult | undefined>;
8
+ export type InferenceRelayOpenFailure = (context: { grantRef: string; delivery: "not_sent" | "unknown" }) => void | Promise<void>;
9
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");
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
- 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");
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
  }
@@ -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) {
@@ -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, grant: InferenceRelayGrant,
50
+ export function inferenceRelayAttempt(model: string, authority: RelayAuthority,
13
51
  metadata?: Parameters<typeof openAICompatibleAttempt>[5]): ModelAttempt {
14
52
  return async function* (request, signal) {
15
- if (Date.now() >= grant.expiresAtMs) { yield expired; return; }
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 dispatchExpired = false;
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 (Date.now() >= grant.expiresAtMs) {
73
+ if (isExpired()) {
23
74
  dispatchExpired = true;
24
75
  throw new Error(expired.message);
25
76
  }
26
- return undici.fetch(String(input), {
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 { await dispatcher.destroy(); }
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,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
- if (decoder) await pipeline(response, boundedBytes(cap), decoder, boundedBytes(cap), sink, { signal });
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) { return failed(cause ?? (error instanceof ExaResponseLimit ? "response_too_large" : "provider_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
+ }
@@ -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 interface InferenceRelayGrant { baseUrl: string; bearerToken: string; expiresAtMs: number }
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";
@@ -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 { exaHttpsTransport } from "../../capabilities/tools/web/exa-transport.ts";
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 ?? exaHttpsTransport, http: directWebFetch });
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 { exaHttpsTransport } from "./capabilities/tools/web/exa-transport.ts";
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 ?? exaHttpsTransport, http: options.webHttp ?? directWebFetch });
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 relayGrant ? inferenceRelayAttempt(compatible.model, relayGrant, metadata)
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
- return { session, config, imageInput, ...(mcp ? { mcpStatus: mcp.status, stopMcp: mcp.close } : {}), ...(attachments ? { attachments } : {}), close() { void mcp?.close(); attachments?.close(); opened.value.close(); }, commitConfig() {
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 { baseUrl, bearerToken, expiresAtMs } = value as Partial<InferenceRelayGrant>;
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
- || typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs)) return failure("is invalid");
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
  }