@av-pi-studio/server 0.0.114 → 0.0.116

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 (58) hide show
  1. package/README.md +8 -8
  2. package/dist/agent/agent-service.d.ts +5 -0
  3. package/dist/agent/agent-service.js +12 -0
  4. package/dist/agent/index.d.ts +0 -1
  5. package/dist/agent/index.js +0 -1
  6. package/dist/agent/mcp-server.d.ts +3 -13
  7. package/dist/agent/mcp-server.js +2 -10
  8. package/dist/agent/provider-contract.d.ts +0 -7
  9. package/dist/agent/providers/mock/mock-provider.d.ts +16 -3
  10. package/dist/agent/providers/mock/mock-provider.js +80 -8
  11. package/dist/agent/providers/mock/stream-script.d.ts +28 -0
  12. package/dist/agent/providers/mock/stream-script.js +57 -0
  13. package/dist/agent/providers/mock/tool-script.d.ts +28 -0
  14. package/dist/agent/providers/mock/tool-script.js +72 -0
  15. package/dist/agent/providers/pi/agent.js +15 -7
  16. package/dist/agent/providers/pi/event-mapper.d.ts +15 -12
  17. package/dist/agent/providers/pi/event-mapper.js +33 -15
  18. package/dist/agent/providers/pi/tool-output-coalescer.d.ts +58 -0
  19. package/dist/agent/providers/pi/tool-output-coalescer.js +121 -0
  20. package/dist/daemon/bootstrap.d.ts +18 -2
  21. package/dist/daemon/bootstrap.js +63 -13
  22. package/dist/daemon/dev-bootstrap.d.ts +7 -0
  23. package/dist/daemon/dev-bootstrap.js +34 -5
  24. package/dist/daemon/dev-main.js +5 -2
  25. package/dist/daemon/loopback.d.ts +4 -0
  26. package/dist/daemon/loopback.js +12 -0
  27. package/dist/daemon/main.js +4 -10
  28. package/dist/extensions/curated-packs.d.ts +0 -1
  29. package/dist/extensions/curated-packs.js +1 -6
  30. package/dist/extensions/sync-executor.js +1 -1
  31. package/dist/logging/index.d.ts +1 -0
  32. package/dist/logging/index.js +1 -0
  33. package/dist/logging/log-tap.d.ts +33 -0
  34. package/dist/logging/log-tap.js +233 -0
  35. package/dist/logging/logger.d.ts +6 -0
  36. package/dist/logging/logger.js +4 -0
  37. package/dist/observability/daemon-logs-rpc.d.ts +12 -0
  38. package/dist/observability/daemon-logs-rpc.js +17 -0
  39. package/dist/observability/daemon-logs-service.d.ts +67 -0
  40. package/dist/observability/daemon-logs-service.js +165 -0
  41. package/dist/observability/daemon-status-rpc.d.ts +12 -0
  42. package/dist/observability/daemon-status-rpc.js +21 -0
  43. package/dist/observability/daemon-status-service.d.ts +85 -0
  44. package/dist/observability/daemon-status-service.js +154 -0
  45. package/dist/test-support/auth-gated-rpc.d.ts +18 -0
  46. package/dist/test-support/auth-gated-rpc.js +80 -0
  47. package/dist/test-support/daemon-test-client.d.ts +43 -0
  48. package/dist/test-support/daemon-test-client.js +91 -0
  49. package/dist/test-support/external-fixtures-scenario.d.ts +30 -0
  50. package/dist/test-support/external-fixtures-scenario.js +223 -0
  51. package/dist/version.d.ts +2 -0
  52. package/dist/version.js +7 -0
  53. package/dist/ws/session.d.ts +11 -0
  54. package/dist/ws/session.js +11 -0
  55. package/dist/ws/ws-server.js +2 -0
  56. package/package.json +3 -3
  57. package/dist/agent/permissions.d.ts +0 -71
  58. package/dist/agent/permissions.js +0 -132
