@camstack/server 1.2.882 → 1.2.883

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/CHANGELOG.md CHANGED
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.883] - 2026-11-15
11
+
12
+ ### Changed
13
+
14
+ - A server update no longer re-downloads ffmpeg when node-av did not change (the seeded install pins the exact version), and a hung npm install is now cut after 5 minutes without progress instead of running to the 3-hour ceiling
15
+ - Logs page export: download the logs of chosen components and/or devices over a time range (default everything, last 6 h) as one NDJSON file (GET /api/logs/export, streamed).
16
+
10
17
  ## [1.2.882] - 2026-11-15
11
18
 
12
19
  ### Changed
@@ -242,7 +242,7 @@ class AgentUpdateService extends index_js_1.RootUpdateService {
242
242
  dataDir: options.dataDir,
243
243
  runningPackageJsonPath: options.runningPackageJsonPath ?? resolveAgentPackageJsonPath(__dirname),
244
244
  workspaceProbeDir: __dirname,
245
- // Default to the runNpm-backed adapter — a packaged desktop agent ships a
245
+ // Default to the system-npm adapter (watched) — a packaged desktop agent ships a
246
246
  // bare Node with no system npm, so the raw `execFile('npm')` default would
247
247
  // ENOENT. `cacheDir` mirrors AddonInstaller's `<dataDir>/addons/.npm-bootstrap`.
248
248
  execNpm: options.execNpm ??
@@ -45,6 +45,7 @@
45
45
  */
46
46
  Object.defineProperty(exports, "__esModule", { value: true });
47
47
  exports.BACKUP_DOWNLOAD_DRAIN_GRACE_MS = exports.BACKUP_DOWNLOAD_CHUNK_BYTES = void 0;
48
+ exports.waitForDrain = waitForDrain;
48
49
  exports.pumpDownload = pumpDownload;
49
50
  /** Bytes read from the storage cap per round trip; one chunk is the most the response holds. */
50
51
  exports.BACKUP_DOWNLOAD_CHUNK_BYTES = 8 * 1024 * 1024;
@@ -1,6 +1,4 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLogsRouter = createLogsRouter;
4
2
  /**
5
3
  * Logs router — fixed core API (not a capability).
6
4
  *
@@ -9,11 +7,15 @@ exports.createLogsRouter = createLogsRouter;
9
7
  * everything; viewers/protected users only see entries matching their
10
8
  * allowed providers scope (filtered in `query`).
11
9
  */
12
- const zod_1 = require("zod");
13
- const trpc_middleware_js_1 = require("../trpc/trpc.middleware.js");
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.hubLocalDestinations = hubLocalDestinations;
12
+ exports.createLogsRouter = createLogsRouter;
14
13
  const node_crypto_1 = require("node:crypto");
15
14
  const system_1 = require("@camstack/server/system");
15
+ const zod_1 = require("zod");
16
+ const log_export_js_1 = require("../../core/logging/log-export.js");
16
17
  const log_history_js_1 = require("../../core/logging/log-history.js");
18
+ const trpc_middleware_js_1 = require("../trpc/trpc.middleware.js");
17
19
  const LogLevelSchema = zod_1.z.enum(['debug', 'info', 'warn', 'error']);
18
20
  const LogTagsSchema = zod_1.z.object({
19
21
  agentId: zod_1.z.string().optional(),
@@ -130,20 +132,9 @@ function readFiltersFromTags(tags) {
130
132
  ...(Object.keys(rest).length > 0 ? { tags: rest } : {}),
131
133
  };
132
134
  }
135
+ /** The same wire line the export writes (#570): every tag as a string. */
133
136
  function toWire(entry) {
134
- return {
135
- ...(entry.id !== undefined ? { id: entry.id } : {}),
136
- timestamp: new Date(entry.timestamp).toISOString(),
137
- level: entry.level,
138
- ...(entry.scope !== undefined ? { scope: entry.scope } : {}),
139
- message: entry.message,
140
- ...(entry.tags !== undefined
141
- ? {
142
- tags: Object.fromEntries(Object.entries(entry.tags).map(([k, v]) => [k, String(v)])),
143
- }
144
- : {}),
145
- ...(entry.meta !== undefined ? { meta: entry.meta } : {}),
146
- };
137
+ return (0, log_export_js_1.toWireLogLine)(entry);
147
138
  }
148
139
  /** Hub-local providers only: an agent's own files hold lines the hub already has. */
149
140
  function hubLocalDestinations(registry) {
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ /**
3
+ * GET /api/logs/export — the log export (#570) as one NDJSON download.
4
+ *
5
+ * Query string (all optional): `components` (comma-separated addonIds),
6
+ * `deviceIds` (comma-separated numeric ids), `since` / `until` (epoch ms),
7
+ * `level`, `source` (a read-capable log-destination, default the hub's files).
8
+ * Default: everything over the last six hours. The selection and the merge
9
+ * live in `core/logging/log-export.ts`; the admin Logs page and the ops MCP
10
+ * tool both call this route, so there is one implementation.
11
+ *
12
+ * The lines go out at the pace the client reads them (D447): a write the
13
+ * socket did not take waits for `drain`, a client that stops reading is cut
14
+ * after the grace, a client that leaves stops the read, and every exit logs
15
+ * one line. Admin only, Bearer auth, like the backup download.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.LOGS_EXPORT_PATH = void 0;
19
+ exports.collectLogExport = collectLogExport;
20
+ exports.registerLogsExportRoute = registerLogsExportRoute;
21
+ const log_export_js_1 = require("../core/logging/log-export.js");
22
+ const log_history_js_1 = require("../core/logging/log-history.js");
23
+ const backup_download_pump_js_1 = require("./backup-download-pump.js");
24
+ const logs_router_js_1 = require("./core/logs.router.js");
25
+ const client_ip_js_1 = require("./trpc/client-ip.js");
26
+ exports.LOGS_EXPORT_PATH = '/api/logs/export';
27
+ /**
28
+ * Write the export's lines into `sink`, one NDJSON line per entry. Past
29
+ * `maxEntries` it stops and writes one last `{"truncated":true,…}` line, so a
30
+ * capped file never looks complete. Never throws: every exit is a result.
31
+ */
32
+ async function collectLogExport(args) {
33
+ const { sink } = args;
34
+ const maxEntries = args.maxEntries ?? log_export_js_1.LOG_EXPORT_MAX_ENTRIES;
35
+ const graceMs = args.graceMs ?? backup_download_pump_js_1.BACKUP_DOWNLOAD_DRAIN_GRACE_MS;
36
+ let lines = 0;
37
+ let bytes = 0;
38
+ let truncated = false;
39
+ const write = async (text) => {
40
+ const chunk = Buffer.from(text, 'utf8');
41
+ bytes += chunk.byteLength;
42
+ if (sink.write(chunk))
43
+ return 'ok';
44
+ const outcome = await (0, backup_download_pump_js_1.waitForDrain)(sink, graceMs);
45
+ return outcome === 'drained' ? 'ok' : outcome;
46
+ };
47
+ try {
48
+ for await (const entry of args.entries) {
49
+ if (sink.destroyed)
50
+ return { status: 'peer-gone', lines, bytes };
51
+ if (lines >= maxEntries) {
52
+ truncated = true;
53
+ break;
54
+ }
55
+ const outcome = await write((0, log_export_js_1.toNdjsonLine)(entry));
56
+ lines += 1;
57
+ if (outcome === 'closed')
58
+ return { status: 'peer-gone', lines, bytes };
59
+ if (outcome === 'timeout') {
60
+ const queuedBytes = sink.writableLength;
61
+ sink.destroy(new Error(`log export: client stopped reading — ${queuedBytes} bytes queued`));
62
+ return { status: 'drain-timeout', lines, bytes, queuedBytes };
63
+ }
64
+ }
65
+ }
66
+ catch (err) {
67
+ const error = err instanceof Error ? err.message : String(err);
68
+ sink.destroy(new Error(`log export: the log source failed — ${error}`));
69
+ return { status: 'source-failed', lines, bytes, error };
70
+ }
71
+ if (truncated) {
72
+ await write(`${JSON.stringify({ truncated: true, maxEntries, lines })}\n`);
73
+ }
74
+ sink.end();
75
+ return { status: 'completed', lines, bytes, truncated };
76
+ }
77
+ function attachmentName(request) {
78
+ const stamp = new Date(request.until).toISOString().replace(/[:.]/g, '-');
79
+ return `camstack-logs-${stamp}.ndjson`;
80
+ }
81
+ function registerLogsExportRoute(fastify, options) {
82
+ const { verifier, registry, tail, logger } = options;
83
+ const now = options.now ?? (() => Date.now());
84
+ fastify.get(exports.LOGS_EXPORT_PATH, async (request, reply) => {
85
+ const authHeader = request.headers.authorization;
86
+ if (!authHeader)
87
+ return reply.status(401).send({ error: 'Unauthorized' });
88
+ try {
89
+ const payload = verifier.verifyToken(authHeader.replace('Bearer ', ''));
90
+ if (!payload.isAdmin)
91
+ return reply.status(403).send({ error: 'Admin required' });
92
+ }
93
+ catch {
94
+ return reply.status(401).send({ error: 'Invalid token' });
95
+ }
96
+ const parsed = (0, log_export_js_1.parseLogExportRequest)(request.query, now());
97
+ if (!parsed.ok)
98
+ return reply.status(400).send({ error: parsed.error });
99
+ const exportRequest = parsed.request;
100
+ const sourceId = (0, log_export_js_1.exportSourceOf)(request.query) ?? log_history_js_1.DEFAULT_LOG_SOURCE;
101
+ const provider = sourceId === log_history_js_1.RING_LOG_SOURCE
102
+ ? null
103
+ : ((0, logs_router_js_1.hubLocalDestinations)(registry).find(([id]) => id === sourceId)?.[1] ?? null);
104
+ const aborter = new AbortController();
105
+ const requestIds = [];
106
+ const read = (query) => {
107
+ const requestId = `log-export-${String(requestIds.length)}-${String(now())}`;
108
+ requestIds.push(requestId);
109
+ return (0, log_history_js_1.readLogHistory)({
110
+ query: { ...query, requestId },
111
+ source: sourceId,
112
+ tail: tail.query({}),
113
+ provider,
114
+ });
115
+ };
116
+ const onClose = () => {
117
+ if (reply.raw.writableFinished)
118
+ return;
119
+ aborter.abort();
120
+ const last = requestIds.at(-1);
121
+ if (last !== undefined)
122
+ void provider?.cancelRead?.({ requestId: last }).catch(() => undefined);
123
+ };
124
+ reply.hijack();
125
+ reply.raw.writeHead(200, {
126
+ 'content-type': 'application/x-ndjson; charset=utf-8',
127
+ 'content-disposition': `attachment; filename="${attachmentName(exportRequest)}"`,
128
+ 'cache-control': 'no-store',
129
+ });
130
+ reply.raw.on('close', onClose);
131
+ const startedAt = now();
132
+ const result = await collectLogExport({
133
+ entries: (0, log_export_js_1.exportLogEntries)({ request: exportRequest, read, signal: aborter.signal }),
134
+ sink: reply.raw,
135
+ ...(options.maxEntries !== undefined ? { maxEntries: options.maxEntries } : {}),
136
+ ...(options.graceMs !== undefined ? { graceMs: options.graceMs } : {}),
137
+ });
138
+ reply.raw.off('close', onClose);
139
+ const meta = {
140
+ ...result,
141
+ source: sourceId,
142
+ components: exportRequest.components,
143
+ deviceIds: exportRequest.deviceIds,
144
+ since: exportRequest.since,
145
+ until: exportRequest.until,
146
+ durationMs: now() - startedAt,
147
+ ip: (0, client_ip_js_1.extractClientIp)(request.raw) ?? '(unidentified)',
148
+ };
149
+ if (result.status === 'completed')
150
+ logger.info('log export completed', { meta });
151
+ else if (result.status === 'peer-gone')
152
+ logger.info('log export abandoned — the client closed the connection', { meta });
153
+ else
154
+ logger.warn(`log export ended early: ${result.status}`, { meta });
155
+ });
156
+ }
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ /**
3
+ * The log export (#570): the lines of some components and/or some devices over
4
+ * a time range, by default everything over the last six hours, as NDJSON.
5
+ *
6
+ * One implementation. The admin Logs page and the ops MCP tool both download
7
+ * `GET /api/logs/export` (`api/logs-export-route.ts`), which streams what
8
+ * {@link exportLogEntries} yields. Nothing here builds the export in memory:
9
+ * the source is read one page at a time, the next page only once the socket
10
+ * took the previous lines.
11
+ *
12
+ * Filter semantics: the selected components are OR-ed, the selected devices
13
+ * are OR-ed, and the two facets are AND-ed. Each (component, device) pair is
14
+ * one read through the D898 read contract with its indexed fields
15
+ * (`fromAddonId`, `deviceId`), and the pairs are merged newest first. A line
16
+ * carries one `addonId` and one `deviceId`, so the pairs never overlap; the
17
+ * id set only guards against a source that repeats a line across pages.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.LOG_EXPORT_MAX_ENTRIES = exports.LOG_EXPORT_PAGE_LIMIT = exports.LOG_EXPORT_DEFAULT_WINDOW_MS = void 0;
21
+ exports.parseLogExportRequest = parseLogExportRequest;
22
+ exports.exportSourceOf = exportSourceOf;
23
+ exports.exportLogEntries = exportLogEntries;
24
+ exports.toWireLogLine = toWireLogLine;
25
+ exports.toNdjsonLine = toNdjsonLine;
26
+ const zod_1 = require("zod");
27
+ /** "Everything, last six hours" — the default the issue asked for. */
28
+ exports.LOG_EXPORT_DEFAULT_WINDOW_MS = 6 * 60 * 60 * 1000;
29
+ /** Lines per source page. The read contract caps a page at 1000. */
30
+ exports.LOG_EXPORT_PAGE_LIMIT = 1000;
31
+ /** The most lines one export writes; the last line says when it stopped there. */
32
+ exports.LOG_EXPORT_MAX_ENTRIES = 500_000;
33
+ /** Pages one pair may ask for before the export gives that pair up. */
34
+ const MAX_PAGES_PER_PAIR = 100_000;
35
+ const LevelSchema = zod_1.z.enum(['debug', 'info', 'warn', 'error']);
36
+ /** Query-string shape: lists are comma-separated, times are epoch ms. */
37
+ const RawExportQuerySchema = zod_1.z.object({
38
+ components: zod_1.z.string().max(4000).optional(),
39
+ deviceIds: zod_1.z.string().max(4000).optional(),
40
+ since: zod_1.z.string().regex(/^\d+$/).optional(),
41
+ until: zod_1.z.string().regex(/^\d+$/).optional(),
42
+ level: LevelSchema.optional(),
43
+ source: zod_1.z.string().min(1).max(200).optional(),
44
+ });
45
+ function splitList(raw) {
46
+ if (raw === undefined)
47
+ return [];
48
+ return raw
49
+ .split(',')
50
+ .map((part) => part.trim())
51
+ .filter((part) => part.length > 0);
52
+ }
53
+ /** The query string the route and the MCP tool send, with the defaults applied. */
54
+ function parseLogExportRequest(raw, now) {
55
+ const parsed = RawExportQuerySchema.safeParse(raw);
56
+ if (!parsed.success)
57
+ return { ok: false, error: parsed.error.issues[0]?.message ?? 'bad query' };
58
+ const q = parsed.data;
59
+ const deviceIds = [];
60
+ for (const part of splitList(q.deviceIds)) {
61
+ const n = Number(part);
62
+ if (!Number.isInteger(n) || n < 0)
63
+ return { ok: false, error: `deviceIds: "${part}" is not a device id` };
64
+ deviceIds.push(n);
65
+ }
66
+ const until = q.until !== undefined ? Number(q.until) : now;
67
+ const since = q.since !== undefined ? Number(q.since) : until - exports.LOG_EXPORT_DEFAULT_WINDOW_MS;
68
+ if (since > until)
69
+ return { ok: false, error: 'since is after until' };
70
+ return {
71
+ ok: true,
72
+ request: {
73
+ components: [...new Set(splitList(q.components))],
74
+ deviceIds: [...new Set(deviceIds)],
75
+ since,
76
+ until,
77
+ ...(q.level !== undefined ? { level: q.level } : {}),
78
+ },
79
+ };
80
+ }
81
+ /** The `source` the query string named, if any (the route's default is the hub's files). */
82
+ function exportSourceOf(raw) {
83
+ const parsed = RawExportQuerySchema.safeParse(raw);
84
+ return parsed.success ? parsed.data.source : undefined;
85
+ }
86
+ function pairsOf(request) {
87
+ const components = request.components.length > 0 ? [...request.components] : [undefined];
88
+ const devices = request.deviceIds.length > 0 ? [...request.deviceIds] : [undefined];
89
+ const pairs = [];
90
+ for (const fromAddonId of components) {
91
+ for (const deviceId of devices) {
92
+ pairs.push({
93
+ ...(fromAddonId !== undefined ? { fromAddonId } : {}),
94
+ ...(deviceId !== undefined ? { deviceId } : {}),
95
+ });
96
+ }
97
+ }
98
+ return pairs;
99
+ }
100
+ /** One pair's lines, newest first, paged on demand. */
101
+ class PairCursor {
102
+ base;
103
+ read;
104
+ buffer = [];
105
+ before;
106
+ exhausted = false;
107
+ pages = 0;
108
+ constructor(base, read) {
109
+ this.base = base;
110
+ this.read = read;
111
+ }
112
+ /** The newest unread line, reading pages until one has a line or the pair is done. */
113
+ async peek() {
114
+ while (this.buffer.length === 0 && !this.exhausted) {
115
+ const page = await this.read({
116
+ ...this.base,
117
+ ...(this.before !== undefined ? { before: this.before } : {}),
118
+ });
119
+ this.pages += 1;
120
+ this.buffer = [...page.entries];
121
+ // `done: false` with a short page is a slice whose time budget ran out:
122
+ // ask again from the cursor. No cursor means nothing more to ask for.
123
+ if (page.done || page.nextBefore === null || this.pages >= MAX_PAGES_PER_PAIR) {
124
+ this.exhausted = true;
125
+ }
126
+ else {
127
+ this.before = page.nextBefore;
128
+ }
129
+ }
130
+ return this.buffer[0];
131
+ }
132
+ shift() {
133
+ this.buffer.shift();
134
+ }
135
+ }
136
+ /** The export's lines, newest first, inside `[since, until]`. */
137
+ async function* exportLogEntries(args) {
138
+ const { request, read } = args;
139
+ const limit = args.pageLimit ?? exports.LOG_EXPORT_PAGE_LIMIT;
140
+ const cursors = pairsOf(request).map((pair) => new PairCursor({
141
+ ...pair,
142
+ since: request.since,
143
+ until: request.until,
144
+ ...(request.level !== undefined ? { level: request.level } : {}),
145
+ limit,
146
+ }, read));
147
+ const seen = new Set();
148
+ for (;;) {
149
+ if (args.signal?.aborted === true)
150
+ return;
151
+ let newest = null;
152
+ for (const cursor of cursors) {
153
+ const entry = await cursor.peek();
154
+ if (entry === undefined)
155
+ continue;
156
+ if (newest === null || entry.timestamp > newest.entry.timestamp)
157
+ newest = { cursor, entry };
158
+ }
159
+ if (newest === null)
160
+ return;
161
+ newest.cursor.shift();
162
+ const { entry } = newest;
163
+ if (entry.timestamp < request.since || entry.timestamp > request.until)
164
+ continue;
165
+ if (entry.id !== undefined) {
166
+ if (seen.has(entry.id))
167
+ continue;
168
+ seen.add(entry.id);
169
+ }
170
+ yield entry;
171
+ }
172
+ }
173
+ function toWireLogLine(entry) {
174
+ return {
175
+ ...(entry.id !== undefined ? { id: entry.id } : {}),
176
+ timestamp: new Date(entry.timestamp).toISOString(),
177
+ level: entry.level,
178
+ ...(entry.scope !== undefined ? { scope: entry.scope } : {}),
179
+ message: entry.message,
180
+ ...(entry.tags !== undefined
181
+ ? {
182
+ tags: Object.fromEntries(Object.entries(entry.tags).map(([k, v]) => [k, String(v)])),
183
+ }
184
+ : {}),
185
+ ...(entry.meta !== undefined ? { meta: entry.meta } : {}),
186
+ };
187
+ }
188
+ function toNdjsonLine(entry) {
189
+ return `${JSON.stringify(toWireLogLine(entry))}\n`;
190
+ }
@@ -86,7 +86,7 @@ class ServerUpdateService extends index_js_1.RootUpdateService {
86
86
  // package.json (workspace server/backend OR the active/baked closure).
87
87
  runningPackageJsonPath: options.runningPackageJsonPath ?? path.resolve(__dirname, '..', '..', '..', 'package.json'),
88
88
  workspaceProbeDir: __dirname,
89
- // Default to the runNpm-backed adapter so a host without system npm (a
89
+ // Default to the system-npm adapter (watched: stall cut + process group) so a host without system npm (a
90
90
  // packaged desktop app with a bare bundled Node) can still stage a root
91
91
  // update. `cacheDir` mirrors AddonInstaller's `<dataDir>/addons/.npm-bootstrap`.
92
92
  execNpm: options.execNpm ??
@@ -1,33 +1,108 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.buildSystemExecNpm = buildSystemExecNpm;
4
37
  /**
5
- * `buildSystemExecNpm` — the runNpm-backed `execNpm` the shared
6
- * `RootUpdateService` uses to shell out to npm when staging a root-package
7
- * closure (`@camstack/server` — the single root package for every node role).
38
+ * `buildSystemExecNpm` — the `execNpm` the shared `RootUpdateService` uses to
39
+ * shell out to npm when staging a root-package closure (`@camstack/server` —
40
+ * the single root package for every node role).
8
41
  *
9
- * The engine's built-in default is a raw `execFile('npm', ...)`: on a host with
10
- * NO system npm on PATH — a packaged desktop app shipping a bare bundled Node —
11
- * that dies with ENOENT and a root update can never stage. Routing through
12
- * `@camstack/server/system`'s `runNpm` solves it uniformly: resolve a working npm
13
- * (system → previously-bootstrapped copy under `cacheDir` → bootstrap from the
14
- * registry) and run the SAME args with it. The `cacheDir` mirrors the value
15
- * `AddonInstaller` uses for its own npm bootstrap (`<dataDir>/addons/.npm-bootstrap`)
16
- * so both share one bootstrapped npm per host.
42
+ * Two jobs:
17
43
  *
18
- * `runNpmFn` is a module-level DI seam (defaults to the real `runNpm`) so the
19
- * arg/cwd/timeout mapping is unit-testable without touching the network.
44
+ * 1. Resolve a working npm. On a host with NO system npm on PATH — a packaged
45
+ * desktop app shipping a bare bundled Node — a raw `npm` dies with ENOENT.
46
+ * `@camstack/server/system`'s `resolveNpmInvocation` answers system →
47
+ * previously-bootstrapped copy under `cacheDir` → bootstrap from the
48
+ * registry. The `cacheDir` mirrors `AddonInstaller`'s
49
+ * (`<dataDir>/addons/.npm-bootstrap`) so both share one bootstrapped npm.
50
+ * 2. Run it under the install watcher (`runWatchedCommand`): its own process
51
+ * group, the 5-minute stall cut for an `npm install` into a staging
52
+ * directory, and the caller's timeout as the hard ceiling. This adapter used
53
+ * to call `execFile` with only that ceiling (3 h). On 2026-11-15 the prod
54
+ * hub sat 28 minutes in node-av's ffmpeg postinstall and nothing cut it;
55
+ * `execFile`'s kill would also have left the postinstall grandchild alive.
56
+ *
57
+ * `deps` is the DI seam so the mapping is unit-testable without npm or disk.
20
58
  */
59
+ const path = __importStar(require("node:path"));
21
60
  const system_1 = require("@camstack/server/system");
22
- function buildSystemExecNpm(options, runNpmFn = system_1.runNpm) {
61
+ const index_js_1 = require("../../server-root/index.js");
62
+ const DEFAULT_DEPS = {
63
+ resolveInvocation: system_1.resolveNpmInvocation,
64
+ runWatched: index_js_1.runWatchedCommand,
65
+ progressDirs: index_js_1.npmInstallProgressDirs,
66
+ };
67
+ function installLogger(logger) {
68
+ return {
69
+ debug: (message, context) => logger.debug(message, context),
70
+ info: (message, context) => logger.info(message, context),
71
+ warn: (message, context) => logger.warn(message, context),
72
+ error: (message, context) => logger.error(message, context),
73
+ };
74
+ }
75
+ function sleep(ms) {
76
+ return new Promise((resolve) => setTimeout(resolve, ms));
77
+ }
78
+ function buildSystemExecNpm(options, deps = {}) {
79
+ const resolved = { ...DEFAULT_DEPS, ...deps };
80
+ const log = installLogger(options.logger);
81
+ let progressDirsPromise = null;
23
82
  return async (args, opts) => {
24
- const { stdout } = await runNpmFn(args, {
83
+ const invocation = await resolved.resolveInvocation({
25
84
  cacheDir: options.cacheDir,
26
85
  registry: options.registry,
27
86
  logger: options.logger,
28
- ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
29
- timeout: opts.timeoutMs,
30
87
  });
31
- return { stdout };
88
+ const env = (0, system_1.buildNpmChildEnv)(process.env, process.execPath);
89
+ const watchProgress = (0, index_js_1.npmCommandWatchesProgress)(args, opts.cwd);
90
+ progressDirsPromise ??= watchProgress ? resolved.progressDirs(env) : null;
91
+ const progressDirs = watchProgress && progressDirsPromise !== null ? await progressDirsPromise : undefined;
92
+ return resolved.runWatched({
93
+ command: invocation.command,
94
+ args: [...invocation.argsPrefix, ...args],
95
+ cwd: opts.cwd ?? path.resolve(process.cwd()),
96
+ stallMs: index_js_1.NPM_INSTALL_STALL_MS,
97
+ ceilingMs: opts.timeoutMs,
98
+ pollMs: index_js_1.NPM_INSTALL_POLL_MS,
99
+ graceMs: index_js_1.NPM_INSTALL_KILL_GRACE_MS,
100
+ now: Date.now,
101
+ sleep,
102
+ env,
103
+ watchProgress,
104
+ ...(progressDirs !== undefined ? { progressDirs } : {}),
105
+ log,
106
+ });
32
107
  };
33
108
  }
package/dist/main.js CHANGED
@@ -64,6 +64,7 @@ const addon_upload_1 = require("./api/addon-upload");
64
64
  const mesh_membership_routes_1 = require("./api/mesh-membership-routes");
65
65
  const auth_whoami_1 = require("./api/auth-whoami");
66
66
  const backup_download_js_1 = require("./api/backup-download.js");
67
+ const logs_export_route_js_1 = require("./api/logs-export-route.js");
67
68
  const cap_providers_1 = require("./api/core/cap-providers");
68
69
  const logging_settings_1 = require("./api/core/logging-settings");
69
70
  const request_census_settings_1 = require("./api/core/request-census-settings");
@@ -1022,6 +1023,15 @@ async function bootstrap() {
1022
1023
  capabilities: capabilityRegistry,
1023
1024
  logger: app.get(logging_service_1.LoggingService).createLogger('backup-download'),
1024
1025
  });
1026
+ // GET /api/logs/export — the Logs page's and the ops MCP's NDJSON export
1027
+ // (#570): components and/or devices over a time range, streamed at the
1028
+ // pace the client reads (D447). Selection lives in core/logging/log-export.
1029
+ (0, logs_export_route_js_1.registerLogsExportRoute)(fastify, {
1030
+ verifier: app.get(auth_service_1.AuthService),
1031
+ registry: capabilityRegistry,
1032
+ tail: app.get(logging_service_1.LoggingService),
1033
+ logger: app.get(logging_service_1.LoggingService).createLogger('logs-export'),
1034
+ });
1025
1035
  // POST /api/auth/session — upgrade a tRPC-issued JWT to a browser cookie.
1026
1036
  fastify.post('/api/auth/session', async (request, reply) => {
1027
1037
  const token = request.body?.token;
@@ -85,6 +85,12 @@ var require_dist = __commonJS({
85
85
  HOST_EXTERNAL_SPECIFIERS: /* @__PURE__ */ __name(() => HOST_EXTERNAL_SPECIFIERS, "HOST_EXTERNAL_SPECIFIERS"),
86
86
  HUB_ROOT_SPEC: /* @__PURE__ */ __name(() => HUB_ROOT_SPEC2, "HUB_ROOT_SPEC"),
87
87
  LAST_BOOTED_FILE: /* @__PURE__ */ __name(() => LAST_BOOTED_FILE, "LAST_BOOTED_FILE"),
88
+ NPM_INSTALL_CEILING_MS: /* @__PURE__ */ __name(() => NPM_INSTALL_CEILING_MS, "NPM_INSTALL_CEILING_MS"),
89
+ NPM_INSTALL_EXIT_WAIT_MS: /* @__PURE__ */ __name(() => NPM_INSTALL_EXIT_WAIT_MS, "NPM_INSTALL_EXIT_WAIT_MS"),
90
+ NPM_INSTALL_KILL_GRACE_MS: /* @__PURE__ */ __name(() => NPM_INSTALL_KILL_GRACE_MS, "NPM_INSTALL_KILL_GRACE_MS"),
91
+ NPM_INSTALL_POLL_MS: /* @__PURE__ */ __name(() => NPM_INSTALL_POLL_MS, "NPM_INSTALL_POLL_MS"),
92
+ NPM_INSTALL_STALL_MS: /* @__PURE__ */ __name(() => NPM_INSTALL_STALL_MS, "NPM_INSTALL_STALL_MS"),
93
+ NpmInstallError: /* @__PURE__ */ __name(() => NpmInstallError, "NpmInstallError"),
88
94
  PENDING_ROOT_SWAP_FILE: /* @__PURE__ */ __name(() => PENDING_ROOT_SWAP_FILE, "PENDING_ROOT_SWAP_FILE"),
89
95
  REQUIRED_NATIVE_PACKAGES: /* @__PURE__ */ __name(() => REQUIRED_NATIVE_PACKAGES, "REQUIRED_NATIVE_PACKAGES"),
90
96
  RESTART_INTENT_FILE: /* @__PURE__ */ __name(() => RESTART_INTENT_FILE, "RESTART_INTENT_FILE"),
@@ -128,6 +134,9 @@ var require_dist = __commonJS({
128
134
  isTransientNpmNetworkError: /* @__PURE__ */ __name(() => isTransientNpmNetworkError, "isTransientNpmNetworkError"),
129
135
  migrateToSingleCopy: /* @__PURE__ */ __name(() => migrateToSingleCopy, "migrateToSingleCopy"),
130
136
  minNodeMajorOf: /* @__PURE__ */ __name(() => minNodeMajorOf, "minNodeMajorOf"),
137
+ npmCommandWatchesProgress: /* @__PURE__ */ __name(() => npmCommandWatchesProgress, "npmCommandWatchesProgress"),
138
+ npmInstallProgressDirs: /* @__PURE__ */ __name(() => npmInstallProgressDirs, "npmInstallProgressDirs"),
139
+ npmProcessLaunch: /* @__PURE__ */ __name(() => npmProcessLaunch, "npmProcessLaunch"),
131
140
  pendingRootSwapPath: /* @__PURE__ */ __name(() => pendingRootSwapPath, "pendingRootSwapPath"),
132
141
  planBoot: /* @__PURE__ */ __name(() => planBoot, "planBoot"),
133
142
  readDesktopAppState: /* @__PURE__ */ __name(() => readDesktopAppState, "readDesktopAppState"),
@@ -138,10 +147,12 @@ var require_dist = __commonJS({
138
147
  readServerRootState: /* @__PURE__ */ __name(() => readServerRootState, "readServerRootState"),
139
148
  readWrapperProbes: /* @__PURE__ */ __name(() => readWrapperProbes, "readWrapperProbes"),
140
149
  registerActiveRootResolver: /* @__PURE__ */ __name(() => registerActiveRootResolver, "registerActiveRootResolver"),
150
+ resolveNpmCliJs: /* @__PURE__ */ __name(() => resolveNpmCliJs, "resolveNpmCliJs"),
141
151
  restartIntentMarkerPath: /* @__PURE__ */ __name(() => restartIntentMarkerPath, "restartIntentMarkerPath"),
142
152
  rootEntryPath: /* @__PURE__ */ __name(() => rootEntryPath2, "rootEntryPath"),
143
153
  rootPackageDir: /* @__PURE__ */ __name(() => rootPackageDir2, "rootPackageDir"),
144
154
  runNodeStarter: /* @__PURE__ */ __name(() => runNodeStarter, "runNodeStarter"),
155
+ runWatchedCommand: /* @__PURE__ */ __name(() => runWatchedCommand, "runWatchedCommand"),
145
156
  serverRootDir: /* @__PURE__ */ __name(() => serverRootDir, "serverRootDir"),
146
157
  stagingDirPath: /* @__PURE__ */ __name(() => stagingDirPath, "stagingDirPath"),
147
158
  stateFilePath: /* @__PURE__ */ __name(() => stateFilePath, "stateFilePath"),
@@ -150,6 +161,7 @@ var require_dist = __commonJS({
150
161
  validateVersionDir: /* @__PURE__ */ __name(() => validateVersionDir, "validateVersionDir"),
151
162
  versionDir: /* @__PURE__ */ __name(() => versionDir, "versionDir"),
152
163
  versionsDir: /* @__PURE__ */ __name(() => versionsDir, "versionsDir"),
164
+ watchedCommandLabel: /* @__PURE__ */ __name(() => watchedCommandLabel, "watchedCommandLabel"),
153
165
  writeDesktopAppState: /* @__PURE__ */ __name(() => writeDesktopAppState, "writeDesktopAppState"),
154
166
  writeDesktopInstallRequest: /* @__PURE__ */ __name(() => writeDesktopInstallRequest, "writeDesktopInstallRequest"),
155
167
  writeDevUploadManifest: /* @__PURE__ */ __name(() => writeDevUploadManifest, "writeDevUploadManifest"),
@@ -1550,7 +1562,8 @@ var require_dist = __commonJS({
1550
1562
  startedMs: Date.now(),
1551
1563
  exceeded: false,
1552
1564
  aborted: options.aborted,
1553
- entryLimit: options.entryBudget ?? PROGRESS_WALK_ENTRY_BUDGET
1565
+ entryLimit: options.entryBudget ?? PROGRESS_WALK_ENTRY_BUDGET,
1566
+ timeLimitMs: options.timeBudgetMs ?? PROGRESS_WALK_TIME_BUDGET_MS
1554
1567
  };
1555
1568
  const cheap = await collectCheap(options.stagingDir, options.progressDirs, options.env, budget);
1556
1569
  if (cheap === "aborted") return {
@@ -1610,7 +1623,7 @@ var require_dist = __commonJS({
1610
1623
  function consume(budget) {
1611
1624
  if (budget.aborted()) return "aborted";
1612
1625
  const overEntries = budget.entries >= budget.entryLimit;
1613
- const overTime = Date.now() - budget.startedMs >= PROGRESS_WALK_TIME_BUDGET_MS;
1626
+ const overTime = Date.now() - budget.startedMs >= budget.timeLimitMs;
1614
1627
  if (overEntries || overTime) {
1615
1628
  budget.exceeded = true;
1616
1629
  return "budget";
@@ -2066,6 +2079,18 @@ var require_dist = __commonJS({
2066
2079
  });
2067
2080
  }
2068
2081
  __name(progressReader, "progressReader");
2082
+ function fullWalkReader(options, aborted) {
2083
+ return () => measureInstallProgress({
2084
+ stagingDir: options.cwd,
2085
+ progressDirs: options.progressDirs ?? [],
2086
+ env: options.env ?? {},
2087
+ previousCheap: null,
2088
+ aborted,
2089
+ entryBudget: Number.POSITIVE_INFINITY,
2090
+ timeBudgetMs: Number.POSITIVE_INFINITY
2091
+ });
2092
+ }
2093
+ __name(fullWalkReader, "fullWalkReader");
2069
2094
  async function seedBaseline(watch) {
2070
2095
  if (!watch.enabled) return;
2071
2096
  const initial = await watch.measure();
@@ -2104,11 +2129,13 @@ var require_dist = __commonJS({
2104
2129
  },
2105
2130
  lastOutput: 0,
2106
2131
  lastGrowthAt: startedAt,
2132
+ fullWalk: null,
2107
2133
  readOutput,
2108
2134
  measure: /* @__PURE__ */ __name(() => Promise.resolve({
2109
2135
  kind: "aborted",
2110
2136
  entries: 0
2111
2137
  }), "measure"),
2138
+ measureFull: fullWalkReader(options, () => false),
2112
2139
  noteUnknown: budgetLogger(options)
2113
2140
  };
2114
2141
  watch.measure = progressReader(options, () => watch.baseline.cheap, () => false);
@@ -2118,6 +2145,7 @@ var require_dist = __commonJS({
2118
2145
  __name(prepareWatch, "prepareWatch");
2119
2146
  function bindAbortableMeasure(options, watch, aborted) {
2120
2147
  watch.measure = progressReader(options, () => watch.baseline.cheap, aborted);
2148
+ watch.measureFull = fullWalkReader(options, aborted);
2121
2149
  }
2122
2150
  __name(bindAbortableMeasure, "bindAbortableMeasure");
2123
2151
  function noteChildOutput(output, chunk, sink) {
@@ -2234,9 +2262,34 @@ var require_dist = __commonJS({
2234
2262
  bytes: sample.bytes === null ? watch.baseline.bytes : sample.bytes
2235
2263
  };
2236
2264
  watch.lastOutput = output;
2237
- if (changed || first) watch.lastGrowthAt = now;
2265
+ if (changed || first) {
2266
+ watch.lastGrowthAt = now;
2267
+ watch.fullWalk = null;
2268
+ }
2238
2269
  }
2239
2270
  __name(noteSample, "noteSample");
2271
+ async function judgeUnknown(options, watch, now) {
2272
+ const output = watch.readOutput();
2273
+ if (output !== watch.lastOutput) {
2274
+ watch.lastOutput = output;
2275
+ watch.lastGrowthAt = now;
2276
+ watch.fullWalk = null;
2277
+ return "continue";
2278
+ }
2279
+ const reference = watch.fullWalk;
2280
+ if (reference !== null && now - reference.at < options.stallMs) return "continue";
2281
+ const full = await watch.measureFull();
2282
+ if (full.kind !== "mark") return "aborted";
2283
+ const token = `${full.cheap}:${full.bytes ?? "none"}`;
2284
+ if (reference !== null && reference.token === token) return "stall";
2285
+ if (reference !== null) watch.lastGrowthAt = now;
2286
+ watch.fullWalk = {
2287
+ token,
2288
+ at: now
2289
+ };
2290
+ return "continue";
2291
+ }
2292
+ __name(judgeUnknown, "judgeUnknown");
2240
2293
  async function pollUntilCut(options, exitPromise, readExit, watch) {
2241
2294
  while (readExit() === null) {
2242
2295
  await Promise.race([
@@ -2248,8 +2301,12 @@ var require_dist = __commonJS({
2248
2301
  if (watch.enabled) {
2249
2302
  const sample = await watch.measure();
2250
2303
  if (readExit() !== null || sample.kind === "aborted") return null;
2251
- if (sample.kind === "unknown") watch.noteUnknown(sample);
2252
- else {
2304
+ if (sample.kind === "unknown") {
2305
+ watch.noteUnknown(sample);
2306
+ const verdict = await judgeUnknown(options, watch, now);
2307
+ if (readExit() !== null || verdict === "aborted") return null;
2308
+ if (verdict === "stall") return "timeout-stall";
2309
+ } else {
2253
2310
  noteSample(watch, sample, watch.readOutput(), now);
2254
2311
  if (now - watch.lastGrowthAt >= options.stallMs) return "timeout-stall";
2255
2312
  }
@@ -3035,6 +3092,7 @@ var require_dist = __commonJS({
3035
3092
  const installArgs = [
3036
3093
  "install",
3037
3094
  "--omit=dev",
3095
+ "--save-exact",
3038
3096
  "--no-audit",
3039
3097
  "--no-fund",
3040
3098
  "--loglevel=error"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/server",
3
- "version": "1.2.882",
3
+ "version": "1.2.883",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -66,9 +66,14 @@
66
66
  ],
67
67
  "requires": {
68
68
  "addons": {
69
- "@camstack/addon-admin-ui": ">=1.2.683",
70
- "@camstack/addon-agent-ui": ">=1.2.396",
71
- "@camstack/addon-provider-bosch": ">=0.1.56"
69
+ "@camstack/addon-admin-ui": ">=1.2.684",
70
+ "@camstack/addon-agent-ui": ">=1.2.397",
71
+ "@camstack/addon-pipeline-orchestrator": ">=1.2.691",
72
+ "@camstack/addon-provider-bosch": ">=0.1.57",
73
+ "@camstack/addon-provider-dreame": ">=0.2.178",
74
+ "@camstack/addon-provider-dreo": ">=0.2.165",
75
+ "@camstack/addon-provider-mqtt-ha": ">=0.1.51",
76
+ "@camstack/addon-provider-petkit": ">=0.2.170"
72
77
  },
73
78
  "wrapper": {
74
79
  "desktop": ">=0.0.1",
@@ -77,19 +82,19 @@
77
82
  }
78
83
  },
79
84
  "dependencies": {
80
- "@camstack/addon-admin-ui": "1.2.683",
81
- "@camstack/addon-agent-ui": "1.2.396",
85
+ "@camstack/addon-admin-ui": "1.2.684",
86
+ "@camstack/addon-agent-ui": "1.2.397",
82
87
  "@camstack/addon-auth": "1.2.182",
83
88
  "@camstack/addon-benchmark": "1.2.313",
84
89
  "@camstack/addon-decoder-nodeav": "1.2.149",
85
90
  "@camstack/addon-notifiers": "1.2.639",
86
91
  "@camstack/addon-pipeline": "1.2.654",
87
- "@camstack/addon-pipeline-orchestrator": "1.2.690",
92
+ "@camstack/addon-pipeline-orchestrator": "1.2.691",
88
93
  "@camstack/addon-post-analysis": "1.2.709",
89
94
  "@camstack/develop": "0.1.53",
90
95
  "@camstack/sdk": "1.2.158",
91
- "@camstack/types": "1.2.579",
92
- "@camstack/ui-library": "1.2.457",
96
+ "@camstack/types": "1.2.580",
97
+ "@camstack/ui-library": "1.2.458",
93
98
  "@fastify/compress": "^9.0.0",
94
99
  "@fastify/cookie": "^11.0.2",
95
100
  "@fastify/cors": "^11.2.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/server",
3
- "version": "1.2.882",
3
+ "version": "1.2.883",
4
4
  "description": "CamStack builtins — shipped inside @camstack/server (generated, do not edit)",
5
5
  "license": "MIT",
6
6
  "camstack": {