@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
@@ -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
+ }
@@ -19,3 +19,5 @@ export type { Reminder, ReminderChange, ReminderChangeResult, ReminderList, Remi
19
19
  export type { InitializeResult } from "./contracts/protocol.ts";
20
20
  export type { OpenResult } from "./contracts/operator-controls.ts";
21
21
  export type { ReminderBlockReason, OneOffSchedule, ReminderSchedule, RoutineSchedule, IntervalRoutineSchedule, CalendarRoutineSchedule, RoutineEnd, RoutineDeliveryOptions, RoutineTimezoneMigration, ReminderLimits, ReminderChannelEvent } from "./contracts/reminders.ts";
22
+
23
+ export type { InspectorStatus } from "./contracts/inspector.ts";
@@ -0,0 +1,5 @@
1
+ /** Process-local status of the optional managed inspector. */
2
+ export type InspectorStatus =
3
+ | { state: "listening"; host: "127.0.0.1" | "0.0.0.0"; port: number }
4
+ | { state: "unavailable"; code: "invalid_config" | "bind_failed" }
5
+ | { state: "stopped" };
@@ -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,8 @@ 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
+ inspector?: import("./inspector.ts").InspectorStatus;
6
+ webUnavailable?: import("./web.ts").WebUnavailable;
5
7
  mcpServers?: Record<string, import("./mcp.ts").McpServerStatus>;
6
8
  sessionId: string;
7
9
  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,8 @@ 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
+ inspector?: import("./inspector.ts").InspectorStatus;
145
+ webUnavailable?: import("./web.ts").WebUnavailable;
143
146
  mcpServers?: Record<string, import("./mcp.ts").McpServerStatus>;
144
147
  sessionId: string; revision: number;
145
148
  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,
@@ -1,3 +1,4 @@
1
+ import { managedInspectorBinding } from "../inspector/config.ts";
1
2
  import { createScriptedServer } from "../../testing.ts";
2
3
  import { serveProtocolStdio } from "../protocol/stdio-server.ts";
3
4
  import { homedir } from "node:os";
@@ -6,16 +7,18 @@ import { join } from "node:path";
6
7
  /** `home` selects durable SQLite sessions; the default is ~/.harness.
7
8
  * HARNESS_TEST_* settings support deterministic offline process tests. */
8
9
  export async function serve(home?: string) {
9
- const { server } = createScriptedServer({ home: home ?? join(homedir(), ".harness"), fault: process.env.HARNESS_TEST_FAULT, effects: process.env.HARNESS_TEST_EFFECTS,
10
+ const { server } = createScriptedServer({ home: home ?? join(homedir(), ".harness"), inspector: managedInspectorBinding(process.env), fault: process.env.HARNESS_TEST_FAULT, effects: process.env.HARNESS_TEST_EFFECTS,
10
11
  requests: process.env.HARNESS_TEST_REQUESTS, attempts: process.env.HARNESS_TEST_ATTEMPTS, snapshotLog: process.env.HARNESS_TEST_SNAPSHOT_LOG, stallChannel: process.env.HARNESS_TEST_STALL_CHANNEL, providerEndpoint: process.env.HARNESS_TEST_PROVIDER_ENDPOINT, webEndpoint: process.env.HARNESS_TEST_WEB_ENDPOINT,
11
12
  streamResponses: process.env.HARNESS_TEST_STREAM_RESPONSES === "1",
12
13
  reminderTime: process.env.HARNESS_TEST_REMINDER_TIME === undefined ? undefined : Number(process.env.HARNESS_TEST_REMINDER_TIME),
13
14
  modelTimeoutMs: process.env.HARNESS_TEST_MODEL_TIMEOUT_MS === undefined ? undefined : Number(process.env.HARNESS_TEST_MODEL_TIMEOUT_MS) });
14
15
  const output = Bun.stdout.writer();
15
- await serveProtocolStdio(server, Bun.stdin.stream(), async bytes => {
16
- output.write(bytes);
17
- await output.flush();
18
- });
19
- await server.dispose();
20
- await output.end();
16
+ try {
17
+ await serveProtocolStdio(server, Bun.stdin.stream(), async bytes => {
18
+ output.write(bytes);
19
+ await output.flush();
20
+ });
21
+ } finally {
22
+ try { await server.dispose(); } finally { await output.end(); }
23
+ }
21
24
  }
@@ -0,0 +1,17 @@
1
+ import type { InspectorStatus } from "../../contracts/inspector.ts";
2
+
3
+ export type InspectorBinding = Pick<Extract<InspectorStatus, { state: "listening" }>, "host" | "port"> & {
4
+ authority?: string;
5
+ };
6
+
7
+ export function managedInspectorBinding(env: Readonly<Record<string, string | undefined>>): InspectorBinding | "invalid" | undefined {
8
+ const raw = env.HARNESS_INSPECTOR_PORT;
9
+ if (raw === undefined) return undefined;
10
+ const host = env.HARNESS_INSPECTOR_HOST ?? "127.0.0.1";
11
+ const port = Number(raw);
12
+ if (!/^\d{1,5}$/.test(raw) || port > 65535 || (host !== "127.0.0.1" && host !== "0.0.0.0")) return "invalid";
13
+ const authority = env.HARNESS_INSPECTOR_PUBLIC_AUTHORITY;
14
+ if (host === "127.0.0.1") return authority === undefined ? { host, port } : "invalid";
15
+ const match = authority?.match(/^127\.0\.0\.1:([1-9]\d{0,4})$/);
16
+ return match && Number(match[1]) <= 65535 ? { host, port, authority } : "invalid";
17
+ }
@@ -0,0 +1,51 @@
1
+ import type { PersistentSession } from "../../contracts/session.ts";
2
+ import type { InspectorStatus } from "../../contracts/inspector.ts";
3
+ import type { InspectorBinding } from "./config.ts";
4
+ import type { Inspection } from "./state.ts";
5
+ import { observeSession } from "./observe.ts";
6
+ import { serveInspector } from "./server.ts";
7
+
8
+ export function managedInspector(binding: InspectorBinding | "invalid", inspection?: Inspection,
9
+ project?: (body: unknown) => unknown) {
10
+ let status: InspectorStatus = { state: "unavailable", code: "invalid_config" };
11
+ let listener: ReturnType<typeof serveInspector> | undefined;
12
+ let detach: (() => void) | undefined;
13
+ let stopping: Promise<void> | undefined;
14
+
15
+ return {
16
+ active: () => status.state === "listening",
17
+ status: () => status,
18
+ start(session: PersistentSession) {
19
+ if (binding === "invalid" || !inspection || status.state === "listening" || stopping) return;
20
+ try {
21
+ listener = serveInspector(inspection, binding, project);
22
+ detach = observeSession(session, inspection).stop;
23
+ status = { state: "listening", host: binding.host, port: listener.port! };
24
+ } catch {
25
+ void listener?.stop(true);
26
+ status = { state: "unavailable", code: "bind_failed" };
27
+ }
28
+ },
29
+ stop() {
30
+ if (stopping) return stopping;
31
+ status = { state: "stopped" };
32
+ detach?.();
33
+ return stopping = Promise.resolve(listener?.stop(true));
34
+ },
35
+ };
36
+ }
37
+
38
+ /** Retain the development payload shape while hiding known runtime material. */
39
+ export function inspectorProjection(values: readonly (string | undefined)[]) {
40
+ const secrets = [...new Set(values.filter((value): value is string => !!value))].sort((a, b) => b.length - a.length);
41
+ const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
42
+ const sensitive = new RegExp([...secrets.map(escape), "data:image/[^;,]+;base64,[A-Za-z0-9+/=]+"].join("|"), "g");
43
+ function project(value: unknown): unknown {
44
+ if (typeof value === "string") return value.replace(sensitive, match => /^data:image\//i.test(match) ? "[REDACTED_IMAGE]" : "[REDACTED]");
45
+ if (Array.isArray(value)) return value.map(project);
46
+ if (value !== null && typeof value === "object")
47
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [project(key), project(child)]));
48
+ return value;
49
+ }
50
+ return project;
51
+ }
@@ -1,17 +1,22 @@
1
+ import html from "./index.html" with { type: "text" };
2
+ import type { InspectorBinding } from "./config.ts";
1
3
  import type { Inspection } from "./state.ts";
2
4
 
3
- /** Read-only development UI, bound to loopback only. */
4
- export function serveInspector(inspection: Inspection, port = 3000) {
5
+ /** The managed launcher supplies an exact authority for a wildcard bind. */
6
+ export function serveInspector(inspection: Inspection, binding: number | InspectorBinding = 3000,
7
+ project: (body: unknown) => unknown = body => body) {
8
+ const { host, port, authority } = typeof binding === "number"
9
+ ? { host: "127.0.0.1", port: binding, authority: undefined } : binding;
5
10
  return Bun.serve({
6
- hostname: "127.0.0.1", port,
11
+ hostname: host, port,
7
12
  async fetch(request, server) {
8
13
  const url = new URL(request.url);
9
14
  if (request.method !== "GET") return new Response("Read only", { status: 405 });
10
- if (request.headers.get("host") !== server.url.host) return new Response("Invalid host", { status: 403 });
11
- if (url.pathname === "/") return new Response(Bun.file(new URL("./index.html", import.meta.url)), {
15
+ if (request.headers.get("host") !== (authority ?? server.url.host)) return new Response("Invalid host", { status: 403 });
16
+ if (url.pathname === "/") return new Response(html as unknown as string, {
12
17
  headers: { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" },
13
18
  });
14
- const json = (body: unknown) => Response.json(body, { headers: { "Cache-Control": "no-store" } });
19
+ const json = (body: unknown) => Response.json(project(body), { headers: { "Cache-Control": "no-store" } });
15
20
  try {
16
21
  if (url.pathname === "/state") return json(inspection.status());
17
22
  if (url.pathname === "/context") return json(inspection.liveContext());
@@ -26,7 +31,7 @@ export function serveInspector(inspection: Inspection, port = 3000) {
26
31
  return id ? json(url.pathname === "/calls" ? inspection.modelCalls(id) : inspection.channel(id)) : new Response("Channel ID is required", { status: 400 });
27
32
  }
28
33
  } catch (error) {
29
- return new Response(error instanceof Error ? error.message : String(error), { status: 500 });
34
+ return new Response(String(project(error instanceof Error ? error.message : String(error))), { status: 500 });
30
35
  }
31
36
  if (url.pathname !== "/events") return new Response("Not found", { status: 404 });
32
37
  server.timeout(request, 0);
@@ -37,7 +42,7 @@ export function serveInspector(inspection: Inspection, port = 3000) {
37
42
  const send = () => {
38
43
  // Drop slow connections; EventSource reconnects with a fresh snapshot.
39
44
  if ((controller.desiredSize ?? 0) <= 0) {
40
- unsubscribe(); controller.close(); return;
45
+ clearTimeout(timer); unsubscribe(); controller.close(); return;
41
46
  }
42
47
  controller.enqueue(new TextEncoder().encode("data: changed\n\n"));
43
48
  };
@@ -26,7 +26,9 @@ 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 = {},
31
+ project: (body: unknown) => unknown = body => body) {
30
32
  const instructions = composeSystemPrompt(systemPrompt);
31
33
  const captures = new Map<string, { turnId: number; metadata: NonNullable<InspectedInference["context"]> }>();
32
34
  const channels = new Map<string, InspectedInference[]>();
@@ -40,7 +42,7 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
40
42
  const { revision, session, channels: status } = read(reads.readInspectionStatus());
41
43
  const execution = stopped ? "stopped" : session.lifecycle !== "running" ? session.lifecycle
42
44
  : 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 },
45
+ return { session: { sessionId: session.sessionId, lifecycle: session.lifecycle, execution, revision, storage, ...(Object.keys(webUnavailable).length ? { webUnavailable } : {}) },
44
46
  channels: status.map(channel => {
45
47
  const contextFailure = channel.unresolved && parseContextLimitFailure(channel.unresolved.reason);
46
48
  return { ...channel, running: channel.turn === "running",
@@ -86,14 +88,14 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
86
88
  const capture = captures.get(id);
87
89
  requests.push({ ...(capture && capture.turnId === turnId ? { context: capture.metadata } : {}),
88
90
  number: (requests.at(-1)?.number ?? 0) + 1, turnId, at: new Date().toISOString(),
89
- body: Buffer.byteLength(body) <= CAPTURE_BYTES ? JSON.parse(body) : { omitted: true } });
91
+ body: Buffer.byteLength(body) <= CAPTURE_BYTES ? project(JSON.parse(body)) : { omitted: true } });
90
92
  if (requests.length > CAPTURE_LIMIT) requests.shift();
91
93
  invalidate();
92
94
  },
93
95
  response(id: string, message: Extract<Message, { role: "assistant" }>) {
94
96
  const request = channels.get(id)?.at(-1);
95
97
  if (!request) return;
96
- request.response = Buffer.byteLength(JSON.stringify(message)) <= CAPTURE_BYTES ? structuredClone(message) : { omitted: true };
98
+ request.response = Buffer.byteLength(JSON.stringify(message)) <= CAPTURE_BYTES ? structuredClone(project(message) as typeof message) : { omitted: true };
97
99
  invalidate();
98
100
  },
99
101
  };
@@ -1,3 +1,4 @@
1
+ import type { InspectorStatus } from "../../contracts/inspector.ts";
1
2
  import { attachmentView } from "../../contracts/attachments.ts";
2
3
  import { OperatorFault, operatorMethods, operatorRead, readValue } from "./operator.ts";
3
4
  import type { ProtocolEndpoint, RpcRequest, RpcResponse, RpcNotification, RpcSessionNotification, ProtocolConfig, Description, Subscription, DurableErrorCode } from "../../contracts/protocol.ts";
@@ -49,8 +50,10 @@ export interface OpenedSession {
49
50
  exportArchive?(): StorageResult<SessionArchive>;
50
51
  attachments?: ReturnType<typeof createManagedAttachmentService>;
51
52
  imageInput?: boolean;
53
+ webUnavailable?: import("../../contracts/web.ts").WebUnavailable;
52
54
  mcpStatus?(): Record<string, import("../../contracts/mcp.ts").McpServerStatus>;
53
55
  stopMcp?(): Promise<void>;
56
+ inspector?: { start(session: PersistentSession): void; status(): InspectorStatus; stop(): Promise<void> };
54
57
  }
55
58
  export interface ProtocolServerOptions {
56
59
  durable?: boolean;
@@ -185,7 +188,9 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
185
188
  * stop first: a resume in it may already have handed a turn to an executor. */
186
189
  async function abandon(opened: OpenedSession, batch: boolean) {
187
190
  if (batch) { try { opened.session.stop("Open failed"); } catch { /* Storage may be the failure. */ } }
188
- try { await opened.stopMcp?.(); } finally { opened.close(); }
191
+ try { await opened.inspector?.stop(); } finally {
192
+ try { await opened.stopMcp?.(); } finally { opened.close(); }
193
+ }
189
194
  }
190
195
 
191
196
  /** Read one snapshot, then keep every later notification behind the response.
@@ -199,7 +204,11 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
199
204
  const image = opened.imageInput && (opened.session.reminders?.executable() ?? true)
200
205
  ? { imageInput: true as const, imageLimits: { formats: ["image/png", "image/jpeg", "image/webp"], fileBytes: ATTACHMENT_LIMITS.fileBytes,
201
206
  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() } : {}) };
207
+ return { ...inspectorStatus(opened), sessionId: value.sessionId, lifecycle: value.lifecycle, revision, ...image, ...(opened.webUnavailable ? { webUnavailable: opened.webUnavailable } : {}), ...(opened.mcpStatus ? { mcpServers: opened.mcpStatus() } : {}) };
208
+ }
209
+
210
+ function inspectorStatus(opened: OpenedSession) {
211
+ return opened.inspector ? { inspector: opened.inspector.status() } : {};
203
212
  }
204
213
 
205
214
  function holdAfterResponse(start?: () => void) {
@@ -288,6 +297,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
288
297
  if (opened.session.reminders) holdAfterResponse();
289
298
  results = finish?.();
290
299
  reminderResult = prepareReminders(opened.session, reminderBatch);
300
+ opened.inspector?.start(opened.session);
291
301
  current = opened;
292
302
  if (batch) startup = { batch, results: results! };
293
303
  } catch (error) { try { await abandon(opened, !!batch); } catch { /* Preserve startup failure. */ } throw error; }
@@ -322,6 +332,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
322
332
  const results = finish?.();
323
333
  opened.commitConfig?.();
324
334
  const reminderResult = prepareReminders(opened.session, reminderBatch);
335
+ opened.inspector?.start(opened.session);
325
336
  const result = ready(opened);
326
337
  holdAfterResponse(() => { if (current === opened) opened.session.start(); });
327
338
  current = opened;
@@ -459,6 +470,8 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
459
470
  if (method === "session/status") {
460
471
  keys(p, []);
461
472
  return { ...wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()),
473
+ ...inspectorStatus(current),
474
+ ...(current.webUnavailable ? { webUnavailable: current.webUnavailable } : {}),
462
475
  ...(current.mcpStatus ? { mcpServers: current.mcpStatus() } : {}) };
463
476
  }
464
477
  if (method === "session/suspend" || method === "session/resume") {
@@ -487,13 +500,16 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
487
500
  const windowMs = p.unlessDueWithinMs ?? 0;
488
501
  if (p.ifIdle !== true || p.unlessDueWithinMs === null || !Number.isSafeInteger(windowMs) || windowMs < 0) bad("Invalid conditional stop");
489
502
  if (!session.reminders) throw new Fault("invalid_state", "Conditional stop is unavailable");
490
- return session.reminders.conditionalStop(windowMs);
503
+ const result = session.reminders.conditionalStop(windowMs);
504
+ if (result.stopped) await current.inspector?.stop();
505
+ return result;
491
506
  }
492
507
  if (method === "session/stop") {
493
508
  keys(p, []);
494
509
  const status = session.stop("Stopped by the host");
495
- await current.stopMcp?.();
496
- return wireStatus(status, session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot());
510
+ try { await current.inspector?.stop(); } finally { await current.stopMcp?.(); }
511
+ return { ...wireStatus(status, session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()),
512
+ ...inspectorStatus(current) };
497
513
  }
498
514
  if (method === "session/model-calls") {
499
515
  keys(p, ["after", "limit"]);
@@ -576,8 +592,12 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
576
592
  bridge.disconnect();
577
593
  transfers?.dispose();
578
594
  opened?.session.reminders?.releaseTimer();
579
- if (opened?.stopMcp) await opened.stopMcp();
580
- opened?.close();
595
+ if (opened) {
596
+ // Without optional resources, storage ownership is released synchronously.
597
+ try { if (opened.inspector) await opened.inspector.stop(); } finally {
598
+ try { if (opened.stopMcp) await opened.stopMcp(); } finally { opened.close(); }
599
+ }
600
+ }
581
601
  },
582
602
  };
583
603
  }
@@ -1,10 +1,17 @@
1
- import { inferenceRelayAttempt } from "./capabilities/model/inference-relay.ts";
1
+ import { createInspection } from "./interfaces/inspector/state.ts";
2
+ import { inspectorProjection, managedInspector } from "./interfaces/inspector/managed.ts";
3
+ import type { InspectorBinding } from "./interfaces/inspector/config.ts";
4
+ import { reminderDefinitions, guardedReminderDefinitions } from "./capabilities/tools/reminders/index.ts";
5
+ import { timelineDefinitions } from "./capabilities/tools/timeline/index.ts";
6
+ import { readToolResultDefinition } from "./capabilities/tools/runtime/catalog.ts";
7
+ import { createRelayAuthority, inferenceRelayAttempt } from "./capabilities/model/inference-relay.ts";
2
8
  import { resolveInferenceRelayGrant } from "./util/inference-relay.ts";
9
+ import { resolveServiceEgress } from "./capabilities/tools/web/service-egress.ts";
3
10
  import { isCompatibleModel } from "./contracts/config-permissions.ts";
4
11
  import { validateMcpRuntimeHeaders } from "./util/mcp-config.ts";
5
12
  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";
13
+ import { createWebRegistry, directWebFetch, webUnavailable } from "./capabilities/tools/web/registry.ts";
14
+ import { exaServiceTransport } from "./capabilities/tools/web/exa-transport.ts";
8
15
  import { webDefinitions } from "./capabilities/tools/web/definitions.ts";
9
16
  import { compatibleInferenceKey } from "./runtime/config/inference-key.ts";
10
17
  import { wallReminderClock } from "./runtime/reminder-timer.ts";
@@ -17,7 +24,7 @@ import type { SessionStorage, SessionStorageAdapter } from "./contracts/storage.
17
24
  import type { ExecuteTool, Model } from "./contracts/loop.ts";
18
25
  import { loadScenario, scriptedCompatibilityKey } from "./capabilities/model/scenario-file.ts";
19
26
  import { scenarioAttempt } from "./capabilities/model/scenario-attempt.ts";
20
- import type { ModelRequest } from "./contracts/model-execution.ts";
27
+ import type { ModelAttempt, ModelRequest } from "./contracts/model-execution.ts";
21
28
  import type { LoadedScenario } from "./contracts/scenario.ts";
22
29
  export type { LoadedScenario, ScenarioHeader, ScenarioModelRecord, ScenarioRecord, ScenarioSend } from "./contracts/scenario.ts";
23
30
  export { loadScenario, parseScenario } from "./capabilities/model/scenario-file.ts";
@@ -41,6 +48,7 @@ import { imageValidationAvailable, validateManagedImage } from "./capabilities/a
41
48
  export interface ScriptedServerOptions {
42
49
  /** Directory of durable sessions, one SQLite file per session ID. */
43
50
  home?: string;
51
+ inspector?: InspectorBinding | "invalid";
44
52
  /** Storage location for a session ID, for tests that keep one location across servers. */
45
53
  adapter?: (sessionId: string) => SessionStorageAdapter;
46
54
  /** `<point>:<n>`: kill this process, without unwinding, right after the n-th
@@ -103,6 +111,8 @@ function withFaults(storage: SessionStorage, hit: (point: string) => void): Sess
103
111
  * protocol. In memory by default; durable when given a home or an adapter. */
104
112
  const BUILTINS = [echoDefinition, recordDefinition, holdDefinition];
105
113
  export function createScriptedServer(options: ScriptedServerOptions = {}) {
114
+ const webEgress = resolveServiceEgress(options.environment ?? process.env);
115
+ const exa = exaServiceTransport(webEgress);
106
116
  let fixtureEndpoint: string | undefined;
107
117
  if (options.providerEndpoint) {
108
118
  const url = new URL(options.providerEndpoint);
@@ -158,7 +168,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
158
168
  [...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(!isCompatibleModel(config.model) && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
159
169
  if (mode === "create" && paths) mkdirSync(paths.directory, { recursive: true });
160
170
  const makeWebTools = () => {
161
- const result = createWebRegistry(config, environment, { exa: options.webTransport ?? webFixture ?? exaHttpsTransport, http: options.webHttp ?? directWebFetch });
171
+ const result = createWebRegistry(config, environment, { exa: options.webTransport ?? webFixture ?? exa, http: options.webHttp ?? directWebFetch }, webEgress);
162
172
  if (!result.ok) throw new SessionOpenError("invalid_config", result.error.message);
163
173
  return result.value;
164
174
  };
@@ -200,10 +210,49 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
200
210
  return result;
201
211
  };
202
212
  const revisions = new Map<string, number>();
213
+ const relayAuthority = relayGrant && createRelayAuthority(relayGrant);
214
+ const unavailable = webUnavailable(config, webEgress);
215
+ const binding = options.inspector;
216
+ const project = binding && binding !== "invalid" ? inspectorProjection([
217
+ credential, compatibleKey, relayGrant?.bearerToken,
218
+ environment[config.webSearch?.apiKeyEnv ?? "EXA_API_KEY"],
219
+ config.webFetch?.backend === "exa" ? environment[config.webFetch.apiKeyEnv ?? "EXA_API_KEY"] : undefined,
220
+ ...Object.values(runtimeHeaders ?? {}).flatMap(headers => Object.values(headers)),
221
+ ]) : undefined;
222
+ const definitions = [...BUILTINS, notifyChannelDefinition,
223
+ ...(config.limits?.unattendedTurns === undefined ? reminderDefinitions : guardedReminderDefinitions),
224
+ ...(config.timelineTools ? timelineDefinitions : []), ...(catalog?.catalog ?? []),
225
+ ...(webTools?.map(tool => tool.definition) ?? []), ...[...(mcp?.bindings.values() ?? [])].map(tool => tool.definition)];
226
+ if (catalog || webTools?.length || mcp?.bindings.size) definitions.push(readToolResultDefinition);
227
+ const inspection = project ? createInspection(config.system, definitions.map(({ name, description, parameters }) =>
228
+ ({ name, description, parameters })), storage, paths ? "sqlite" : "memory",
229
+ turnId => session.tools?.invocations(turnId) ?? [], unavailable, project) : undefined;
230
+ const inspector = binding ? managedInspector(binding, inspection, project) : undefined;
231
+ function observeAttempt(attempt: ModelAttempt, channel: string, turnId: number, scripted = false): ModelAttempt {
232
+ if (!inspection || !inspector?.active()) return attempt;
233
+ return async function* (request, signal) {
234
+ if (scripted) inspection.request(channel, JSON.stringify(request), turnId);
235
+ for await (const event of attempt(request, signal)) {
236
+ if (event.type === "response" && inspector.active()) inspection.response(channel, event.response);
237
+ yield event;
238
+ }
239
+ };
240
+ }
203
241
  const session = createSession({
204
242
  ...(script && options.reminderTime !== undefined && Number.isSafeInteger(options.reminderTime)
205
- ? { reminderClock: { ...wallReminderClock, now: () => options.reminderTime! } } : {}), ...(options.requests ? { captureContext: ({ context }: import("./contracts/context.ts").ContextCapture) =>
206
- revisions.set(context.channelId, context.timelineRevision) } : {}), systemPrompt: config.system, config, storage, imageInput, webTools, mcpTools: mcp?.bindings, ...(catalog ? { catalog } : {}), configureTurn(turn) {
243
+ ? { reminderClock: { ...wallReminderClock, now: () => options.reminderTime! } } : {}),
244
+ ...(options.requests || inspection ? { captureContext: capture => {
245
+ if (options.requests) revisions.set(capture.context.channelId, capture.context.timelineRevision);
246
+ if (inspector?.active()) inspection?.capture(capture);
247
+ } } : {}),
248
+ ...(inspection ? { observeModelCall: (...args) => {
249
+ if (inspector?.active()) inspection.modelCall(...args);
250
+ } } : {}),
251
+ systemPrompt: config.system, config, storage, imageInput, webTools, mcpTools: mcp?.bindings,
252
+ ...(catalog ? { catalog } : {}),
253
+ configureTurn(turn) {
254
+ const captureRequest = inspection && inspector?.active()
255
+ ? (body: string) => { if (inspector.active()) inspection.request(turn.channelId, body, turn.turnId); } : undefined;
207
256
  if (compatible) {
208
257
  const model: Model = async () => { throw new Error("Chat Completions requires a model attempt"); };
209
258
  bindModelAttempt(model, { scripted: false,
@@ -213,23 +262,24 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
213
262
  const metadata = attachments ? (id: string) => {
214
263
  const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
215
264
  } : undefined;
216
- return relayGrant ? inferenceRelayAttempt(compatible.model, relayGrant, metadata)
217
- : managedCompatibleAttempt(compatible, conversation, compatibleKey, undefined, metadata);
265
+ const attempt = relayAuthority ? inferenceRelayAttempt(compatible.model, relayAuthority, metadata, captureRequest)
266
+ : managedCompatibleAttempt(compatible, conversation, compatibleKey, captureRequest, metadata);
267
+ return observeAttempt(attempt, turn.channelId, turn.turnId);
218
268
  } });
219
269
  return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
220
270
  }
221
271
  if (config.model.protocol === "openrouter") {
222
272
  const model = (options.providerFactory ?? openRouter)(credential!, config.model.model);
223
- if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => openRouterAttempt(credential!, config.model.protocol === "openrouter" ? config.model.model : "", providerFetch, undefined,
273
+ if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => observeAttempt(openRouterAttempt(credential!, config.model.protocol === "openrouter" ? config.model.model : "", providerFetch, captureRequest,
224
274
  attachments ? { supported: imageInput, metadata(id) { const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined; },
225
275
  read(metadata) { return attachments!.readForInference(turn.channelId, metadata.id); },
226
- verify(metadata, signal) { return attachments!.verifyForInference(turn.channelId, metadata.id, signal); } } : undefined) });
276
+ verify(metadata, signal) { return attachments!.verifyForInference(turn.channelId, metadata.id, signal); } } : undefined), turn.channelId, turn.turnId) });
227
277
  return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
228
278
  }
229
279
  const model: Model = async () => { throw new Error("Scripted model requires a reserved attempt"); };
230
280
  bindModelAttempt(model, { scripted: true, ...(options.modelTimeoutMs === undefined ? {} : { settings: { timeoutMs: options.modelTimeoutMs } }), create: (step, ordinal) => {
231
281
  const next = scenarioAttempt(script!, turn.channelId, step!);
232
- return async function* (request, signal) {
282
+ return observeAttempt(async function* (request, signal) {
233
283
  // Offline rehearsal can observe the real provider projection while
234
284
  // retaining scripted records as the source of model decisions.
235
285
  if (fixtureEndpoint && imageInput && attachments && request.messages.some(message => message.role === "user" && message.parts)) {
@@ -260,11 +310,11 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
260
310
  yield { type: "text_delta", text: event.response.content };
261
311
  yield event;
262
312
  }
263
- };
313
+ }, turn.channelId, turn.turnId, true);
264
314
  } });
265
315
  return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
266
316
  } });
267
- return { session, config, imageInput, ...(mcp ? { mcpStatus: mcp.status, stopMcp: mcp.close } : {}), ...(attachments ? { attachments } : {}), close() { void mcp?.close(); attachments?.close(); opened.value.close(); }, commitConfig() {
317
+ return { session, config, imageInput, inspector, ...(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
318
  const saved = storage.saveConfig(config);
269
319
  if (!saved.ok && saved.error.code !== "incompatible") throw new SessionOpenError("storage_failure", saved.error.message);
270
320
  }, exportArchive: () => storage.exportArchive() };