@av-pi-studio/server 0.0.115 → 0.0.117

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 (50) hide show
  1. package/README.md +8 -8
  2. package/dist/agent/index.d.ts +0 -1
  3. package/dist/agent/index.js +0 -1
  4. package/dist/agent/mcp-server.d.ts +3 -13
  5. package/dist/agent/mcp-server.js +2 -10
  6. package/dist/agent/provider-contract.d.ts +0 -7
  7. package/dist/agent/providers/mock/mock-provider.d.ts +12 -3
  8. package/dist/agent/providers/mock/mock-provider.js +46 -7
  9. package/dist/agent/providers/mock/stream-script.d.ts +28 -0
  10. package/dist/agent/providers/mock/stream-script.js +57 -0
  11. package/dist/agent/providers/pi/agent.js +0 -7
  12. package/dist/daemon/bootstrap.d.ts +18 -2
  13. package/dist/daemon/bootstrap.js +63 -13
  14. package/dist/daemon/dev-bootstrap.d.ts +7 -0
  15. package/dist/daemon/dev-bootstrap.js +34 -5
  16. package/dist/daemon/dev-main.js +5 -2
  17. package/dist/daemon/loopback.d.ts +4 -0
  18. package/dist/daemon/loopback.js +12 -0
  19. package/dist/daemon/main.js +4 -10
  20. package/dist/extensions/curated-packs.d.ts +0 -1
  21. package/dist/extensions/curated-packs.js +1 -6
  22. package/dist/extensions/sync-executor.js +1 -1
  23. package/dist/logging/index.d.ts +1 -0
  24. package/dist/logging/index.js +1 -0
  25. package/dist/logging/log-tap.d.ts +33 -0
  26. package/dist/logging/log-tap.js +233 -0
  27. package/dist/logging/logger.d.ts +6 -0
  28. package/dist/logging/logger.js +4 -0
  29. package/dist/observability/daemon-logs-rpc.d.ts +12 -0
  30. package/dist/observability/daemon-logs-rpc.js +17 -0
  31. package/dist/observability/daemon-logs-service.d.ts +67 -0
  32. package/dist/observability/daemon-logs-service.js +165 -0
  33. package/dist/observability/daemon-status-rpc.d.ts +12 -0
  34. package/dist/observability/daemon-status-rpc.js +21 -0
  35. package/dist/observability/daemon-status-service.d.ts +85 -0
  36. package/dist/observability/daemon-status-service.js +154 -0
  37. package/dist/test-support/auth-gated-rpc.d.ts +18 -0
  38. package/dist/test-support/auth-gated-rpc.js +80 -0
  39. package/dist/test-support/daemon-test-client.d.ts +43 -0
  40. package/dist/test-support/daemon-test-client.js +91 -0
  41. package/dist/test-support/external-fixtures-scenario.d.ts +30 -0
  42. package/dist/test-support/external-fixtures-scenario.js +223 -0
  43. package/dist/version.d.ts +2 -0
  44. package/dist/version.js +7 -0
  45. package/dist/ws/session.d.ts +11 -0
  46. package/dist/ws/session.js +11 -0
  47. package/dist/ws/ws-server.js +2 -0
  48. package/package.json +3 -3
  49. package/dist/agent/permissions.d.ts +0 -71
  50. package/dist/agent/permissions.js +0 -132
