@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
@@ -23,14 +23,20 @@ import { deterministicFallback } from "../agent/structured-generation.js";
23
23
  import { SessionOperationsService } from "../agent/session-operations.js";
24
24
  import { SlashCommandOperationsService } from "../agent/slash-command-operations.js";
25
25
  import { registerTimelineHandler } from "../agent/timeline-rpc.js";
26
- import { PermissionService } from "../agent/permissions.js";
27
26
  import { createMockClient } from "../agent/providers/mock/mock-provider.js";
28
27
  import { ProviderRegistry } from "../agent/provider-registry.js";
29
28
  import { FileExplorerService } from "../files/file-explorer.js";
30
29
  import { MAX_INLINE_FILE_READ_BYTES } from "../files/limits.js";
30
+ import { LogTap } from "../logging/log-tap.js";
31
31
  import { createDaemonLogger } from "../logging/logger.js";
32
+ import { registerDaemonLogsHandlers } from "../observability/daemon-logs-rpc.js";
33
+ import { DaemonLogsService } from "../observability/daemon-logs-service.js";
34
+ import { registerDaemonStatusHandlers } from "../observability/daemon-status-rpc.js";
35
+ import { DaemonStatusService } from "../observability/daemon-status-service.js";
32
36
  import { registerViewerSettingsHandlers } from "../viewers/viewer-settings-rpc.js";
37
+ import { SERVER_VERSION } from "../version.js";
33
38
  import { wrapSessionEnvelope } from "./bootstrap.js";
39
+ import { isLoopbackHost, UNPROTECTED_BIND_WARNING } from "./loopback.js";
34
40
  /** Broadcast helper — see `bootstrap.ts`'s `wrapSessionEnvelope` for the full rationale. */
