@qlairoslabs/acp-client 0.13.8-e-alpha.1 → 0.13.10-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.
Files changed (30) hide show
  1. package/CONSUMER_GUIDE.md +78 -10
  2. package/package.json +1 -1
  3. package/src/agent/config.ts +2 -0
  4. package/src/index.ts +2 -1
  5. package/src/native/errors.ts +1 -1
  6. package/src/native/host-config.ts +2 -0
  7. package/src/native/host.ts +6 -1
  8. package/src/native/inference-relay.ts +91 -26
  9. package/src/native/recovery.ts +6 -5
  10. package/src/native-harness/src/capabilities/model/inference-relay.ts +73 -9
  11. package/src/native-harness/src/capabilities/model/runner.ts +4 -1
  12. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +30 -10
  13. package/src/native-harness/src/capabilities/tools/web/exa.ts +5 -1
  14. package/src/native-harness/src/capabilities/tools/web/registry.ts +14 -1
  15. package/src/native-harness/src/capabilities/tools/web/service-egress.ts +80 -0
  16. package/src/native-harness/src/client.ts +2 -0
  17. package/src/native-harness/src/contracts/inspector.ts +5 -0
  18. package/src/native-harness/src/contracts/model-execution.ts +3 -1
  19. package/src/native-harness/src/contracts/operator-controls.ts +2 -0
  20. package/src/native-harness/src/contracts/protocol.ts +4 -1
  21. package/src/native-harness/src/contracts/web.ts +3 -0
  22. package/src/native-harness/src/interfaces/cli/development.ts +7 -4
  23. package/src/native-harness/src/interfaces/cli/serve.ts +10 -7
  24. package/src/native-harness/src/interfaces/inspector/config.ts +17 -0
  25. package/src/native-harness/src/interfaces/inspector/managed.ts +51 -0
  26. package/src/native-harness/src/interfaces/inspector/server.ts +13 -8
  27. package/src/native-harness/src/interfaces/inspector/state.ts +6 -4
  28. package/src/native-harness/src/interfaces/protocol/server.ts +27 -7
  29. package/src/native-harness/src/testing.ts +64 -14
  30. package/src/native-harness/src/util/inference-relay.ts +11 -3
package/CONSUMER_GUIDE.md CHANGED
@@ -1164,6 +1164,22 @@ Handle that command before normal application startup and keep stdout reserved
1164
1164
  for the harness protocol. The command override includes all arguments, so pass
1165
1165
  the same directory as `harness.home`.
1166
1166
 
1167
+ ### Managed inspector
1168
+
1169
+ Set `HARNESS_INSPECTOR_PORT=0` in the native harness launch environment to open
1170
+ the existing read-only inspector on a free loopback port. Start the harness,
1171
+ then read `(await agent.nativeHarness.status()).inspector`. A `listening`
1172
+ status gives the bound port for `http://127.0.0.1:<port>/`. An `unavailable`
1173
+ status gives a fixed reason and the session can still run. An unset port
1174
+ leaves the inspector off. Read the status again after a process replacement.
1175
+
1176
+ In an isolated container network, use a known container port, set
1177
+ `HARNESS_INSPECTOR_HOST=0.0.0.0`, and set
1178
+ `HARNESS_INSPECTOR_PUBLIC_AUTHORITY` to the exact loopback Host authority
1179
+ that reaches the inspector. Publish through the launcher's loopback mapping
1180
+ or local proxy. The launcher supplies the browser URL. Limit access to
1181
+ trusted users because the inspector shows conversation and model details.
1182
+
1167
1183
  ### Configuration
1168
1184
 
1169
1185
  ```ts
@@ -1237,11 +1253,28 @@ For an operator-managed native inference relay, declare
1237
1253
  `credentialMode: "relay"` on the `openai-compatible` model and set its
1238
1254
  `baseUrl` to the exact relay URL. Omit `apiKeyEnv`. Supply a trusted
1239
1255
  `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.