@@ -0,0 +1,154 @@
1
+ import { monitorEventLoopDelay, performance } from "node:perf_hooks";
2
+ import { SERVER_VERSION } from "../version.js";
3
+ /**
4
+ * Daemon status snapshots + per-session push (swe/features/daemon-status-rpc.md § Behavior &
5
+ * algorithms). One shared 5 s timer and one event-loop histogram exist only while at least one
6
+ * session is subscribed; with no subscribers the service holds no timer, no histogram and does
7
+ * no work. Each tick builds ONE snapshot shared by every subscriber.
8
+ */
9
+ export const DAEMON_STATUS_INTERVAL_MS = 5000;
10
+ export const systemSampler = {
11
+ cpuUsage: () => process.cpuUsage(),
12
+ memoryUsage: () => process.memoryUsage(),
13
+ createEventLoopHistogram: () => monitorEventLoopDelay({ resolution: 20 }),
14
+ now: () => performance.now(),
15
+ wallNow: () => Date.now(),
16
+ };
17
+ const compareClients = (a, b) => a.connectedAt - b.connectedAt || (a.clientId < b.clientId ? -1 : a.clientId > b.clientId ? 1 : 0);
18
+ function toClientInfo(session) {
19
+ return {
20
+ clientId: session.clientId,
21
+ clientType: session.clientType,
22
+ ...(session.appVersion !== undefined ? { appVersion: session.appVersion } : {}),
23
+ connectedAt: session.connectedAt,
24
+ ...(session.remoteAddress !== undefined ? { remoteAddress: session.remoteAddress } : {}),
25
+ transport: session.transport,
26
+ };
27
+ }
28
+ export class DaemonStatusService {
29
+ deps;
30
+ sampler;
31
+ startedAt;
32
+ startMonotonic;
33
+ subscribers = new Set();
34
+ timer = null;
35
+ histogram = null;
36
+ lastCpu = null;
37
+ constructor(deps) {
38
+ this.deps = deps;
39
+ this.sampler = deps.sampler ?? systemSampler;
40
+ // Process-level start captured at construction (bootstrap start); a daemon restart resets it.
41
+ this.startedAt = this.sampler.wallNow();
42
+ this.startMonotonic = this.sampler.now();
43
+ }
44
+ /** Build a snapshot. Advances the CPU baseline and resets the lag window. */
45
+ snapshot() {
46
+ const now = this.sampler.now();
47
+ const cpu = this.sampler.cpuUsage();
48
+ const micros = cpu.user + cpu.system;
49
+ const last = this.lastCpu;
50
+ const elapsedMicros = last ? (now - last.atMs) * 1000 : 0;
51
+ const cpuPercent = last && elapsedMicros > 0 ? ((micros - last.micros) / elapsedMicros) * 100 : 0;
52
+ this.lastCpu = { micros, atMs: now };
53
+ const meanNs = this.histogram?.mean ?? 0;
54
+ const eventLoopLagMs = Number.isFinite(meanNs) && meanNs > 0 ? meanNs / 1e6 : 0;
55
+ this.histogram?.reset();
56
+ const agentsByStatus = {};
57
+ for (const agent of this.deps.listAgents()) {
58
+ const status = agent.record.lastStatus;
59
+ agentsByStatus[status] = (agentsByStatus[status] ?? 0) + 1;
60
+ }
61
+ const mem = this.sampler.memoryUsage();
62
+ return {
63
+ version: SERVER_VERSION,
64
+ startedAt: this.startedAt,
65
+ uptimeMs: Math.max(0, now - this.startMonotonic),
66
+ pid: process.pid,
67
+ nodeVersion: process.version,
68
+ memory: { rss: mem.rss, heapUsed: mem.heapUsed, heapTotal: mem.heapTotal },
69
+ cpuPercent,
70
+ eventLoopLagMs,
71
+ agentsByStatus,
72
+ clients: this.deps.getActiveSessions().map(toClientInfo).toSorted(compareClients),
73
+ };
74
+ }
75
+ /**
76
+ * One-shot status. Without subscribers no sampling runs, so `cpuPercent` and `eventLoopLagMs`
77
+ * are 0 (no window to measure): use `subscribe` for live gauges.
78
+ */
79
+ oneShot() {
80
+ if (this.timer !== null)
81
+ return this.snapshot();
82
+ this.startSampling(false);
83
+ try {
84
+ return this.snapshot();
85
+ }
86
+ finally {
87
+ this.stopSampling();
88
+ }
89
+ }
90
+ /** Idempotent per session; always returns a fresh snapshot. */
91
+ subscribe(session) {
92
+ this.subscribers.add(session);
93
+ if (this.timer === null)
94
+ this.startSampling(true);
95
+ this.deps.logger?.debug({ clientId: session.clientId }, "daemon status subscribed");
96
+ return { ok: true, intervalMs: DAEMON_STATUS_INTERVAL_MS, status: this.snapshot() };
97
+ }
98
+ unsubscribe(session) {
99
+ if (!this.subscribers.delete(session))
100
+ return;
101
+ this.deps.logger?.debug({ clientId: session.clientId }, "daemon status unsubscribed");
102
+ if (this.subscribers.size === 0)
103
+ this.stopSampling();
104
+ }
105
+ /** `SessionSubscriptions` disposer: same as unsubscribe, safe when not subscribed. */
106
+ disposeSession(session) {
107
+ this.unsubscribe(session);
108
+ }
109
+ /** Release the timer and histogram (daemon shutdown). */
110
+ dispose() {
111
+ this.subscribers.clear();
112
+ this.stopSampling();
113
+ }
114
+ startSampling(withTimer) {
115
+ const histogram = this.sampler.createEventLoopHistogram();
116
+ histogram.enable();
117
+ this.histogram = histogram;
118
+ // Baseline so the first snapshot after this point has a window to measure against.
119
+ const cpu = this.sampler.cpuUsage();
120
+ this.lastCpu = { micros: cpu.user + cpu.system, atMs: this.sampler.now() };
121
+ if (!withTimer)
122
+ return;
123
+ this.timer = setInterval(() => this.tick(), DAEMON_STATUS_INTERVAL_MS);
124
+ this.timer.unref();
125
+ }
126
+ stopSampling() {
127
+ if (this.timer !== null)
128
+ clearInterval(this.timer);
129
+ this.timer = null;
130
+ this.histogram?.disable();
131
+ this.histogram = null;
132
+ this.lastCpu = null;
133
+ }
134
+ tick() {
135
+ if (this.subscribers.size === 0) {
136
+ this.stopSampling();
137
+ return;
138
+ }
139
+ const envelope = {
140
+ type: "session",
141
+ message: { type: "daemon_status_update", payload: this.snapshot() },
142
+ };
143
+ for (const session of this.subscribers) {
144
+ try {
145
+ this.deps.send(session, envelope);
146
+ }
147
+ catch {
148
+ // Dead socket: drop only this subscriber; its close path also cleans up.
149
+ this.unsubscribe(session);
150
+ }
151
+ }
152
+ }
153
+ }
154
+ //# sourceMappingURL=daemon-status-service.js.map
@@ -0,0 +1,18 @@
1
+ import { HandlerRegistry } from "../ws/router.js";
2
+ import type { Session } from "../ws/session.js";
3
+ /**
4
+ * Password-protected `createWebSocketServer` + `HandlerRegistry` harness for "authenticated only"
5
+ * tests of an RPC family (sprint-084/085). Tests only; not part of the daemon runtime.
6
+ */
7
+ export declare const AUTH_TEST_PASSWORD = "hunter2";
8
+ export interface AuthGatedServer {
9
+ port: number;
10
+ close(): Promise<void>;
11
+ }
12
+ /** Starts a protected server; `register` receives the registry and the live session set. */
13
+ export declare function startAuthGatedServer(register: (registry: HandlerRegistry, sessions: () => Session[]) => void): Promise<AuthGatedServer>;
14
+ /** HTTP status of the rejected upgrade for a socket that presents no password. */
15
+ export declare function unauthenticatedUpgradeStatus(port: number): Promise<number | "open">;
16
+ /** One authenticated hello + RPC round trip; resolves with the inner reply message. */
17
+ export declare function authenticatedRpc(port: number, type: string, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
18
+ //# sourceMappingURL=auth-gated-rpc.d.ts.map
@@ -0,0 +1,80 @@
1
+ import { createServer } from "node:http";
2
+ import bcrypt from "bcryptjs";
3
+ import { WebSocket } from "ws";
4
+ import { WS_BEARER_SUBPROTOCOL_PREFIX, createPasswordAuth } from "../auth/password-auth.js";
5
+ import { silentLogger } from "../logging/logger.js";
6
+ import { HandlerRegistry, routeTextFrame } from "../ws/router.js";
7
+ import { createWebSocketServer } from "../ws/ws-server.js";
8
+ import { listeningPort, messageOf } from "./daemon-test-client.js";
9
+ /**
10
+ * Password-protected `createWebSocketServer` + `HandlerRegistry` harness for "authenticated only"
11
+ * tests of an RPC family (sprint-084/085). Tests only; not part of the daemon runtime.
12
+ */
13
+ export const AUTH_TEST_PASSWORD = "hunter2";
14
+ /** Starts a protected server; `register` receives the registry and the live session set. */
15
+ export async function startAuthGatedServer(register) {
16
+ const http = createServer();
17
+ const registry = new HandlerRegistry(silentLogger());
18
+ const wsHandle = createWebSocketServer(http, {
19
+ serverId: "srv-auth-test",
20
+ version: "0.0.0-test",
21
+ auth: createPasswordAuth(bcrypt.hashSync(AUTH_TEST_PASSWORD, 4)),
22
+ onMessage: (session, frame) => {
23
+ if ("text" in frame)
24
+ void routeTextFrame(session, frame.text, registry);
25
+ },
26
+ });
27
+ register(registry, () => [...wsHandle.sessions]);
28
+ await new Promise((resolve) => http.listen(0, "127.0.0.1", () => resolve()));
29
+ return {
30
+ port: await listeningPort(http),
31
+ close: async () => {
32
+ await wsHandle.close();
33
+ http.close();
34
+ },
35
+ };
36
+ }
37
+ /** HTTP status of the rejected upgrade for a socket that presents no password. */
38
+ export function unauthenticatedUpgradeStatus(port) {
39
+ const ws = new WebSocket(`ws://127.0.0.1:${port}`);
40
+ return new Promise((resolve) => {
41
+ ws.once("unexpected-response", (_req, res) => resolve(res.statusCode ?? 0));
42
+ ws.once("open", () => {
43
+ ws.close();
44
+ resolve("open");
45
+ });
46
+ ws.once("error", () => undefined);
47
+ });
48
+ }
49
+ /** One authenticated hello + RPC round trip; resolves with the inner reply message. */
50
+ export async function authenticatedRpc(port, type, body = {}) {
51
+ const ws = new WebSocket(`ws://127.0.0.1:${port}`, [
52
+ `${WS_BEARER_SUBPROTOCOL_PREFIX}${AUTH_TEST_PASSWORD}`,
53
+ ]);
54
+ const reply = Promise.withResolvers();
55
+ ws.on("message", (data) => {
56
+ const frame = JSON.parse(data.toString("utf8"));
57
+ if (frame.type === "status") {
58
+ ws.send(JSON.stringify({ type: "session", message: { ...body, type, requestId: "auth-rpc" } }));
59
+ }
60
+ else {
61
+ reply.resolve(messageOf(frame));
62
+ }
63
+ });
64
+ ws.once("open", () => {
65
+ ws.send(JSON.stringify({
66
+ type: "hello",
67
+ clientId: "auth-client",
68
+ clientType: "cli",
69
+ protocolVersion: 1,
70
+ }));
71
+ });
72
+ ws.once("error", reply.reject);
73
+ try {
74
+ return await reply.promise;
75
+ }
76
+ finally {
77
+ ws.close();
78
+ }
79
+ }
80
+ //# sourceMappingURL=auth-gated-rpc.js.map
@@ -0,0 +1,43 @@
1
+ import type { Server } from "node:http";
2
+ import { WebSocket } from "ws";
3
+ /**
4
+ * Shared raw-`ws` client for daemon-level tests and the external-fixture recorder (sprint-083).
5
+ * Speaks the wire protocol directly (hello → `status`, `{type:"session",message}` envelopes with a
6
+ * stamped `requestId`) so a test sees exactly what an external client sees. Not part of the
7
+ * daemon's runtime surface; exported only for tests/scripts.
8
+ */
9
+ /** One top-level frame exactly as received: `status`, `pong`, `{type:"session",message}`, … */
10
+ export type WireFrame = Record<string, unknown>;
11
+ export interface TestClientOptions {
12
+ clientType?: string;
13
+ appVersion?: string;
14
+ capabilities?: Record<string, boolean>;
15
+ }
16
+ export interface TestClient {
17
+ ws: WebSocket;
18
+ /** Every top-level frame received so far, in arrival order (the handshake `status` first). */
19
+ frames: WireFrame[];
20
+ /** The handshake `status` frame. */
21
+ status: WireFrame;
22
+ /** Sends a raw top-level frame as JSON. */
23
+ send(frame: WireFrame): void;
24
+ /** Sends `{type:"session",message:{...body,type,requestId}}` and resolves with the full reply
25
+ * frame correlated by `requestId` (rejects after 4 s). */
26
+ rpcFrame(type: string, body?: WireFrame): Promise<WireFrame>;
27
+ /** Like `rpcFrame`, resolving with the inner session message. */
28
+ rpc(type: string, body?: WireFrame): Promise<WireFrame>;
29
+ /** Polls the frame log for the first frame matching `predicate` (default 4 s timeout). */
30
+ waitFor(predicate: (frame: WireFrame) => boolean, timeoutMs?: number): Promise<WireFrame>;
31
+ close(): Promise<void>;
32
+ }
33
+ export declare const RPC_TIMEOUT_MS = 4000;
34
+ /** The session message inside a `{type:"session",message}` frame; any other frame is its own
35
+ * message (`status`, `pong`, …). */
36
+ export declare function messageOf(frame: WireFrame): WireFrame;
37
+ /**
38
+ * The port the OS assigned to `server`. Every dev daemon in tests binds `port: 0` and learns its
39
+ * port here; guessing from a fixed range collides across vitest's parallel processes.
40
+ */
41
+ export declare function listeningPort(server: Server): Promise<number>;
42
+ export declare function connectTestClient(port: number, options?: TestClientOptions): Promise<TestClient>;
43
+ //# sourceMappingURL=daemon-test-client.d.ts.map
@@ -0,0 +1,91 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { WebSocket } from "ws";
3
+ export const RPC_TIMEOUT_MS = 4000;
4
+ /** The session message inside a `{type:"session",message}` frame; any other frame is its own
5
+ * message (`status`, `pong`, …). */
6
+ export function messageOf(frame) {
7
+ return frame.type === "session" ? frame.message : frame;
8
+ }
9
+ /**
10
+ * The port the OS assigned to `server`. Every dev daemon in tests binds `port: 0` and learns its
11
+ * port here; guessing from a fixed range collides across vitest's parallel processes.
12
+ */
13
+ export function listeningPort(server) {
14
+ if (server.listening)
15
+ return Promise.resolve(server.address().port);
16
+ const { promise, resolve, reject } = Promise.withResolvers();
17
+ server.once("listening", () => resolve(server.address().port));
18
+ server.once("error", reject);
19
+ return promise;
20
+ }
21
+ export async function connectTestClient(port, options = {}) {
22
+ const ws = new WebSocket(`ws://127.0.0.1:${port}`);
23
+ const frames = [];
24
+ const replies = new Map();
25
+ const handshake = Promise.withResolvers();
26
+ ws.once("error", handshake.reject);
27
+ ws.on("message", (data) => {
28
+ const frame = JSON.parse(data.toString("utf8"));
29
+ frames.push(frame);
30
+ const requestId = messageOf(frame).requestId;
31
+ if (typeof requestId === "string")
32
+ replies.get(requestId)?.(frame);
33
+ if (frame.type === "status")
34
+ handshake.resolve(frame);
35
+ });
36
+ ws.once("open", () => {
37
+ ws.send(JSON.stringify({
38
+ type: "hello",
39
+ clientId: `test-${randomUUID()}`,
40
+ clientType: options.clientType ?? "cli",
41
+ protocolVersion: 1,
42
+ ...(options.appVersion !== undefined ? { appVersion: options.appVersion } : {}),
43
+ ...(options.capabilities !== undefined ? { capabilities: options.capabilities } : {}),
44
+ }));
45
+ });
46
+ const status = await handshake.promise;
47
+ const waitFor = async (predicate, timeoutMs = RPC_TIMEOUT_MS) => {
48
+ const deadline = Date.now() + timeoutMs;
49
+ for (;;) {
50
+ const found = frames.find(predicate);
51
+ if (found)
52
+ return found;
53
+ if (Date.now() > deadline)
54
+ throw new Error("waitFor: timed out waiting for a matching frame");
55
+ await new Promise((resolve) => setTimeout(resolve, 10));
56
+ }
57
+ };
58
+ const rpcFrame = (type, body = {}) => {
59
+ const requestId = `req-${randomUUID()}`;
60
+ const { promise, resolve, reject } = Promise.withResolvers();
61
+ const timer = setTimeout(() => {
62
+ replies.delete(requestId);
63
+ reject(new Error(`rpc timeout: ${type}`));
64
+ }, RPC_TIMEOUT_MS);
65
+ replies.set(requestId, (frame) => {
66
+ clearTimeout(timer);
67
+ replies.delete(requestId);
68
+ resolve(frame);
69
+ });
70
+ ws.send(JSON.stringify({ type: "session", message: { ...body, type, requestId } }));
71
+ return promise;
72
+ };
73
+ return {
74
+ ws,
75
+ frames,
76
+ status,
77
+ send: (frame) => ws.send(JSON.stringify(frame)),
78
+ rpcFrame,
79
+ rpc: async (type, body) => messageOf(await rpcFrame(type, body)),
80
+ waitFor,
81
+ close: async () => {
82
+ if (ws.readyState === WebSocket.CLOSED)
83
+ return;
84
+ const closed = Promise.withResolvers();
85
+ ws.once("close", () => closed.resolve());
86
+ ws.close();
87
+ await closed.promise;
88
+ },
89
+ };
90
+ }
91
+ //# sourceMappingURL=daemon-test-client.js.map
@@ -0,0 +1,30 @@
1
+ import type { DevBootstrapHandle } from "../daemon/dev-bootstrap.js";
2
+ import { LogTap } from "../logging/log-tap.js";
3
+ import { type Logger } from "../logging/logger.js";
4
+ import { type TestClient, type WireFrame } from "./daemon-test-client.js";
5
+ /**
6
+ * The scripted dev-daemon scenario behind the external-client wire fixtures
7
+ * (swe/architecture/external-client-fixtures.md). Shared by the Layer B contract test
8
+ * (`daemon/external-fixtures-e2e.test.ts`) and the recorder script
9
+ * (`scripts/record-external-fixtures.ts`), so what is recorded is exactly what is verified.
10
+ *
11
+ * Drives every daemon-output type through its real path and returns the FIRST captured frame per
12
+ * fixture variant key (the manifest `file` stem, e.g. `agent_stream.tool_call.partial`). Matching
13
+ * is by predicate over the frame log, never by index.
14
+ */
15
+ /** The dev daemon must be started with at least this `mockTurnDelayMs` so a mock turn is still
16
+ * running when `interrupt_agent` arrives (`turn_canceled`). */
17
+ export declare const SCENARIO_MOCK_TURN_DELAY_MS = 150;
18
+ /**
19
+ * Dev-daemon options the scenario needs: the turn delay plus a tapped silent-output logger, so the
20
+ * `daemon_logs_*` stage 2 steps have a stream (`logTap` is shared with the bootstrap's service).
21
+ */
22
+ export declare function scenarioDaemonOptions(): {
23
+ logger: Logger;
24
+ logTap: LogTap;
25
+ mockTurnDelayMs: number;
26
+ };
27
+ /** Fixture-variant key for `frame`, or `undefined` when the frame is not a fixtured variant. */
28
+ export declare function variantKey(frame: WireFrame): string | undefined;
29
+ export declare function runExternalFixtureScenario(dev: DevBootstrapHandle, client: TestClient): Promise<Map<string, WireFrame>>;
30
+ //# sourceMappingURL=external-fixtures-scenario.d.ts.map
@@ -0,0 +1,223 @@
1
+ import { PassThrough } from "node:stream";
2
+ import { MOCK_REBIND_ENTRY_ID } from "../agent/providers/mock/mock-provider.js";
3
+ import { LogTap } from "../logging/log-tap.js";
4
+ import { createLogger } from "../logging/logger.js";
5
+ import { listeningPort, messageOf } from "./daemon-test-client.js";
6
+ /**
7
+ * The scripted dev-daemon scenario behind the external-client wire fixtures
8
+ * (swe/architecture/external-client-fixtures.md). Shared by the Layer B contract test
9
+ * (`daemon/external-fixtures-e2e.test.ts`) and the recorder script
10
+ * (`scripts/record-external-fixtures.ts`), so what is recorded is exactly what is verified.
11
+ *
12
+ * Drives every daemon-output type through its real path and returns the FIRST captured frame per
13
+ * fixture variant key (the manifest `file` stem, e.g. `agent_stream.tool_call.partial`). Matching
14
+ * is by predicate over the frame log, never by index.
15
+ */
16
+ /** The dev daemon must be started with at least this `mockTurnDelayMs` so a mock turn is still
17
+ * running when `interrupt_agent` arrives (`turn_canceled`). */
18
+ export const SCENARIO_MOCK_TURN_DELAY_MS = 150;
19
+ /**
20
+ * Dev-daemon options the scenario needs: the turn delay plus a tapped silent-output logger, so the
21
+ * `daemon_logs_*` stage 2 steps have a stream (`logTap` is shared with the bootstrap's service).
22
+ */
23
+ export function scenarioDaemonOptions() {
24
+ const logTap = new LogTap();
25
+ const logger = createLogger({
26
+ level: "info",
27
+ tap: logTap,
28
+ stdoutStream: new PassThrough(),
29
+ pretty: false,
30
+ });
31
+ return { logger, logTap, mockTurnDelayMs: SCENARIO_MOCK_TURN_DELAY_MS };
32
+ }
33
+ /** Fixture-variant key for `frame`, or `undefined` when the frame is not a fixtured variant. */
34
+ export function variantKey(frame) {
35
+ const m = messageOf(frame);
36
+ const type = String(m.type);
37
+ switch (type) {
38
+ case "status":
39
+ return "status.server_info";
40
+ case "agent_stream": {
41
+ const event = m.event;
42
+ return `agent_stream.${event.kind}${event.kind === "tool_call" && event.partial ? ".partial" : ""}`;
43
+ }
44
+ case "agent_update":
45
+ if ("model" in m)
46
+ return "agent_update.model";
47
+ return "status" in m ? "agent_update" : undefined;
48
+ case "agent_ui_request":
49
+ return `agent_ui_request.${String(m.method)}${m.removed === true ? ".removed" : ""}`;
50
+ case "agent_ui_resolved":
51
+ return `agent_ui_resolved.${String(m.reason)}`;
52
+ case "agent_ui_respond_response": {
53
+ const payload = m.payload;
54
+ return payload.ok ? "agent_ui_respond_response.ok" : "agent_ui_respond_response.not_found";
55
+ }
56
+ case "pong":
57
+ case "daemon_status_response":
58
+ case "daemon_status_subscribe_response":
59
+ case "daemon_status_unsubscribe_response":
60
+ case "daemon_status_update":
61
+ case "daemon_logs_subscribe_response":
62
+ case "daemon_logs_unsubscribe_response":
63
+ case "daemon_log_lines":
64
+ case "list_agents_response":
65
+ case "agent_archived":
66
+ case "agent_deleted":
67
+ case "agent_timeline_reset":
68
+ case "fetch_agent_timeline_response":
69
+ case "agent_session_stats_response":
70
+ case "interrupt_response":
71
+ case "agent_ui_list_response":
72
+ case "rpc_error":
73
+ return type;
74
+ default:
75
+ return undefined;
76
+ }
77
+ }
78
+ const isStream = (kind, extra = () => true) => (frame) => {
79
+ const m = messageOf(frame);
80
+ if (m.type !== "agent_stream")
81
+ return false;
82
+ const event = m.event;
83
+ return event.kind === kind && extra(event);
84
+ };
85
+ const isType = (type, extra = () => true) => (frame) => {
86
+ const m = messageOf(frame);
87
+ return m.type === type && extra(m);
88
+ };
89
+ export async function runExternalFixtureScenario(dev, client) {
90
+ const { rpc, waitFor } = client;
91
+ const createAgent = async (initialPrompt) => {
92
+ const created = await rpc("create_agent_request", {
93
+ config: { provider: "mock", cwd: "/tmp" },
94
+ ...(initialPrompt !== undefined ? { initialPrompt } : {}),
95
+ });
96
+ return created.payload.agentId;
97
+ };
98
+ // `MockAgentSession.emitUiRequest` is deliberately not part of the provider-neutral
99
+ // `AgentSession` contract; the dev handle's `manager` is the sanctioned test seam to reach it.
100
+ const mockSession = (agentId) => {
101
+ const session = dev.manager.get(agentId)?.session;
102
+ if (!session)
103
+ throw new Error(`no live session for ${agentId}`);
104
+ return session;
105
+ };
106
+ // Liveness.
107
+ client.send({ type: "ping", requestId: "scenario-ping", clientSentAt: Date.now() });
108
+ await waitFor(isType("pong"));
109
+ // Normal turn: user_message, turn_started, assistant_message, turn_completed, agent_update.
110
+ const agentId = await createAgent("hello");
111
+ await waitFor(isStream("turn_completed"));
112
+ await waitFor(isType("agent_update", (m) => m.status === "idle"));
113
+ // Tool call with partials, then the `#stream` kinds the normal turn never produces.
114
+ await rpc("send_agent_prompt", { agentId, prompt: "#tool shell" });
115
+ for (const recipe of ["reasoning", "fail", "error"]) {
116
+ await rpc("send_agent_prompt", { agentId, prompt: `#stream ${recipe}` });
117
+ }
118
+ // Cancellation: `send_agent_prompt` blocks until the turn ends, so send raw and interrupt once
119
+ // the daemon has recorded the prompt (the mock turn is still pending its delay).
120
+ client.send({
121
+ type: "session",
122
+ message: {
123
+ type: "send_agent_prompt",
124
+ requestId: "scenario-slow",
125
+ agentId,
126
+ prompt: "slow turn to cancel",
127
+ },
128
+ });
129
+ await waitFor(isStream("user_message", (e) => e.text === "slow turn to cancel"));
130
+ await rpc("interrupt_agent", { agentId });
131
+ await waitFor(isStream("turn_canceled"));
132
+ await waitFor(isType("agent_prompt_response", (m) => m.requestId === "scenario-slow"));
133
+ // Compaction (mock holds `started` for ~1.5 s).
134
+ await rpc("agent_compact_request", { agentId });
135
+ // Reads.
136
+ await rpc("list_agents_request");
137
+ await rpc("fetch_agent_timeline_request", { agentId, direction: "after" });
138
+ await rpc("agent_session_stats_request", { agentId });
139
+ // Extension UI: dialogs, a hand-off pair, a non-dialog, a retained surface, list, removal.
140
+ const session = mockSession(agentId);
141
+ session.emitUiRequest({ method: "select", payload: { title: "Pick one", options: ["a", "b"] } });
142
+ session.emitUiRequest({
143
+ method: "confirm",
144
+ payload: { title: "Proceed?", message: "Apply the change?" },
145
+ });
146
+ session.emitUiRequest({ method: "input", payload: { title: "Name", placeholder: "name" } });
147
+ session.emitUiRequest({ method: "editor", payload: { title: "Edit", prefill: "text" } });
148
+ session.emitUiRequest({ method: "notify", expectsResponse: false, payload: { message: "Done" } });
149
+ session.emitUiRequest({
150
+ method: "setStatus",
151
+ expectsResponse: false,
152
+ surfaceKey: "status:build",
153
+ payload: { statusText: "building" },
154
+ });
155
+ await waitFor(isType("agent_ui_request", (m) => m.method === "setStatus"));
156
+ await rpc("agent_ui_list_request", { agentId });
157
+ session.emitUiRequest({
158
+ method: "setStatus",
159
+ expectsResponse: false,
160
+ surfaceKey: "status:build",
161
+ removed: true,
162
+ payload: {},
163
+ });
164
+ // Answered (confirm → {confirmed}, select → {value}); unknown id → not_found; timeout.
165
+ const uiRequestId = async (method) => String(messageOf(await waitFor(isType("agent_ui_request", (m) => m.method === method))).requestId);
166
+ await rpc("agent_ui_respond_request", {
167
+ uiRequestId: await uiRequestId("confirm"),
168
+ response: { confirmed: true },
169
+ });
170
+ await rpc("agent_ui_respond_request", {
171
+ uiRequestId: await uiRequestId("select"),
172
+ response: { value: "a" },
173
+ });
174
+ await rpc("agent_ui_respond_request", {
175
+ uiRequestId: "unknown-request-id",
176
+ response: { confirmed: true },
177
+ });
178
+ session.emitUiRequest({ method: "confirm", timeoutMs: 50, payload: { title: "Hurry" } });
179
+ await waitFor(isType("agent_ui_resolved", (m) => m.reason === "timeout"));
180
+ // Aborted + archived + deleted: a second agent with a dialog pending, then archive / delete.
181
+ const doomedId = await createAgent("bye");
182
+ await waitFor(isType("agent_update", (m) => m.agentId === doomedId && m.status === "idle"));
183
+ mockSession(doomedId).emitUiRequest({ method: "input", payload: { title: "Never answered" } });
184
+ await waitFor(isType("agent_ui_request", (m) => m.agentId === doomedId));
185
+ await rpc("archive_agent", { agentId: doomedId });
186
+ await waitFor(isType("agent_ui_resolved", (m) => m.reason === "aborted"));
187
+ await rpc("delete_agent", { agentId: doomedId });
188
+ // A session-less draft: the model switch is broadcast as `agent_update {model, modelProvider}`.
189
+ const draftId = await createAgent();
190
+ await rpc("agent_set_model_request", { agentId: draftId, provider: "mock", modelId: "mock-2" });
191
+ // Timeline reset: the mock rebinds its persistence handle, so `handleFork` runs for real.
192
+ await rpc("agent_fork_request", { agentId, entryId: MOCK_REBIND_ENTRY_ID });
193
+ await waitFor(isType("agent_timeline_reset"));
194
+ // Unknown message type with a requestId → rpc_error.
195
+ await rpc("scenario_no_such_type");
196
+ // Stage 2 (daemonObservability): status one-shot, subscribe → push (real 5 s interval) →
197
+ // unsubscribe; then a log subscription with a one-line backlog, a live push and unsubscribe.
198
+ await rpc("daemon_status_request");
199
+ await rpc("daemon_status_subscribe_request");
200
+ await waitFor(isType("daemon_status_update"), 10_000);
201
+ await rpc("daemon_status_unsubscribe_request");
202
+ dev.logger.info("external fixture log line");
203
+ await rpc("daemon_logs_subscribe_request", { minLevel: "info", tail: 1 });
204
+ dev.logger.info("external fixture live line");
205
+ await waitFor(isType("daemon_log_lines"), 2000);
206
+ await rpc("daemon_logs_unsubscribe_request");
207
+ const captured = new Map();
208
+ for (const frame of client.frames) {
209
+ const key = variantKey(frame);
210
+ if (key !== undefined && !captured.has(key))
211
+ captured.set(key, frame);
212
+ }
213
+ // HTTP health (unauthenticated).
214
+ const port = await listeningPort(dev.httpServer);
215
+ const response = await fetch(`http://127.0.0.1:${port}/api/health`);
216
+ captured.set("health", {
217
+ status: response.status,
218
+ contentType: response.headers.get("content-type"),
219
+ body: await response.json(),
220
+ });
221
+ return captured;
222
+ }
223
+ //# sourceMappingURL=external-fixtures-scenario.js.map
@@ -0,0 +1,2 @@
1
+ export declare const SERVER_VERSION: string;
2
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1,7 @@
1
+ import { createRequire } from "node:module";
2
+ // Aligned workspace version, read from packages/server/package.json (never the root one — the
3
+ // root package.json deliberately carries no "version" field). This module sits one level below
4
+ // the package root in both `src/` and compiled `dist/`, so the specifier is "../package.json".
5
+ export const SERVER_VERSION = createRequire(import.meta.url)("../package.json")
6
+ .version;
7
+ //# sourceMappingURL=version.js.map