35
41
  function broadcast(sessions, message) {
36
42
  const envelope = wrapSessionEnvelope(message);
@@ -45,7 +51,8 @@ function broadcast(sessions, message) {
45
51
  }
46
52
  export function startDevDaemon(opts) {
47
53
  const serverId = opts.serverId ?? randomUUID();
48
- const logger = opts.logger ?? createDaemonLogger(undefined);
54
+ const logTap = opts.logTap ?? new LogTap();
55
+ const logger = opts.logger ?? createDaemonLogger(undefined, { tap: logTap });
49
56
  // Services receive `getActiveSessions` backed by the module-level `broadcast` (hoisted
50
57
  // above) and a mutable holder so they can be registered before the WS server exists.
51
58
  const sessionsHolder = { sessions: [] };
@@ -66,6 +73,18 @@ export function startDevDaemon(opts) {
66
73
  resolveClient: (provider) => resolveClient(provider),
67
74
  logger,
68
75
  });
76
+ // ── Daemon status (features/daemon-status-rpc.md) — reads agents lazily through `manager`.
77
+ const daemonStatusService = new DaemonStatusService({
78
+ listAgents: () => manager.list(),
79
+ getActiveSessions: () => [...getActiveSessions()],
80
+ send: (session, envelope) => session.send(envelope),
81
+ logger: logger.child({ component: "daemon-status" }),
82
+ });
83
+ // ── Daemon log streaming (features/daemon-log-streaming.md)
84
+ const daemonLogsService = new DaemonLogsService({
85
+ tap: logTap,
86
+ send: (session, envelope) => session.send(envelope),
87
+ });
69
88
  // ── In-memory agent manager (no disk persistence in dev mode) ──────────────
70
89
  const agentsById = new Map();
71
90
  const manager = new AgentManager({
@@ -124,10 +143,10 @@ export function startDevDaemon(opts) {
124
143
  });
125
144
  slashCommandOps.registerHandlers(registry, getActiveSessions);
126
145
  registerTimelineHandler(registry, { manager, resolveClient });
127
- const permissionService = new PermissionService({ manager, broadcast });
128
- permissionService.registerHandlers(registry, getActiveSessions);
129
146
  registerAgentUiHandlers(registry, { service: agentUiService, logger });
130
147
  registerAgentTodosHandlers(registry, { service: agentTodosService });
148
+ registerDaemonStatusHandlers(registry, { service: daemonStatusService });
149
+ registerDaemonLogsHandlers(registry, { service: daemonLogsService });
131
150
  // Unlike extensions (production-only), this subsystem must exist in dev: the web client is
132
151
  // developed against the dev daemon, and without it every dev session runs the
133
152
  // capability-absent degrade path and can never exercise the toggle.
@@ -310,11 +329,15 @@ export function startDevDaemon(opts) {
310
329
  const wsHandle = createWebSocketServer(httpServer, {
311
330
  serverId,
312
331
  hostname: opts.host,
313
- version: "0.1.0-dev",
332
+ version: SERVER_VERSION,
314
333
  logger,
315
334
  onSession: (session) => {
316
335
  logger.info({ clientId: session.clientId, clientType: session.clientType }, "ws client connected");
317
336
  },
337
+ onSessionClose: (session) => {
338
+ daemonStatusService.disposeSession(session);
339
+ daemonLogsService.disposeSession(session);
340
+ },
318
341
  onMessage: (session, frame) => {
319
342
  if ("text" in frame) {
320
343
  void routeTextFrame(session, frame.text, registry);
@@ -325,6 +348,10 @@ export function startDevDaemon(opts) {
325
348
  // Now that the WS server exists, point the holder at its live session set.
326
349
  sessionsHolder.sessions = wsHandle.sessions;
327
350
  httpServer.listen(opts.port, opts.host);
351
+ // The dev daemon has no auth at all.
352
+ if (!isLoopbackHost(opts.host)) {
353
+ logger.warn({ host: opts.host, port: opts.port }, UNPROTECTED_BIND_WARNING);
354
+ }
328
355
  return {
329
356
  httpServer,
330
357
  serverId,
@@ -332,6 +359,8 @@ export function startDevDaemon(opts) {
332
359
  manager,
333
360
  close: async () => {
334
361
  logger.info("dev daemon shutting down");
362
+ daemonStatusService.dispose();
363
+ daemonLogsService.dispose();
335
364
  await wsHandle.close();
336
365
  await new Promise((resolve) => httpServer.close(() => resolve()));
337
366
  },
@@ -7,7 +7,6 @@ import { createDaemonRuntimeInfo } from "./index.js";
7
7
  import { startDevDaemon } from "./dev-bootstrap.js";
8
8
  const info = createDaemonRuntimeInfo({
9
9
  mode: "development",
10
- listen: process.env.PI_STUDIO_LISTEN ?? "0.0.0.0:6767",
11
10
  });
12
11
  const hostnamesEnv = process.env.PI_STUDIO_HOSTNAMES;
13
12
  const hostnames = hostnamesEnv
@@ -23,7 +22,11 @@ const handle = startDevDaemon({
23
22
  : undefined,
24
23
  });
25
24
  const log = handle.logger;
26
- log.info({ listen: `http://${info.listen.host}:${info.listen.port}`, serverId: handle.serverId, provider: "mock" }, `pi-studio dev daemon listening on http://${info.listen.host}:${info.listen.port}`);
25
+ log.info({
26
+ listen: `http://${info.listen.host}:${info.listen.port}`,
27
+ serverId: handle.serverId,
28
+ provider: "mock",
29
+ }, `pi-studio dev daemon listening on http://${info.listen.host}:${info.listen.port}`);
27
30
  process.on("SIGINT", async () => {
28
31
  log.info("shutting down");
29
32
  await handle.close();
@@ -0,0 +1,4 @@
1
+ /** True for hosts that only accept connections from this machine. */
2
+ export declare function isLoopbackHost(host: string): boolean;
3
+ export declare const UNPROTECTED_BIND_WARNING = "daemon is reachable beyond this machine with no password \u2014 set PI_STUDIO_PASSWORD or bind 127.0.0.1";
4
+ //# sourceMappingURL=loopback.d.ts.map
@@ -0,0 +1,12 @@
1
+ /** True for hosts that only accept connections from this machine. */
2
+ export function isLoopbackHost(host) {
3
+ const h = host
4
+ .trim()
5
+ .toLowerCase()
6
+ .replace(/^\[|\]$/g, "");
7
+ if (h === "::1" || h === "localhost" || h.endsWith(".localhost"))
8
+ return true;
9
+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
10
+ }
11
+ export const UNPROTECTED_BIND_WARNING = "daemon is reachable beyond this machine with no password — set PI_STUDIO_PASSWORD or bind 127.0.0.1";
12
+ //# sourceMappingURL=loopback.js.map
@@ -1,28 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * Production daemon entry point — starts the REAL daemon (real Pi provider, disk persistence, full
4
- * RPC surface). Binds `PI_STUDIO_LISTEN` (default `0.0.0.0:6767`).
4
+ * RPC surface). Listen address: `PI_STUDIO_LISTEN` → `config.json` `daemon.listen` → `127.0.0.1:6767`.
5
5
  */
6
- import { createDaemonRuntimeInfo } from "./index.js";
7
6
  import { startDaemon } from "./bootstrap.js";
8
- const info = createDaemonRuntimeInfo({
9
- mode: "production",
10
- listen: process.env.PI_STUDIO_LISTEN ?? "0.0.0.0:6767",
11
- });
12
7
  const handle = startDaemon({
13
- host: info.listen.host,
14
- port: info.listen.port,
15
8
  // The process-level half of `startDaemon`'s fatal-error contract: the bootstrap logs the error
16
9
  // and tears down the WS server, but leaves terminating the process to its entry point.
17
10
  onFatalError: () => process.exit(1),
18
11
  });
19
12
  const log = handle.logger;
13
+ const url = `http://${handle.listen.host}:${handle.listen.port}`;
20
14
  log.info({
21
- listen: `http://${info.listen.host}:${info.listen.port}`,
15
+ listen: url,
22
16
  serverId: handle.serverId,
23
17
  home: handle.home,
24
18
  provider: handle.provider,
25
- }, `pi-studio daemon listening on http://${info.listen.host}:${info.listen.port}`);
19
+ }, `pi-studio daemon listening on ${url}${handle.exposedWithoutPassword ? " (WARNING: no password set)" : ""}`);
26
20
  async function shutdown() {
27
21
  log.info("shutting down");
28
22
  await handle.close();
@@ -34,7 +34,6 @@ export declare const CURATED_PACKS: {
34
34
  }[];
35
35
  };
36
36
  };
37
- export declare const SERVER_VERSION: string;
38
37
  export interface ParsedSource {
39
38
  kind: "npm" | "git";
40
39
  /** Pi's own dedup key: npm package name, or git URL without ref. */
@@ -1,4 +1,4 @@
1
- import { createRequire } from "node:module";
1
+ import { SERVER_VERSION } from "../version.js";
2
2
  // core is implicit and always selected; swe/science/data are future audience packs, added as pure
3
3
  // data edits over time.
4
4
  export const CURATED_PACKS = {
@@ -20,11 +20,6 @@ export const CURATED_PACKS = {
20
20
  ],
21
21
  },
22
22
  };
23
- // Aligned workspace version, read from packages/server/package.json (never the root one — the
24
- // root package.json deliberately carries no "version" field). This module sits two levels below
25
- // the package root in both `src/` and compiled `dist/`, so the specifier is "../../package.json".
26
- export const SERVER_VERSION = createRequire(import.meta.url)("../../package.json")
27
- .version;
28
23
  /** Split a pi git source's `repo[@ref]` shape (mirrors pi's own `splitRef`,
29
24
  * `@earendil-works/pi-coding-agent/dist/utils/git.js`), so `pinned` is correct for scp-like
30
25
  * (`git@host:path@ref`), URL (`https://host/path@ref`), and bare (`host/path@ref`) forms. */
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import treeKill from "tree-kill";
3
3
  import { resolveBundledPiCli } from "../agent/providers/pi/rpc-transport.js";
4
- import { SERVER_VERSION } from "./curated-packs.js";
4
+ import { SERVER_VERSION } from "../version.js";
5
5
  import { effectivePiHomeKey, loadExtensionsState, saveExtensionsState, } from "./extensions-state.js";
6
6
  const INSTALL_TIMEOUT_MS = 180_000;
7
7
  const STDERR_TAIL_MAX = 2048;
@@ -1,2 +1,3 @@
1
+ export { LogTap, type LogTapListener } from "./log-tap.js";
1
2
  export { createDaemonLogger, createLogger, type CreateLoggerOptions, type Logger, type LogLevel, silentLogger, } from "./logger.js";
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,3 @@
1
+ export { LogTap } from "./log-tap.js";
1
2
  export { createDaemonLogger, createLogger, silentLogger, } from "./logger.js";
2
3
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,33 @@
1
+ import { Writable } from "node:stream";
2
+ import type { LogLine } from "@av-pi-studio/protocol";
3
+ import type { LogLevel } from "./logger.js";
4
+ /**
5
+ * `LogTap` — a pino multistream destination that mirrors every line the daemon logger writes into
6
+ * a bounded, sanitised, size-capped ring and fans it out to live listeners
7
+ * (swe/features/daemon-log-streaming.md). It only ever receives a copy: stdout and the rotating
8
+ * file are separate multistream entries and stay byte-for-byte untouched.
9
+ *
10
+ * Invariants: the tap never throws into pino; the ring never holds a line over
11
+ * `LOG_LINE_MAX_BYTES`; redaction/truncation happen once, here, at tap time.
12
+ */
13
+ export declare const LOG_RING_CAPACITY = 1000;
14
+ export declare const LOG_LINE_MAX_BYTES = 8192;
15
+ /** Pino's numeric levels. */
16
+ export declare const LOG_LEVEL_NUMBERS: Readonly<Record<Exclude<LogLevel, "silent">, number>>;
17
+ export type LogTapListener = (line: string, levelNum: number) => void;
18
+ export declare class LogTap {
19
+ #private;
20
+ readonly stream: Writable;
21
+ constructor();
22
+ /** The logger level the tap was attached at, or `"silent"` while unattached. */
23
+ get effectiveLevel(): LogLevel;
24
+ /** Called by `createLogger` when it pushes the tap's stream. */
25
+ attach(level: LogLevel): void;
26
+ /** Register a live listener; returns its remover. Listener errors are swallowed. */
27
+ onLine(listener: LogTapListener): () => void;
28
+ /** The newest `n` lines at or above `minLevelNum`, oldest first. */
29
+ backlog(minLevelNum: number, n: number): string[];
30
+ /** Project a ring/listener line to the wire shape. Never throws. */
31
+ toLogLine(raw: string): LogLine;
32
+ }
33
+ //# sourceMappingURL=log-tap.d.ts.map
@@ -0,0 +1,233 @@
1
+ import { Writable } from "node:stream";
2
+ /**
3
+ * `LogTap` — a pino multistream destination that mirrors every line the daemon logger writes into
4
+ * a bounded, sanitised, size-capped ring and fans it out to live listeners
5
+ * (swe/features/daemon-log-streaming.md). It only ever receives a copy: stdout and the rotating
6
+ * file are separate multistream entries and stay byte-for-byte untouched.
7
+ *
8
+ * Invariants: the tap never throws into pino; the ring never holds a line over
9
+ * `LOG_LINE_MAX_BYTES`; redaction/truncation happen once, here, at tap time.
10
+ */
11
+ export const LOG_RING_CAPACITY = 1000;
12
+ export const LOG_LINE_MAX_BYTES = 8192;
13
+ const MSG_MAX_CHARS = 2048;
14
+ const FIELD_STRING_MAX_CHARS = 1024;
15
+ const STACK_MAX_CHARS = 2048;
16
+ const MAX_DEPTH = 4;
17
+ const REDACTED = "[redacted]";
18
+ const TRUNCATED_NODE = "[truncated]";
19
+ /** Pino's numeric levels. */
20
+ export const LOG_LEVEL_NUMBERS = {
21
+ trace: 10,
22
+ debug: 20,
23
+ info: 30,
24
+ warn: 40,
25
+ error: 50,
26
+ fatal: 60,
27
+ };
28
+ const LEVEL_NAMES = new Map(Object.entries(LOG_LEVEL_NUMBERS).map(([name, num]) => [
29
+ num,
30
+ name,
31
+ ]));
32
+ /** Keys stripped from `LogLine.fields`. */
33
+ const CORE_KEYS = new Set(["level", "time", "msg", "pid", "hostname", "v"]);
34
+ /**
35
+ * Whole key names (lower-cased) whose values are redacted. Whole-name matching deliberately
36
+ * spares usage counters such as `tokens` / `inputTokens`.
37
+ */
38
+ const SENSITIVE_KEYS = new Set([
39
+ "password",
40
+ "passwd",
41
+ "secret",
42
+ "token",
43
+ "authorization",
44
+ "cookie",
45
+ "apikey",
46
+ "api_key",
47
+ "bearer",
48
+ "privatekey",
49
+ "secretkey",
50
+ ]);
51
+ const BEARER_PATTERN = /pi-studio\.bearer\.[^\s"']+/g;
52
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
53
+ const maskBearer = (s) => s.replace(BEARER_PATTERN, "pi-studio.bearer.[redacted]");
54
+ const cut = (s, max) => (s.length > max ? s.slice(0, max) : s);
55
+ /** Redact sensitive keys and mask bearer tokens in strings, recursively. Mutates `node`. */
56
+ function sanitize(node) {
57
+ if (typeof node === "string")
58
+ return maskBearer(node);
59
+ if (Array.isArray(node)) {
60
+ for (let i = 0; i < node.length; i++)
61
+ node[i] = sanitize(node[i]);
62
+ return node;
63
+ }
64
+ if (isObject(node)) {
65
+ for (const key of Object.keys(node)) {
66
+ node[key] = SENSITIVE_KEYS.has(key.toLowerCase()) ? REDACTED : sanitize(node[key]);
67
+ }
68
+ }
69
+ return node;
70
+ }
71
+ /** Shorten strings and cap nesting depth. Returns a new value. */
72
+ function shrink(node, depth, inErr) {
73
+ if (typeof node === "string")
74
+ return cut(node, FIELD_STRING_MAX_CHARS);
75
+ if (Array.isArray(node)) {
76
+ if (depth > MAX_DEPTH)
77
+ return TRUNCATED_NODE;
78
+ return node.map((v) => shrink(v, depth + 1, false));
79
+ }
80
+ if (isObject(node)) {
81
+ if (depth > MAX_DEPTH)
82
+ return TRUNCATED_NODE;
83
+ const out = {};
84
+ for (const [k, v] of Object.entries(node)) {
85
+ out[k] =
86
+ inErr && k === "stack" && typeof v === "string"
87
+ ? cut(v, STACK_MAX_CHARS)
88
+ : shrink(v, depth + 1, k === "err" && depth === 0);
89
+ }
90
+ return out;
91
+ }
92
+ return node;
93
+ }
94
+ function truncateLine(obj) {
95
+ const out = {};
96
+ for (const [k, v] of Object.entries(obj)) {
97
+ if (k === "msg" && typeof v === "string")
98
+ out[k] = cut(v, MSG_MAX_CHARS);
99
+ else if (CORE_KEYS.has(k))
100
+ out[k] = v;
101
+ else
102
+ out[k] = shrink(v, 1, k === "err");
103
+ }
104
+ out.truncated = true;
105
+ if (Buffer.byteLength(JSON.stringify(out)) <= LOG_LINE_MAX_BYTES)
106
+ return out;
107
+ // Pathologically wide line (thousands of small fields): keep only the core keys.
108
+ const core = {};
109
+ for (const k of CORE_KEYS)
110
+ if (k in out)
111
+ core[k] = out[k];
112
+ core.truncated = true;
113
+ return core;
114
+ }
115
+ export class LogTap {
116
+ stream;
117
+ #ring = Array.from({
118
+ length: LOG_RING_CAPACITY,
119
+ });
120
+ #next = 0;
121
+ #size = 0;
122
+ #listeners = new Set();
123
+ #effectiveLevel = "silent";
124
+ constructor() {
125
+ this.stream = new Writable({
126
+ decodeStrings: false,
127
+ write: (chunk, _enc, cb) => {
128
+ try {
129
+ this.#ingest(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
130
+ }
131
+ catch {
132
+ // The tap must never push an error back into pino.
133
+ }
134
+ cb();
135
+ },
136
+ });
137
+ }
138
+ /** The logger level the tap was attached at, or `"silent"` while unattached. */
139
+ get effectiveLevel() {
140
+ return this.#effectiveLevel;
141
+ }
142
+ /** Called by `createLogger` when it pushes the tap's stream. */
143
+ attach(level) {
144
+ this.#effectiveLevel = level;
145
+ }
146
+ /** Register a live listener; returns its remover. Listener errors are swallowed. */
147
+ onLine(listener) {
148
+ this.#listeners.add(listener);
149
+ return () => {
150
+ this.#listeners.delete(listener);
151
+ };
152
+ }
153
+ /** The newest `n` lines at or above `minLevelNum`, oldest first. */
154
+ backlog(minLevelNum, n) {
155
+ const out = [];
156
+ for (let i = 1; i <= this.#size && out.length < n; i++) {
157
+ const entry = this.#ring[(this.#next - i + LOG_RING_CAPACITY) % LOG_RING_CAPACITY];
158
+ if (entry && entry.level >= minLevelNum)
159
+ out.push(entry.raw);
160
+ }
161
+ return out.toReversed();
162
+ }
163
+ /** Project a ring/listener line to the wire shape. Never throws. */
164
+ toLogLine(raw) {
165
+ let parsed;
166
+ try {
167
+ parsed = JSON.parse(raw);
168
+ }
169
+ catch {
170
+ return { time: Date.now(), level: "info", msg: cut(raw, MSG_MAX_CHARS) };
171
+ }
172
+ if (!isObject(parsed))
173
+ return { time: Date.now(), level: "info", msg: cut(raw, MSG_MAX_CHARS) };
174
+ const fields = {};
175
+ for (const [k, v] of Object.entries(parsed))
176
+ if (!CORE_KEYS.has(k))
177
+ fields[k] = v;
178
+ const level = typeof parsed.level === "number" ? (LEVEL_NAMES.get(parsed.level) ?? "info") : "info";
179
+ return {
180
+ time: typeof parsed.time === "number" ? parsed.time : Date.now(),
181
+ level,
182
+ msg: typeof parsed.msg === "string" ? parsed.msg : "",
183
+ ...(Object.keys(fields).length > 0 ? { fields } : {}),
184
+ };
185
+ }
186
+ #ingest(chunk) {
187
+ for (const part of chunk.split("\n")) {
188
+ if (part.trim().length === 0)
189
+ continue;
190
+ const entry = this.#normalise(part);
191
+ this.#ring[this.#next] = entry;
192
+ this.#next = (this.#next + 1) % LOG_RING_CAPACITY;
193
+ if (this.#size < LOG_RING_CAPACITY)
194
+ this.#size++;
195
+ for (const listener of this.#listeners) {
196
+ try {
197
+ listener(entry.raw, entry.level);
198
+ }
199
+ catch {
200
+ // A faulty listener must not affect pino or other listeners.
201
+ }
202
+ }
203
+ }
204
+ }
205
+ #normalise(part) {
206
+ let parsed;
207
+ try {
208
+ parsed = JSON.parse(part);
209
+ }
210
+ catch {
211
+ parsed = undefined;
212
+ }
213
+ if (!isObject(parsed)) {
214
+ return {
215
+ raw: JSON.stringify({
216
+ level: LOG_LEVEL_NUMBERS.info,
217
+ time: Date.now(),
218
+ msg: maskBearer(cut(part, MSG_MAX_CHARS)),
219
+ }),
220
+ level: LOG_LEVEL_NUMBERS.info,
221
+ };
222
+ }
223
+ const level = typeof parsed.level === "number" ? parsed.level : LOG_LEVEL_NUMBERS.info;
224
+ let obj = sanitize(parsed);
225
+ let raw = JSON.stringify(obj);
226
+ if (Buffer.byteLength(raw) > LOG_LINE_MAX_BYTES) {
227
+ obj = truncateLine(obj);
228
+ raw = JSON.stringify(obj);
229
+ }
230
+ return { raw, level };
231
+ }
232
+ }
233
+ //# sourceMappingURL=log-tap.js.map
@@ -1,3 +1,4 @@
1
+ import type { LogTap } from "./log-tap.js";
1
2
  /**
2
3
  * Daemon logging (operational concern; adopted from the reference daemon's `pino` stack). The rest
3
4
  * of the codebase injects a `Pick<Console, "info" | "warn" | "error">`-shaped logger; a pino logger
@@ -41,6 +42,11 @@ export interface CreateLoggerOptions {
41
42
  bindings?: Record<string, unknown>;
42
43
  /** Override the stdout stream (tests). Defaults to `process.stdout`. */
43
44
  stdoutStream?: NodeJS.WritableStream;
45
+ /**
46
+ * Mirror every written line into a `LogTap` (live log streaming). Adds ONE extra multistream
47
+ * entry at the resolved level; stdout/file entries are untouched. Ignored when silent.
48
+ */
49
+ tap?: LogTap;
44
50
  }
45
51
  /** Build a pino logger per the options. Pure/synchronous; safe to call in tests. */
46
52
  export declare function createLogger(options?: CreateLoggerOptions): Logger;
@@ -45,6 +45,10 @@ export function createLogger(options = {}) {
45
45
  }),
46
46
  });
47
47
  }
48
+ if (options.tap) {
49
+ options.tap.attach(level);
50
+ streams.push({ level, stream: options.tap.stream });
51
+ }
48
52
  return pino(base, multistream(streams));
49
53
  }
