@camstack/server 1.2.176 → 1.2.178

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.
@@ -0,0 +1,181 @@
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
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DEFAULT_NPM_REGISTRY = void 0;
37
+ exports.readInstalledAddonPackages = readInstalledAddonPackages;
38
+ exports.buildAddonUpdateEntries = buildAddonUpdateEntries;
39
+ exports.resolvePublishedVersion = resolvePublishedVersion;
40
+ exports.buildAgentAddonUpdateReport = buildAgentAddonUpdateReport;
41
+ /**
42
+ * Agent-local addon ALIGNMENT report — "is this node behind?", answered
43
+ * WITHOUT the hub.
44
+ *
45
+ * ── Why this is read-only, and the update button is not here ──────────────
46
+ * Updating an addon on an agent is hub-driven and CANNOT be initiated here:
47
+ * the hub packs the version IT resolved and pushes the tarball over
48
+ * `$agent.deploy` (`api/core/cap-providers.ts` `updatePackage`, agent branch).
49
+ * There is no agent→hub trigger for that — the `addons` capability is
50
+ * `mount: 'server-provided'`, i.e. it exists only inside the hub's tRPC
51
+ * router and is never published as a Moleculer cap service, so an agent's
52
+ * broker cannot reach it; and CLAUDE.md forbids minting a Moleculer action
53
+ * for business logic to bridge the gap.
54
+ *
55
+ * Pulling the published tarball locally instead would be a SECOND install
56
+ * channel resolving a DIFFERENT artifact: the hub routinely ships builds via
57
+ * `camstack deploy` that were never published, so a node that self-pulled
58
+ * npm-latest would run bytes the hub never sent and still report itself
59
+ * updated. That is precisely the divergence the hub-push path exists to
60
+ * prevent.
61
+ *
62
+ * So this module answers the question the isolated operator actually has —
63
+ * *which of my addons are behind the published release?* — and the UI names
64
+ * where the action lives. A read that cannot mislead beats a button that
65
+ * cannot work.
66
+ */
67
+ const fs = __importStar(require("node:fs"));
68
+ const path = __importStar(require("node:path"));
69
+ const index_js_1 = require("../server-root/index.js");
70
+ const addon_scan_js_1 = require("./addon-scan.js");
71
+ /** Default public registry, matching `AddonInstaller.downloadNpmTarball`. */
72
+ exports.DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
73
+ /** Read `<dir>/package.json`'s `name` + `version`, tolerating a broken file. */
74
+ function readPackageIdentity(dir) {
75
+ try {
76
+ const parsed = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
77
+ if (typeof parsed.name !== 'string' || parsed.name.length === 0)
78
+ return null;
79
+ return {
80
+ packageName: parsed.name,
81
+ installedVersion: typeof parsed.version === 'string' ? parsed.version : null,
82
+ };
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ /**
89
+ * Every addon package installed under `addonsDir`, keyed by its npm PACKAGE
90
+ * name (not the addon declaration id — the two differ for scoped packages and
91
+ * only the package name can be looked up in a registry).
92
+ *
93
+ * `@camstack/system` is deliberately INCLUDED: on an agent the addon-root copy
94
+ * is the only copy of the builtin infra (D87), so it is exactly the package an
95
+ * operator needs to see the version of when a node is misaligned.
96
+ */
97
+ function readInstalledAddonPackages(addonsDir) {
98
+ const found = [];
99
+ for (const dir of (0, addon_scan_js_1.resolveAddonPackageDirs)(addonsDir)) {
100
+ const identity = readPackageIdentity(dir);
101
+ if (identity !== null)
102
+ found.push(identity);
103
+ }
104
+ return found.sort((a, b) => a.packageName.localeCompare(b.packageName));
105
+ }
106
+ /**
107
+ * Pure join of the on-disk roster with the published versions.
108
+ *
109
+ * `updateAvailable` requires BOTH versions to be known and the published one
110
+ * to be strictly newer. An unknown published version is never "up to date"
111
+ * and never "behind" — it is unknown, and carries its error into the row.
112
+ */
113
+ function buildAddonUpdateEntries(installed, published) {
114
+ return installed.map((pkg) => {
115
+ const latest = published.get(pkg.packageName);
116
+ const latestVersion = latest?.latestVersion ?? null;
117
+ const updateAvailable = latestVersion !== null &&
118
+ pkg.installedVersion !== null &&
119
+ (0, index_js_1.compareSemver)(latestVersion, pkg.installedVersion) > 0;
120
+ return {
121
+ packageName: pkg.packageName,
122
+ installedVersion: pkg.installedVersion,
123
+ latestVersion,
124
+ updateAvailable,
125
+ error: latest?.error ?? null,
126
+ };
127
+ });
128
+ }
129
+ /**
130
+ * Resolve `dist-tags.latest` for one package over the registry's HTTPS API —
131
+ * the same door `AddonInstaller.downloadNpmTarball` uses, so a host with no
132
+ * `npm` on PATH (a packaged desktop agent) still gets an answer.
133
+ *
134
+ * Never throws: a failure becomes `{ latestVersion: null, error }` so one
135
+ * unreachable package cannot blank the whole report.
136
+ */
137
+ async function resolvePublishedVersion(packageName, registryUrl, fetchFn) {
138
+ const base = registryUrl.replace(/\/+$/, '');
139
+ const url = `${base}/${encodeURIComponent(packageName).replace(/^%40/, '@')}`;
140
+ try {
141
+ const res = await fetchFn(url);
142
+ if (!res.ok)
143
+ return { latestVersion: null, error: `registry GET → ${res.status}` };
144
+ const body = (await res.json());
145
+ const latest = body['dist-tags']?.['latest'];
146
+ if (typeof latest !== 'string' || latest.length === 0) {
147
+ return { latestVersion: null, error: 'registry returned no dist-tags.latest' };
148
+ }
149
+ return { latestVersion: latest, error: null };
150
+ }
151
+ catch (err) {
152
+ return { latestVersion: null, error: err instanceof Error ? err.message : String(err) };
153
+ }
154
+ }
155
+ /**
156
+ * Build the full report. The report-wide `error` is set only when EVERY
157
+ * package failed to resolve — that is the "registry unreachable" signal, and
158
+ * distinguishing it from a single 404 is what stops the UI claiming a node is
159
+ * aligned when it simply could not ask.
160
+ */
161
+ async function buildAgentAddonUpdateReport(input) {
162
+ const now = input.now ?? Date.now;
163
+ const registryUrl = input.registryUrl ?? exports.DEFAULT_NPM_REGISTRY;
164
+ const installed = readInstalledAddonPackages(input.addonsDir);
165
+ const published = new Map();
166
+ const resolved = await Promise.all(installed.map(async (pkg) => ({
167
+ packageName: pkg.packageName,
168
+ result: await resolvePublishedVersion(pkg.packageName, registryUrl, input.fetchFn),
169
+ })));
170
+ for (const r of resolved)
171
+ published.set(r.packageName, r.result);
172
+ const entries = buildAddonUpdateEntries(installed, published);
173
+ const allFailed = entries.length > 0 && entries.every((e) => e.latestVersion === null);
174
+ const firstError = entries.find((e) => e.error !== null)?.error ?? 'registry unreachable';
175
+ return {
176
+ entries,
177
+ checkedAtMs: now(),
178
+ error: allFailed ? `Could not reach ${registryUrl}: ${firstError}` : null,
179
+ hubReachable: input.isHubReachable(),
180
+ };
181
+ }
@@ -54,6 +54,7 @@ const fs = __importStar(require("node:fs"));
54
54
  const path = __importStar(require("node:path"));
55
55
  const fastify_1 = __importDefault(require("fastify"));
56
56
  const agent_http_auth_js_1 = require("./agent-http-auth.js");
57
+ const agent_update_routes_js_1 = require("./agent-update-routes.js");
57
58
  const derive_hub_url_js_1 = require("./derive-hub-url.js");
58
59
  Object.defineProperty(exports, "pickIpv4", { enumerable: true, get: function () { return derive_hub_url_js_1.pickIpv4; } });
59
60
  /** Dotted-numeric version compare; `null` sorts lowest. */
@@ -404,6 +405,10 @@ async function createAgentHttpServer(getBroker, config) {
404
405
  });
405
406
  return { success: true, message: 'Agent reconnecting...' };
406
407
  });