1256
+ it receives `{ sessionId, signal }` and returns `{ baseUrl, bearerToken }`
1257
+ with exactly one lifetime field. Use `lifetime: { mode: "process" }` for a
1258
+ process-bound grant with no clock expiry, or `expiresAtMs` for a timed
1259
+ grant. The grant stays in memory. Keep upstream provider keys on the relay
1260
+ side. Prefer HTTPS. The native control connection must be trusted, and
1261
+ plaintext requires an isolated hop.
1262
+
1263
+ To clean up a grant after a failed executable open, return an optional opaque
1264
+ `grantRef` and configure `harness.onInferenceRelayOpenFailure`. The callback
1265
+ receives `{ grantRef, delivery }`. On `not_sent`, abandon the issuance. On
1266
+ `unknown`, revoke the grant because it may have reached the harness. Resolve
1267
+ the callback only after cleanup is confirmed. `harness.inferenceRelayCleanupMs`
1268
+ sets the independent deadline and defaults to 10 seconds. The reference
1269
+ stays on the host side.
1270
+
1271
+ If startup surfaces `relay_cleanup_unconfirmed` on the error or its cause,
1272
+ stop using that SDK host. Verify that the old harness execution has ended or
1273
+ been fenced before opening the saved session with a fresh host and process.
1274
+ A late cleanup acknowledgement leaves the old execution fenced. If the relay
1275
+ revokes the current grant, later inference needs a fresh executable open.
1276
+ ACP-client leaves that action to the host and never replays a relay request
1277
+ that may have been sent.
1245
1278
 
1246
1279
  Set `harness.config.model.contextBudget` on OpenRouter, OpenCode Go or OpenAI-compatible models
1247
1280
  to fit a larger inference request. For example, a model with a 128,000-token
@@ -1830,16 +1863,41 @@ harness: {
1830
1863
  - **Deadlines.** `deadlineMs` on a tool overrides `defaultDeadlineMs`. When it
1831
1864
  passes, the model receives a timeout result that says the effect is unknown,
1832
1865
  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).
1866
+ - **Large results.** Keep returning JSON values from handlers. ACP-client
1867
+ counts the UTF-8 bytes of the full inline success result, including the
1868
+ `{ ok: true, output }` wrapper. The default is 16 KiB. Use
1869
+ `harness.functions.inlineBytes` to store results earlier. Values above
1870
+ 16 KiB are capped at 16 KiB. When a result exceeds the effective limit,
1871
+ ACP-client stores the output JSON in `resultDirectory` or a temporary
1872
+ directory removed on stop. The model receives a preview and an ID and can
1873
+ page through the result using `read_tool_result`. Only the producing
1874
+ conversation can read it. Results expire after `resultTtlMs` (24 hours by
1875
+ default).
1838
1876
  - **Records.** `agent.nativeHarness.toolInvocation(id)` and
1839
1877
  `toolInvocations(turn)` return each call's state. A call that was dispatched
1840
1878
  but has no recorded result (crash, lost connection, interrupt) is
1841
1879
  `interrupted` with `effect: "unknown"`. It is never run again automatically.
1842
1880
 
1881
+ #### Native web tools and proxy egress
1882
+
1883
+ Configure managed search and fetch with `harness.config.webSearch` and
1884
+ `harness.config.webFetch`. Exa resolves the configured `apiKeyEnv` from the
1885
+ harness environment and defaults to `EXA_API_KEY`.
1886
+
1887
+ For a hosted deployment that requires a proxy, set
1888
+ `HARNESS_WEB_EGRESS=proxy-required` and uppercase `HTTPS_PROXY` in the
1889
+ trusted harness launch environment. Use an HTTP or HTTPS proxy URL without
1890
+ credentials, such as `http://egress.internal:8080`. Supply the same environment
1891
+ on relaunch. Exa search and Exa-backed fetch use CONNECT to the fixed Exa
1892
+ origin, with the service credential sent inside origin TLS. Required mode
1893
+ ignores `NO_PROXY`, disables direct URL fetch, and never falls back to direct
1894
+ egress. With the mode omitted or set to `direct`, the harness connects directly
1895
+ and ignores ambient proxy variables.
1896
+
1897
+ An Exa result can still reach the model when the provider omits cost data.
1898
+ The harness reports the cost as unknown. A proxy failure produces a tool
1899
+ error and the turn can continue.
1900
+
1843
1901
  #### Native MCP servers
