@qlairoslabs/acp-client 0.13.9-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.
- package/CONSUMER_GUIDE.md +16 -0
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/native-harness/src/capabilities/model/inference-relay.ts +3 -2
- package/src/native-harness/src/client.ts +2 -0
- package/src/native-harness/src/contracts/inspector.ts +5 -0
- package/src/native-harness/src/contracts/operator-controls.ts +1 -0
- package/src/native-harness/src/contracts/protocol.ts +1 -0
- package/src/native-harness/src/interfaces/cli/serve.ts +10 -7
- package/src/native-harness/src/interfaces/inspector/config.ts +17 -0
- package/src/native-harness/src/interfaces/inspector/managed.ts +51 -0
- package/src/native-harness/src/interfaces/inspector/server.ts +13 -8
- package/src/native-harness/src/interfaces/inspector/state.ts +4 -3
- package/src/native-harness/src/interfaces/protocol/server.ts +25 -7
- package/src/native-harness/src/testing.ts +56 -11
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
|
package/package.json
CHANGED
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";
|
|
@@ -48,7 +48,8 @@ async function relayRefusal(response: { status: number; body: ReadableStream<Uin
|
|
|
48
48
|
/** A relay attempt owns its direct dispatcher and releases it on any terminal
|
|
49
49
|
* event, including cancellation by the model runner. */
|
|
50
50
|
export function inferenceRelayAttempt(model: string, authority: RelayAuthority,
|
|
51
|
-
metadata?: Parameters<typeof openAICompatibleAttempt>[5]
|
|
51
|
+
metadata?: Parameters<typeof openAICompatibleAttempt>[5],
|
|
52
|
+
onRequest?: Parameters<typeof openAICompatibleAttempt>[4]): ModelAttempt {
|
|
52
53
|
return async function* (request, signal) {
|
|
53
54
|
const captured = authority.capture(), { grant } = captured;
|
|
54
55
|
const isExpired = () => grant.expiresAtMs !== undefined && Date.now() >= grant.expiresAtMs;
|
|
@@ -88,7 +89,7 @@ export function inferenceRelayAttempt(model: string, authority: RelayAuthority,
|
|
|
88
89
|
if (refusal === "native_grant_revoked") authority.revoke(captured);
|
|
89
90
|
return new Response(null, { status: response.status });
|
|
90
91
|
}) as unknown as typeof fetch;
|
|
91
|
-
const attempt = openAICompatibleAttempt(grant.baseUrl, model, grant.bearerToken, directFetch,
|
|
92
|
+
const attempt = openAICompatibleAttempt(grant.baseUrl, model, grant.bearerToken, directFetch, onRequest, metadata);
|
|
92
93
|
const token = grant.bearerToken;
|
|
93
94
|
const marker = "[relay credential hidden]";
|
|
94
95
|
const redact = (text: string) => text.replaceAll(token, marker.includes(token) ? "[ ]" : marker);
|
|
@@ -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";
|
|
@@ -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
|
+
inspector?: import("./inspector.ts").InspectorStatus;
|
|
5
6
|
webUnavailable?: import("./web.ts").WebUnavailable;
|
|
6
7
|
mcpServers?: Record<string, import("./mcp.ts").McpServerStatus>;
|
|
7
8
|
sessionId: string;
|
|
@@ -141,6 +141,7 @@ export interface TurnStatus {
|
|
|
141
141
|
/** `idle`, `suspended` and unresolved interrupted work are distinguishable:
|
|
142
142
|
* see SessionStatus in the session contract for the exact derivation. */
|
|
143
143
|
export interface StatusResult {
|
|
144
|
+
inspector?: import("./inspector.ts").InspectorStatus;
|
|
144
145
|
webUnavailable?: import("./web.ts").WebUnavailable;
|
|
145
146
|
mcpServers?: Record<string, import("./mcp.ts").McpServerStatus>;
|
|
146
147
|
sessionId: string; revision: number;
|
|
@@ -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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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
|
-
/**
|
|
4
|
-
export function serveInspector(inspection: Inspection,
|
|
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:
|
|
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(
|
|
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
|
};
|
|
@@ -27,7 +27,8 @@ function read<T>(result: StorageResult<T>) {
|
|
|
27
27
|
export function createInspection(systemPrompt: string, tools: readonly ToolDefinition[],
|
|
28
28
|
reads: InspectionStorageReads, storage: string,
|
|
29
29
|
webInvocations?: (turnId: number) => import("../../contracts/tools.ts").ToolInvocation[],
|
|
30
|
-
webUnavailable: import("../../contracts/web.ts").WebUnavailable = {}
|
|
30
|
+
webUnavailable: import("../../contracts/web.ts").WebUnavailable = {},
|
|
31
|
+
project: (body: unknown) => unknown = body => body) {
|
|
31
32
|
const instructions = composeSystemPrompt(systemPrompt);
|
|
32
33
|
const captures = new Map<string, { turnId: number; metadata: NonNullable<InspectedInference["context"]> }>();
|
|
33
34
|
const channels = new Map<string, InspectedInference[]>();
|
|
@@ -87,14 +88,14 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
|
|
|
87
88
|
const capture = captures.get(id);
|
|
88
89
|
requests.push({ ...(capture && capture.turnId === turnId ? { context: capture.metadata } : {}),
|
|
89
90
|
number: (requests.at(-1)?.number ?? 0) + 1, turnId, at: new Date().toISOString(),
|
|
90
|
-
body: Buffer.byteLength(body) <= CAPTURE_BYTES ? JSON.parse(body) : { omitted: true } });
|
|
91
|
+
body: Buffer.byteLength(body) <= CAPTURE_BYTES ? project(JSON.parse(body)) : { omitted: true } });
|
|
91
92
|
if (requests.length > CAPTURE_LIMIT) requests.shift();
|
|
92
93
|
invalidate();
|
|
93
94
|
},
|
|
94
95
|
response(id: string, message: Extract<Message, { role: "assistant" }>) {
|
|
95
96
|
const request = channels.get(id)?.at(-1);
|
|
96
97
|
if (!request) return;
|
|
97
|
-
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 };
|
|
98
99
|
invalidate();
|
|
99
100
|
},
|
|
100
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";
|
|
@@ -52,6 +53,7 @@ export interface OpenedSession {
|
|
|
52
53
|
webUnavailable?: import("../../contracts/web.ts").WebUnavailable;
|
|
53
54
|
mcpStatus?(): Record<string, import("../../contracts/mcp.ts").McpServerStatus>;
|
|
54
55
|
stopMcp?(): Promise<void>;
|
|
56
|
+
inspector?: { start(session: PersistentSession): void; status(): InspectorStatus; stop(): Promise<void> };
|
|
55
57
|
}
|
|
56
58
|
export interface ProtocolServerOptions {
|
|
57
59
|
durable?: boolean;
|
|
@@ -186,7 +188,9 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
186
188
|
* stop first: a resume in it may already have handed a turn to an executor. */
|
|
187
189
|
async function abandon(opened: OpenedSession, batch: boolean) {
|
|
188
190
|
if (batch) { try { opened.session.stop("Open failed"); } catch { /* Storage may be the failure. */ } }
|
|
189
|
-
try { await opened.
|
|
191
|
+
try { await opened.inspector?.stop(); } finally {
|
|
192
|
+
try { await opened.stopMcp?.(); } finally { opened.close(); }
|
|
193
|
+
}
|
|
190
194
|
}
|
|
191
195
|
|
|
192
196
|
/** Read one snapshot, then keep every later notification behind the response.
|
|
@@ -200,7 +204,11 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
200
204
|
const image = opened.imageInput && (opened.session.reminders?.executable() ?? true)
|
|
201
205
|
? { imageInput: true as const, imageLimits: { formats: ["image/png", "image/jpeg", "image/webp"], fileBytes: ATTACHMENT_LIMITS.fileBytes,
|
|
202
206
|
turnBytes: ATTACHMENT_LIMITS.imageBytesPerTurn, maxImages: ATTACHMENT_LIMITS.references, maxSide: ATTACHMENT_LIMITS.imageSide, maxPixels: ATTACHMENT_LIMITS.imagePixels } } : {};
|
|
203
|
-
return { sessionId: value.sessionId, lifecycle: value.lifecycle, revision, ...image, ...(opened.webUnavailable ? { webUnavailable: opened.webUnavailable } : {}), ...(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() } : {};
|
|
204
212
|
}
|
|
205
213
|
|
|
206
214
|
function holdAfterResponse(start?: () => void) {
|
|
@@ -289,6 +297,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
289
297
|
if (opened.session.reminders) holdAfterResponse();
|
|
290
298
|
results = finish?.();
|
|
291
299
|
reminderResult = prepareReminders(opened.session, reminderBatch);
|
|
300
|
+
opened.inspector?.start(opened.session);
|
|
292
301
|
current = opened;
|
|
293
302
|
if (batch) startup = { batch, results: results! };
|
|
294
303
|
} catch (error) { try { await abandon(opened, !!batch); } catch { /* Preserve startup failure. */ } throw error; }
|
|
@@ -323,6 +332,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
323
332
|
const results = finish?.();
|
|
324
333
|
opened.commitConfig?.();
|
|
325
334
|
const reminderResult = prepareReminders(opened.session, reminderBatch);
|
|
335
|
+
opened.inspector?.start(opened.session);
|
|
326
336
|
const result = ready(opened);
|
|
327
337
|
holdAfterResponse(() => { if (current === opened) opened.session.start(); });
|
|
328
338
|
current = opened;
|
|
@@ -460,6 +470,7 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
460
470
|
if (method === "session/status") {
|
|
461
471
|
keys(p, []);
|
|
462
472
|
return { ...wireStatus(session.status(), session.operatorReads ? readValue(session.operatorReads.readExecution()).value : session.snapshot()),
|
|
473
|
+
...inspectorStatus(current),
|
|
463
474
|
...(current.webUnavailable ? { webUnavailable: current.webUnavailable } : {}),
|
|
464
475
|
...(current.mcpStatus ? { mcpServers: current.mcpStatus() } : {}) };
|
|
465
476
|
}
|
|
@@ -489,13 +500,16 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
489
500
|
const windowMs = p.unlessDueWithinMs ?? 0;
|
|
490
501
|
if (p.ifIdle !== true || p.unlessDueWithinMs === null || !Number.isSafeInteger(windowMs) || windowMs < 0) bad("Invalid conditional stop");
|
|
491
502
|
if (!session.reminders) throw new Fault("invalid_state", "Conditional stop is unavailable");
|
|
492
|
-
|
|
503
|
+
const result = session.reminders.conditionalStop(windowMs);
|
|
504
|
+
if (result.stopped) await current.inspector?.stop();
|
|
505
|
+
return result;
|
|
493
506
|
}
|
|
494
507
|
if (method === "session/stop") {
|
|
495
508
|
keys(p, []);
|
|
496
509
|
const status = session.stop("Stopped by the host");
|
|
497
|
-
await current.stopMcp?.();
|
|
498
|
-
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) };
|
|
499
513
|
}
|
|
500
514
|
if (method === "session/model-calls") {
|
|
501
515
|
keys(p, ["after", "limit"]);
|
|
@@ -578,8 +592,12 @@ export function createProtocolServer(open: (request: SessionRequest) => Promise<
|
|
|
578
592
|
bridge.disconnect();
|
|
579
593
|
transfers?.dispose();
|
|
580
594
|
opened?.session.reminders?.releaseTimer();
|
|
581
|
-
if (opened
|
|
582
|
-
|
|
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
|
+
}
|
|
583
601
|
},
|
|
584
602
|
};
|
|
585
603
|
}
|
|
@@ -1,3 +1,9 @@
|
|
|
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";
|
|
1
7
|
import { createRelayAuthority, inferenceRelayAttempt } from "./capabilities/model/inference-relay.ts";
|
|
2
8
|
import { resolveInferenceRelayGrant } from "./util/inference-relay.ts";
|
|
3
9
|
import { resolveServiceEgress } from "./capabilities/tools/web/service-egress.ts";
|
|
@@ -18,7 +24,7 @@ import type { SessionStorage, SessionStorageAdapter } from "./contracts/storage.
|
|
|
18
24
|
import type { ExecuteTool, Model } from "./contracts/loop.ts";
|
|
19
25
|
import { loadScenario, scriptedCompatibilityKey } from "./capabilities/model/scenario-file.ts";
|
|
20
26
|
import { scenarioAttempt } from "./capabilities/model/scenario-attempt.ts";
|
|
21
|
-
import type { ModelRequest } from "./contracts/model-execution.ts";
|
|
27
|
+
import type { ModelAttempt, ModelRequest } from "./contracts/model-execution.ts";
|
|
22
28
|
import type { LoadedScenario } from "./contracts/scenario.ts";
|
|
23
29
|
export type { LoadedScenario, ScenarioHeader, ScenarioModelRecord, ScenarioRecord, ScenarioSend } from "./contracts/scenario.ts";
|
|
24
30
|
export { loadScenario, parseScenario } from "./capabilities/model/scenario-file.ts";
|
|
@@ -42,6 +48,7 @@ import { imageValidationAvailable, validateManagedImage } from "./capabilities/a
|
|
|
42
48
|
export interface ScriptedServerOptions {
|
|
43
49
|
/** Directory of durable sessions, one SQLite file per session ID. */
|
|
44
50
|
home?: string;
|
|
51
|
+
inspector?: InspectorBinding | "invalid";
|
|
45
52
|
/** Storage location for a session ID, for tests that keep one location across servers. */
|
|
46
53
|
adapter?: (sessionId: string) => SessionStorageAdapter;
|
|
47
54
|
/** `<point>:<n>`: kill this process, without unwinding, right after the n-th
|
|
@@ -204,10 +211,48 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
204
211
|
};
|
|
205
212
|
const revisions = new Map<string, number>();
|
|
206
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
|
+
}
|
|
207
241
|
const session = createSession({
|
|
208
242
|
...(script && options.reminderTime !== undefined && Number.isSafeInteger(options.reminderTime)
|
|
209
|
-
? { reminderClock: { ...wallReminderClock, now: () => options.reminderTime! } } : {}),
|
|
210
|
-
|
|
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;
|
|
211
256
|
if (compatible) {
|
|
212
257
|
const model: Model = async () => { throw new Error("Chat Completions requires a model attempt"); };
|
|
213
258
|
bindModelAttempt(model, { scripted: false,
|
|
@@ -217,23 +262,24 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
217
262
|
const metadata = attachments ? (id: string) => {
|
|
218
263
|
const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
|
|
219
264
|
} : undefined;
|
|
220
|
-
|
|
221
|
-
: managedCompatibleAttempt(compatible, conversation, compatibleKey,
|
|
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);
|
|
222
268
|
} });
|
|
223
269
|
return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
|
|
224
270
|
}
|
|
225
271
|
if (config.model.protocol === "openrouter") {
|
|
226
272
|
const model = (options.providerFactory ?? openRouter)(credential!, config.model.model);
|
|
227
|
-
if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => openRouterAttempt(credential!, config.model.protocol === "openrouter" ? config.model.model : "", providerFetch,
|
|
273
|
+
if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => observeAttempt(openRouterAttempt(credential!, config.model.protocol === "openrouter" ? config.model.model : "", providerFetch, captureRequest,
|
|
228
274
|
attachments ? { supported: imageInput, metadata(id) { const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined; },
|
|
229
275
|
read(metadata) { return attachments!.readForInference(turn.channelId, metadata.id); },
|
|
230
|
-
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) });
|
|
231
277
|
return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
|
|
232
278
|
}
|
|
233
279
|
const model: Model = async () => { throw new Error("Scripted model requires a reserved attempt"); };
|
|
234
280
|
bindModelAttempt(model, { scripted: true, ...(options.modelTimeoutMs === undefined ? {} : { settings: { timeoutMs: options.modelTimeoutMs } }), create: (step, ordinal) => {
|
|
235
281
|
const next = scenarioAttempt(script!, turn.channelId, step!);
|
|
236
|
-
return async function* (request, signal) {
|
|
282
|
+
return observeAttempt(async function* (request, signal) {
|
|
237
283
|
// Offline rehearsal can observe the real provider projection while
|
|
238
284
|
// retaining scripted records as the source of model decisions.
|
|
239
285
|
if (fixtureEndpoint && imageInput && attachments && request.messages.some(message => message.role === "user" && message.parts)) {
|
|
@@ -264,12 +310,11 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
|
|
|
264
310
|
yield { type: "text_delta", text: event.response.content };
|
|
265
311
|
yield event;
|
|
266
312
|
}
|
|
267
|
-
};
|
|
313
|
+
}, turn.channelId, turn.turnId, true);
|
|
268
314
|
} });
|
|
269
315
|
return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
|
|
270
316
|
} });
|
|
271
|
-
|
|
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() {
|
|
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() {
|
|
273
318
|
const saved = storage.saveConfig(config);
|
|
274
319
|
if (!saved.ok && saved.error.code !== "incompatible") throw new SessionOpenError("storage_failure", saved.error.message);
|
|
275
320
|
}, exportArchive: () => storage.exportArchive() };
|