50
54
  /**
@@ -0,0 +1,12 @@
1
+ import type { HandlerRegistry } from "../ws/router.js";
2
+ import type { DaemonLogsService } from "./daemon-logs-service.js";
3
+ /**
4
+ * Wires the `daemon_logs_*` request family (swe/features/daemon-log-streaming.md) onto
5
+ * `DaemonLogsService`. Invalid `minLevel`/`tail` are domain failures in `payload`, never
6
+ * `rpc_error`. `requestId` is stamped by the router. Registered in both bootstraps; advertised by the
7
+ * `daemonObservability` server feature.
8
+ */
9
+ export declare function registerDaemonLogsHandlers(registry: HandlerRegistry, deps: {
10
+ service: DaemonLogsService;
11
+ }): void;
12
+ //# sourceMappingURL=daemon-logs-rpc.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Wires the `daemon_logs_*` request family (swe/features/daemon-log-streaming.md) onto
3
+ * `DaemonLogsService`. Invalid `minLevel`/`tail` are domain failures in `payload`, never
4
+ * `rpc_error`. `requestId` is stamped by the router. Registered in both bootstraps; advertised by the
5
+ * `daemonObservability` server feature.
6
+ */
7
+ export function registerDaemonLogsHandlers(registry, deps) {
8
+ registry.register("daemon_logs_subscribe_request", (ctx) => ({
9
+ type: "daemon_logs_subscribe_response",
10
+ payload: deps.service.subscribe(ctx.session, ctx.message.minLevel, ctx.message.tail),
11
+ }));
12
+ registry.register("daemon_logs_unsubscribe_request", (ctx) => {
13
+ deps.service.unsubscribe(ctx.session);
14
+ return { type: "daemon_logs_unsubscribe_response", payload: { ok: true } };
15
+ });
16
+ }
17
+ //# sourceMappingURL=daemon-logs-rpc.js.map
@@ -0,0 +1,67 @@
1
+ import type { LogLine } from "@av-pi-studio/protocol";
2
+ import { type LogTap } from "../logging/log-tap.js";
3
+ import type { LogLevel } from "../logging/logger.js";
4
+ import type { Session } from "../ws/session.js";
5
+ /**
6
+ * Per-session daemon log delivery (swe/features/daemon-log-streaming.md § Subscribe / deliver /
7
+ * cap). Each subscriber owns a level filter, a 200 lines/s token bucket (burst 200), a queue and a
8
+ * 100 ms flush timer that exists only while that subscriber has pending data. Overflow lines are
9
+ * counted in `dropped` (incremental, per subscriber) and never re-delivered. The ring and the log
10
+ * files are never subject to the cap.
11
+ */
12
+ export declare const LOG_RATE_PER_SECOND = 200;
13
+ export declare const LOG_FLUSH_INTERVAL_MS = 100;
14
+ export declare const LOG_TAIL_MAX = 1000;
15
+ export type DaemonLogLevelName = Exclude<LogLevel, "silent">;
16
+ export interface DaemonLogsTimers {
17
+ setTimeout(fn: () => void, ms: number): unknown;
18
+ clearTimeout(handle: unknown): void;
19
+ }
20
+ export interface DaemonLogsServiceDeps {
21
+ tap: LogTap;
22
+ /** Delivers one `{type:"session", message}` envelope to a session. May throw. */
23
+ send(session: Session, envelope: unknown): void;
24
+ /** Monotonic milliseconds. Defaults to `performance.now`. */
25
+ now?: () => number;
26
+ timers?: DaemonLogsTimers;
27
+ }
28
+ export type DaemonLogsSubscribeResult = {
29
+ ok: true;
30
+ minLevel: DaemonLogLevelName;
31
+ effectiveLevel: LogLevel;
32
+ lines: LogLine[];
33
+ dropped: 0;
34
+ } | {
35
+ ok: false;
36
+ error: "invalid_level" | "invalid_tail";
37
+ };
38
+ export declare class DaemonLogsService {
39
+ private readonly tap;
40
+ private readonly send;
41
+ private readonly now;
42
+ private readonly timers;
43
+ private readonly subs;
44
+ private removeListener;
45
+ constructor(deps: DaemonLogsServiceDeps);
46
+ /**
47
+ * Validates, then REPLACES any existing subscription for the session (fresh limiter). An invalid
48
+ * request leaves the previous subscription untouched.
49
+ */
50
+ subscribe(session: Session, minLevel: unknown, tail?: unknown): DaemonLogsSubscribeResult;
51
+ /** Idempotent. */
52
+ unsubscribe(session: Session): void;
53
+ /** `SessionSubscriptions` disposer; safe when not subscribed. */
54
+ disposeSession(session: Session): void;
55
+ /** Release every subscription, timer and tap listener (daemon shutdown). */
56
+ dispose(): void;
57
+ /** The stricter of the daemon's level and `minLevel`; `"silent"` when the tap is unattached. */
58
+ private effectiveLevel;
59
+ private ensureListening;
60
+ private stopListeningIfIdle;
61
+ private clearSubscription;
62
+ private onLine;
63
+ private enqueue;
64
+ private scheduleFlush;
65
+ private flush;
66
+ }
67
+ //# sourceMappingURL=daemon-logs-service.d.ts.map