1844
1902
 
1845
1903
  Configure native servers in `harness.config.mcpServers`. The harness
@@ -2492,6 +2550,16 @@ const unsubscribe = session.subscribe((notification: AgentSessionNotification) =
2492
2550
  });
2493
2551
  ```
2494
2552
 
2553
+ For external ACP adapters, read `session.state.sessionStartFailure` when a
2554
+ recoverable startup refusal leaves the connection open without a provider
2555
+ session. Direct controller callers can read `sessionStartFailure` on the
2556
+ result of `HarnessController.start()`. The optional detail carries a safe
2557
+ display message and the adapter's numeric JSON-RPC `rpcCode` when available.
2558
+ Show the message if you want to surface the failure in the app. For an
2559
+ adapter that reliably signals authentication is required, offer its login
2560
+ flow and let the caller retry on the open connection. Successful session
2561
+ creation or load clears the detail.
2562
+
2495
2563
  `onResponseChunk` and activity callbacks are provisional live streams. A
2496
2564
  `presentation_recorded` notification means the displayed item revision has been appended
2497
2565
  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.10e-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
@@ -269,6 +269,7 @@ export type {
269
269
  export { ADAPTERS, buildSpawnCommand, isNativeAdapter } from "./adapters.ts";
270
270
  export type { Adapter, AdapterPreset, AgentAdapter, NativeAdapter } from "./adapters.ts";
271
271
  export { HarnessIncompatibleError, HarnessUnavailableError, NativeHarnessHost } from "./native/host.ts";
272
+ export type { InspectorStatus } from "./native-harness/src/client.ts";
272
273
  export type { HarnessUnavailableCode } from "./native/errors.ts";
273
274
  export type { ChannelChangeOutcome, NativeApprovalRequest, NativeApprovalResponder, NativeHarnessHostConfig, NativeHostState } from "./native/host.ts";
274
275
  export { NativeTurnError } from "./native/controller.ts";
@@ -807,5 +808,5 @@ export type { ReminderErrorCode, ReminderSchedule, ReminderScheduleInput } from
807
808
  export type { Reminder } from "./persistence/reminders.ts";
808
809
  export type { ReminderCreate, ReminderEdit, ReminderView, ReminderEvent } from "./native/reminders/service.ts";
809
810
 
810
- export type { InferenceRelayGrant, InferenceRelayGrantProvider } from "./native/inference-relay.ts";
811
+ export type { InferenceRelayGrant, InferenceRelayGrantProvider, InferenceRelayGrantProviderResult, InferenceRelayOpenFailure } from "./native/inference-relay.ts";
811
812
  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,29 +7,89 @@ 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,
13
- metadata?: Parameters<typeof openAICompatibleAttempt>[5]): ModelAttempt {
50
+ export function inferenceRelayAttempt(model: string, authority: RelayAuthority,
51
+ metadata?: Parameters<typeof openAICompatibleAttempt>[5],
52
+ onRequest?: Parameters<typeof openAICompatibleAttempt>[4]): ModelAttempt {
14
53
  return async function* (request, signal) {
15
- if (Date.now() >= grant.expiresAtMs) { yield expired; return; }
54
+ const captured = authority.capture(), { grant } = captured;
55
+ const isExpired = () => grant.expiresAtMs !== undefined && Date.now() >= grant.expiresAtMs;
56
+ const refusalEvent = (reason: string) => ({
57
+ type: "failure", kind: "provider", message: "Inference relay refused",
58
+ diagnostic: { provider: "chat_completions", category: "relay_refusal", reason }, noRetry: true,
59
+ }) as const;
60
+ if (captured.revoked) { yield refusalEvent("native_grant_revoked"); return; }
61
+ if (isExpired()) { yield expired; return; }
16
62
  // Bun's package-name shim can use global, proxy-aware fetch. An explicit
17
63
  // unshimmed dispatcher sends this request only to the validated origin.
18
64
  const undici: typeof import("undici") = await import(new URL("index.js", import.meta.resolve("undici/package.json")).href);
19
65
  const dispatcher = new undici.Agent({ connect: { rejectUnauthorized: true } });
20
- let dispatchExpired = false;
66
+ let closing: Promise<void> | undefined;
67
+ const close = () => closing ??= dispatcher.destroy().catch(() => {});
68
+ const abort = () => { void close(); };
69
+ signal.addEventListener("abort", abort, { once: true });
70
+ if (signal.aborted) abort();
71
+ let dispatchExpired = false, dispatched = false;
72
+ let refusal: string | undefined;
21
73
  const directFetch = (async (input: unknown, init?: RequestInit) => {
22
- if (Date.now() >= grant.expiresAtMs) {
74
+ if (isExpired()) {
23
75
  dispatchExpired = true;
24
76
  throw new Error(expired.message);
25
77
  }
26
- return undici.fetch(String(input), {
78
+ if (authority.capture() !== captured) { refusal = "native_unavailable"; throw new Error("Inference relay replaced"); }
79
+ if (captured.revoked) { refusal = "native_grant_revoked"; throw new Error("Inference relay revoked"); }
80
+ (init?.signal ?? signal).throwIfAborted();
81
+ dispatched = true;
82
+ const response = await undici.fetch(String(input), {
27
83
  method: "POST", body: String(init?.body),
28
84
  headers: Object.fromEntries(new Headers(init?.headers)), signal: init?.signal ?? undefined,
29
85
  redirect: "manual", dispatcher,
30
86
  });
87
+ if (response.ok) return response;
88
+ refusal = await relayRefusal(response);
89
+ if (refusal === "native_grant_revoked") authority.revoke(captured);
90
+ return new Response(null, { status: response.status });
31
91
  }) as unknown as typeof fetch;
32
- const attempt = openAICompatibleAttempt(grant.baseUrl, model, grant.bearerToken, directFetch, undefined, metadata);
92
+ const attempt = openAICompatibleAttempt(grant.baseUrl, model, grant.bearerToken, directFetch, onRequest, metadata);
33
93
  const token = grant.bearerToken;
34
94
  const marker = "[relay credential hidden]";
35
95
  const redact = (text: string) => text.replaceAll(token, marker.includes(token) ? "[ ]" : marker);
@@ -37,6 +97,7 @@ export function inferenceRelayAttempt(model: string, grant: InferenceRelayGrant,
37
97
  try {
38
98
  for await (const event of attempt(request, signal)) {
39
99
  if (dispatchExpired) { yield expired; return; }
100
+ if (refusal) { yield refusalEvent(refusal); return; }
40
101
  if (event.type === "text_delta") {
41
102
  // Retain only a possible partial credential across provider frames.
42
103
  pending = redact(pending + event.text);
@@ -58,8 +119,11 @@ export function inferenceRelayAttempt(model: string, grant: InferenceRelayGrant,
58
119
  content: event.response.content === null ? null : redact(event.response.content) } };
59
120
  return;
60
121
  }
61
- yield event;
122
+ yield event.type === "failure" && dispatched ? { ...event, noRetry: true } : event;
62
123
  }
63
- } finally { await dispatcher.destroy(); }
124
+ } finally {
125
+ signal.removeEventListener("abort", abort);
126
+ await close();
127
+ }
64
128
  };
65
129
  }
@@ -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" } };