@@ -0,0 +1,165 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { LOG_LEVEL_NUMBERS } from "../logging/log-tap.js";
3
+ /**
4
+ * Per-session daemon log delivery (swe/features/daemon-log-streaming.md § Subscribe / deliver /
5
+ * cap). Each subscriber owns a level filter, a 200 lines/s token bucket (burst 200), a queue and a
6
+ * 100 ms flush timer that exists only while that subscriber has pending data. Overflow lines are
7
+ * counted in `dropped` (incremental, per subscriber) and never re-delivered. The ring and the log
8
+ * files are never subject to the cap.
9
+ */
10
+ export const LOG_RATE_PER_SECOND = 200;
11
+ export const LOG_FLUSH_INTERVAL_MS = 100;
12
+ export const LOG_TAIL_MAX = 1000;
13
+ const systemTimers = {
14
+ setTimeout: (fn, ms) => {
15
+ const handle = setTimeout(fn, ms);
16
+ handle.unref();
17
+ return handle;
18
+ },
19
+ clearTimeout: (handle) => clearTimeout(handle),
20
+ };
21
+ const isLevelName = (v) => typeof v === "string" && Object.hasOwn(LOG_LEVEL_NUMBERS, v);
22
+ export class DaemonLogsService {
23
+ tap;
24
+ send;
25
+ now;
26
+ timers;
27
+ subs = new Map();
28
+ removeListener = null;
29
+ constructor(deps) {
30
+ this.tap = deps.tap;
31
+ this.send = deps.send;
32
+ this.now = deps.now ?? (() => performance.now());
33
+ this.timers = deps.timers ?? systemTimers;
34
+ }
35
+ /**
36
+ * Validates, then REPLACES any existing subscription for the session (fresh limiter). An invalid
37
+ * request leaves the previous subscription untouched.
38
+ */
39
+ subscribe(session, minLevel, tail) {
40
+ if (!isLevelName(minLevel))
41
+ return { ok: false, error: "invalid_level" };
42
+ const tailCount = tail === undefined ? 0 : tail;
43
+ if (typeof tailCount !== "number" ||
44
+ !Number.isInteger(tailCount) ||
45
+ tailCount < 0 ||
46
+ tailCount > LOG_TAIL_MAX) {
47
+ return { ok: false, error: "invalid_tail" };
48
+ }
49
+ this.clearSubscription(session);
50
+ const minLevelNum = LOG_LEVEL_NUMBERS[minLevel];
51
+ this.subs.set(session, {
52
+ session,
53
+ minLevelNum,
54
+ queue: [],
55
+ tokens: LOG_RATE_PER_SECOND,
56
+ refilledAt: this.now(),
57
+ droppedSinceLastPush: 0,
58
+ timer: null,
59
+ });
60
+ this.ensureListening();
61
+ const lines = tailCount > 0
62
+ ? this.tap.backlog(minLevelNum, tailCount).map((raw) => this.tap.toLogLine(raw))
63
+ : [];
64
+ return {
65
+ ok: true,
66
+ minLevel,
67
+ effectiveLevel: this.effectiveLevel(minLevel),
68
+ lines,
69
+ dropped: 0,
70
+ };
71
+ }
72
+ /** Idempotent. */
73
+ unsubscribe(session) {
74
+ this.clearSubscription(session);
75
+ this.stopListeningIfIdle();
76
+ }
77
+ /** `SessionSubscriptions` disposer; safe when not subscribed. */
78
+ disposeSession(session) {
79
+ this.unsubscribe(session);
80
+ }
81
+ /** Release every subscription, timer and tap listener (daemon shutdown). */
82
+ dispose() {
83
+ for (const session of this.subs.keys())
84
+ this.clearSubscription(session);
85
+ this.stopListeningIfIdle();
86
+ }
87
+ /** The stricter of the daemon's level and `minLevel`; `"silent"` when the tap is unattached. */
88
+ effectiveLevel(minLevel) {
89
+ const daemonLevel = this.tap.effectiveLevel;
90
+ if (daemonLevel === "silent")
91
+ return "silent";
92
+ return LOG_LEVEL_NUMBERS[daemonLevel] > LOG_LEVEL_NUMBERS[minLevel] ? daemonLevel : minLevel;
93
+ }
94
+ ensureListening() {
95
+ this.removeListener ??= this.tap.onLine((raw, levelNum) => this.onLine(raw, levelNum));
96
+ }
97
+ stopListeningIfIdle() {
98
+ if (this.subs.size > 0 || this.removeListener === null)
99
+ return;
100
+ this.removeListener();
101
+ this.removeListener = null;
102
+ }
103
+ clearSubscription(session) {
104
+ const sub = this.subs.get(session);
105
+ if (!sub)
106
+ return;
107
+ if (sub.timer !== null)
108
+ this.timers.clearTimeout(sub.timer);
109
+ sub.timer = null;
110
+ this.subs.delete(session);
111
+ }
112
+ onLine(raw, levelNum) {
113
+ for (const sub of this.subs.values()) {
114
+ if (levelNum >= sub.minLevelNum)
115
+ this.enqueue(sub, raw);
116
+ }
117
+ }
118
+ enqueue(sub, raw) {
119
+ const now = this.now();
120
+ const elapsed = Math.max(0, now - sub.refilledAt);
121
+ sub.refilledAt = now;
122
+ sub.tokens = Math.min(LOG_RATE_PER_SECOND, sub.tokens + (elapsed * LOG_RATE_PER_SECOND) / 1000);
123
+ if (sub.tokens >= 1) {
124
+ sub.tokens -= 1;
125
+ sub.queue.push(raw);
126
+ }
127
+ else {
128
+ sub.droppedSinceLastPush += 1;
129
+ }
130
+ this.scheduleFlush(sub);
131
+ }
132
+ scheduleFlush(sub) {
133
+ if (sub.timer !== null)
134
+ return;
135
+ sub.timer = this.timers.setTimeout(() => this.flush(sub), LOG_FLUSH_INTERVAL_MS);
136
+ }
137
+ flush(sub) {
138
+ sub.timer = null;
139
+ if (this.subs.get(sub.session) !== sub)
140
+ return;
141
+ if (sub.queue.length === 0 && sub.droppedSinceLastPush === 0)
142
+ return;
143
+ const batch = sub.queue.splice(0, LOG_RATE_PER_SECOND);
144
+ const dropped = sub.droppedSinceLastPush;
145
+ sub.droppedSinceLastPush = 0;
146
+ try {
147
+ this.send(sub.session, {
148
+ type: "session",
149
+ message: {
150
+ type: "daemon_log_lines",
151
+ lines: batch.map((raw) => this.tap.toLogLine(raw)),
152
+ dropped,
153
+ },
154
+ });
155
+ }
156
+ catch {
157
+ // Dead socket: remove only this subscriber; its close path also disposes.
158
+ this.unsubscribe(sub.session);
159
+ return;
160
+ }
161
+ if (sub.queue.length > 0)
162
+ this.scheduleFlush(sub);
163
+ }
164
+ }
165
+ //# sourceMappingURL=daemon-logs-service.js.map
@@ -0,0 +1,12 @@
1
+ import type { HandlerRegistry } from "../ws/router.js";
2
+ import type { DaemonStatusService } from "./daemon-status-service.js";
3
+ /**
4
+ * Wires the `daemon_status_*` request family (swe/features/daemon-status-rpc.md) onto
5
+ * `DaemonStatusService`: a thin adapter with no policy of its own. Domain results travel in
6
+ * `payload`; `requestId` is stamped by the router. Registered in both bootstraps; advertised by the
7
+ * `daemonObservability` server feature.
8
+ */
9
+ export declare function registerDaemonStatusHandlers(registry: HandlerRegistry, deps: {
10
+ service: DaemonStatusService;
11
+ }): void;
12
+ //# sourceMappingURL=daemon-status-rpc.d.ts.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Wires the `daemon_status_*` request family (swe/features/daemon-status-rpc.md) onto
3
+ * `DaemonStatusService`: a thin adapter with no policy of its own. Domain results travel in
4
+ * `payload`; `requestId` is stamped by the router. Registered in both bootstraps; advertised by the
5
+ * `daemonObservability` server feature.
6
+ */
7
+ export function registerDaemonStatusHandlers(registry, deps) {
8
+ registry.register("daemon_status_request", () => ({
9
+ type: "daemon_status_response",
10
+ payload: deps.service.oneShot(),
11
+ }));
12
+ registry.register("daemon_status_subscribe_request", (ctx) => ({
13
+ type: "daemon_status_subscribe_response",
14
+ payload: deps.service.subscribe(ctx.session),
15
+ }));
16
+ registry.register("daemon_status_unsubscribe_request", (ctx) => {
17
+ deps.service.unsubscribe(ctx.session);
18
+ return { type: "daemon_status_unsubscribe_response", payload: { ok: true } };
19
+ });
20
+ }
21
+ //# sourceMappingURL=daemon-status-rpc.js.map
@@ -0,0 +1,85 @@
1
+ import type { DaemonStatus } from "@av-pi-studio/protocol";
2
+ import type { Logger } from "../logging/logger.js";
3
+ import type { Session } from "../ws/session.js";
4
+ /**
5
+ * Daemon status snapshots + per-session push (swe/features/daemon-status-rpc.md § Behavior &
6
+ * algorithms). One shared 5 s timer and one event-loop histogram exist only while at least one
7
+ * session is subscribed; with no subscribers the service holds no timer, no histogram and does
8
+ * no work. Each tick builds ONE snapshot shared by every subscriber.
9
+ */
10
+ export declare const DAEMON_STATUS_INTERVAL_MS = 5000;
11
+ /** The slice of `perf_hooks.IntervalHistogram` the service uses. */
12
+ export interface EventLoopHistogram {
13
+ enable(): unknown;
14
+ disable(): unknown;
15
+ reset(): void;
16
+ /** Mean delay in nanoseconds; `NaN` before any sample. */
17
+ readonly mean: number;
18
+ }
19
+ /** Process-level reads, injectable so tests can count calls and feed known values. */
20
+ export interface DaemonStatusSampler {
21
+ cpuUsage(): {
22
+ user: number;
23
+ system: number;
24
+ };
25
+ memoryUsage(): {
26
+ rss: number;
27
+ heapUsed: number;
28
+ heapTotal: number;
29
+ };
30
+ createEventLoopHistogram(): EventLoopHistogram;
31
+ /** Monotonic milliseconds. */
32
+ now(): number;
33
+ /** Wall-clock epoch milliseconds. */
34
+ wallNow(): number;
35
+ }
36
+ export declare const systemSampler: DaemonStatusSampler;
37
+ /** The minimal agent shape the status counts need (`AgentManager.list()` satisfies it). */
38
+ export interface StatusAgentView {
39
+ record: {
40
+ lastStatus: string;
41
+ };
42
+ }
43
+ export interface DaemonStatusServiceDeps {
44
+ /** Non-archived agents only (`AgentManager.list()`). */
45
+ listAgents(): readonly StatusAgentView[];
46
+ getActiveSessions(): readonly Session[];
47
+ /** Delivers one shared `{type:"session", message}` envelope to a session. May throw. */
48
+ send(session: Session, envelope: unknown): void;
49
+ sampler?: DaemonStatusSampler;
50
+ logger?: Logger;
51
+ }
52
+ export type DaemonStatusSubscribeResult = {
53
+ ok: true;
54
+ intervalMs: number;
55
+ status: DaemonStatus;
56
+ };
57
+ export declare class DaemonStatusService {
58
+ private readonly deps;
59
+ private readonly sampler;
60
+ private readonly startedAt;
61
+ private readonly startMonotonic;
62
+ private readonly subscribers;
63
+ private timer;
64
+ private histogram;
65
+ private lastCpu;
66
+ constructor(deps: DaemonStatusServiceDeps);
67
+ /** Build a snapshot. Advances the CPU baseline and resets the lag window. */
68
+ snapshot(): DaemonStatus;
69
+ /**
70
+ * One-shot status. Without subscribers no sampling runs, so `cpuPercent` and `eventLoopLagMs`
71
+ * are 0 (no window to measure): use `subscribe` for live gauges.
72
+ */
73
+ oneShot(): DaemonStatus;
74
+ /** Idempotent per session; always returns a fresh snapshot. */
75
+ subscribe(session: Session): DaemonStatusSubscribeResult;
76
+ unsubscribe(session: Session): void;
77
+ /** `SessionSubscriptions` disposer: same as unsubscribe, safe when not subscribed. */
78
+ disposeSession(session: Session): void;
79
+ /** Release the timer and histogram (daemon shutdown). */
80
+ dispose(): void;
81
+ private startSampling;
82
+ private stopSampling;
83
+ private tick;
84
+ }
85
+ //# sourceMappingURL=daemon-status-service.d.ts.map
@@ -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