408
+ // -- Updates (framework local; addon roster read-only) --------------
409
+ // Registered AFTER the onRequest hook above, so every path it mounts is
410
+ // gated by the same loopback-or-bearer rule as the rest of `/api/`.
411
+ (0, agent_update_routes_js_1.registerAgentUpdateRoutes)(app, config.updateControls ?? {});
407
412
  // -- Discovered nodes -----------------------------------------------
408
413
  app.get('/api/agent/discovered-nodes', async () => {
409
414
  const b = getBroker();
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ADDON_UPDATE_UNAVAILABLE_REASON = exports.SERVER_UPDATE_UNAVAILABLE_REASON = exports.APPLY_ALREADY_RUNNING_MESSAGE = void 0;
4
+ exports.createAgentServerUpdateControls = createAgentServerUpdateControls;
5
+ exports.registerAgentUpdateRoutes = registerAgentUpdateRoutes;
6
+ /** The message a second concurrent apply gets. Exported so the test names it once. */
7
+ exports.APPLY_ALREADY_RUNNING_MESSAGE = 'Refused: an update is already in flight on this node.';
8
+ /**
9
+ * Bind the routes' controls to a real update engine.
10
+ *
11
+ * The two remembered cells (`lastCheckError`, `lastApply`) mirror the engine's
12
+ * own `checkCache`: an outcome an operator never sees is an outcome that did
13
+ * not happen, and both of these arrive on a different tick from the poll that
14
+ * has to render them.
15
+ */
16
+ function createAgentServerUpdateControls(engine, onError) {
17
+ let lastCheckError = null;
18
+ let lastApply = null;
19
+ let applyInFlight = false;
20
+ return {
21
+ getView: async () => ({
22
+ status: await engine.getServerPackageStatus(),
23
+ lastCheckError,
24
+ lastApply,
25
+ applyInFlight,
26
+ }),
27
+ check: async () => {
28
+ const result = await engine.checkServerUpdate();
29
+ lastCheckError = result.error;
30
+ return result;
31
+ },
32
+ applyLatest: () => {
33
+ if (applyInFlight) {
34
+ return { started: false, message: exports.APPLY_ALREADY_RUNNING_MESSAGE };
35
+ }
36
+ applyInFlight = true;
37
+ lastApply = null;
38
+ void engine
39
+ .applyServerUpdate({})
40
+ .then((result) => {
41
+ lastApply = result;
42
+ if (!result.accepted)
43
+ onError?.(result.message);
44
+ })
45
+ .catch((err) => {
46
+ const message = err instanceof Error ? err.message : String(err);
47
+ lastApply = {
48
+ accepted: false,
49
+ targetVersion: null,
50
+ restarting: false,
51
+ message: `Update failed: ${message}`,
52
+ };
53
+ onError?.(message);
54
+ })
55
+ .finally(() => {
56
+ applyInFlight = false;
57
+ });
58
+ return { started: true, message: null };
59
+ },
60
+ };
61
+ }
62
+ // ---------------------------------------------------------------------------
63
+ // Routes
64
+ // ---------------------------------------------------------------------------
65
+ /** Why the framework card renders empty when nothing was wired. */
66
+ exports.SERVER_UPDATE_UNAVAILABLE_REASON = 'Framework updates are not available on this agent build.';
67
+ /** Why the addon report renders empty when nothing was wired. */
68
+ exports.ADDON_UPDATE_UNAVAILABLE_REASON = 'The addon roster is not available on this agent build.';
69
+ /**
70
+ * Mount the update routes on an already-built agent HTTP server. Called from
71
+ * `createAgentHttpServer` AFTER the auth hook, so every path here inherits it.
72
+ */
73
+ function registerAgentUpdateRoutes(app, controls) {
74
+ const server = controls.server;
75
+ const addons = controls.addons;
76
+ app.get('/api/agent/server-update', async () => {
77
+ if (server === undefined) {
78
+ return { available: false, reason: exports.SERVER_UPDATE_UNAVAILABLE_REASON };
79
+ }
80
+ return { available: true, ...(await server.getView()) };
81
+ });
82
+ app.post('/api/agent/server-update/check', async (_req, reply) => {
83
+ if (server === undefined) {
84
+ return reply.status(503).send({ error: exports.SERVER_UPDATE_UNAVAILABLE_REASON });
85
+ }
86
+ return server.check();
87
+ });
88
+ // No request body is read: the target is always registry `latest`.
89
+ app.post('/api/agent/server-update/apply', async (_req, reply) => {
90
+ if (server === undefined) {
91
+ return reply.status(503).send({ error: exports.SERVER_UPDATE_UNAVAILABLE_REASON });
92
+ }
93
+ return server.applyLatest();
94
+ });
95
+ app.get('/api/agent/addon-updates', async () => {
96
+ if (addons === undefined) {
97
+ return { available: false, reason: exports.ADDON_UPDATE_UNAVAILABLE_REASON };
98
+ }
99
+ return { available: true, ...(await addons.getReport()) };
100
+ });
101
+ }
@@ -47,6 +47,8 @@ const agent_config_js_1 = require("./agent-config.js");
47
47
  const agent_group_runner_js_1 = require("./agent-group-runner.js");
48
48
  const agent_http_js_1 = require("./agent-http.js");
49
49
  const agent_service_js_1 = require("./agent-service.js");
50
+ const agent_addon_updates_js_1 = require("./agent-addon-updates.js");
51
+ const agent_update_routes_js_1 = require("./agent-update-routes.js");
50
52
  const agent_update_service_js_1 = require("./agent-update-service.js");
51
53
  const derive_hub_url_js_1 = require("./derive-hub-url.js");
52
54
  const infra_boot_guard_js_1 = require("./infra-boot-guard.js");
@@ -697,6 +699,29 @@ async function startAgent(configPath) {
697
699
  // Started early (before addon boot) so the status page is reachable
698
700
  // even while addons are still loading.
699
701
  const getBrokerFn = (() => broker);
702
+ // ── Update controls for the agent UI ──────────────────────────────
703
+ // Framework: the LOCAL `AgentUpdateService` — `npm view` + `npm install`
704
+ // straight from the registry, no hub in the path, so an isolated node can
705
+ // repair its own version. Addons: report only (the install is a hub push;
706
+ // see `agent-addon-updates.ts`).
707
+ const updateControls = {
708
+ server: (0, agent_update_routes_js_1.createAgentServerUpdateControls)(agentUpdateService, (message) => {
709
+ // A refused/failed update that logs nothing reads as "never happened".
710
+ consoleLogger.warn(`framework update not applied: ${message}`, {
711
+ tags: { nodeId: config.nodeId },
712
+ });
713
+ }),
714
+ addons: {
715
+ getReport: () => (0, agent_addon_updates_js_1.buildAgentAddonUpdateReport)({
716
+ addonsDir: config.addonsDir,
717
+ ...(process.env['CAMSTACK_NPM_REGISTRY'] !== undefined
718
+ ? { registryUrl: process.env['CAMSTACK_NPM_REGISTRY'] }
719
+ : {}),
720
+ fetchFn: (url) => fetch(url),
721
+ isHubReachable: () => getHubConnectionState() === 'connected',
722
+ }),
723
+ },
724
+ };
700
725
  void (0, agent_http_js_1.startAgentHttpServer)(getBrokerFn, {
701
726
  port: config.statusPort ?? 4444,
702
727
  nodeId: config.nodeId,
@@ -704,6 +729,7 @@ async function startAgent(configPath) {
704
729
  configPath: config.configPath,
705
730
  onReconnect: reconnect,
706
731
  getHubConnectionState,
732
+ updateControls,
707
733
  });
708
734
  // ── Phase 1: Load core infrastructure addons (in-process) ──
709
735
  // storage + settings + metrics + hub-forwarder (log destination)
@@ -99,10 +99,17 @@ function buildSystemProvider(feature, registry, logger, census = (0, http_reques
99
99
  // reachable only through this service now — `system.setRequestCensus` was
100
100
  // retired on 2026-08-27 precisely so two writes cannot disagree about the
101
101
  // same window (D245).
102
+ // The channels themselves are DECLARED by the addons that own them and
103
+ // reached through the registry's per-provider proxies — hub-main never keeps
104
+ // a hand-written list, which would rot at the first addon that adds one.
105
+ const channels = (0, logging_settings_js_1.buildLogChannelPlane)({ entries: () => registry?.getCollectionEntries('log-channels') ?? [] }, (addonId, phase, error) => {
106
+ logger?.warn('log-channels provider unreachable', { meta: { addonId, phase, error } });
107
+ });
102
108
  const loggingSettings = new logging_settings_js_1.LoggingSettingsService({
103
109
  store,
104
110
  gate: (0, system_1.getLoggingGate)(),
105
111
  requestCensus,
112
+ channels,
106
113
  ...(logger !== undefined ? { logger } : {}),
107
114
  });
108
115
  return {
@@ -136,8 +143,8 @@ function buildSystemProvider(feature, registry, logger, census = (0, http_reques
136
143
  setSiteLocation: async (input) => siteLocation.set(input),
137
144
  detectSiteLocation: async () => siteLocation.detect(),
138
145
  getRequestCensus: async () => requestCensus.status(),
139
- getLoggingSettings: async (input) => loggingSettings.get(input.scopeNodeId),
140
- setLoggingSettings: async (input) => loggingSettings.set(input.patch, input.scopeNodeId),
146
+ getLoggingSettings: async (input) => loggingSettings.get(input.scopeNodeId, input.scopeComponent),
147
+ setLoggingSettings: async (input) => loggingSettings.set(input.patch, input.scopeNodeId, input.scopeComponent),
141
148
  };
142
149
  }
143
150
  /**