ceulen 0.30.0 → 0.32.0

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,370 @@
1
+ // ponytail: vendored from @kalera/munin-sdk 1.6.0 (dist/client.js + client.d.ts).
2
+ // Local deltas marked `// ponytail (local delta):` below.
3
+
4
+ import { MuninMaintenanceError, MuninSdkError, MuninTransportError, type MaintenanceReason } from "./errors.js";
5
+ import { fetchCapabilities, isActionSupported } from "./capabilities.js";
6
+ import {
7
+ DEFAULT_MAINTENANCE_RETRY,
8
+ isDeleteAction,
9
+ isGatewayResponse,
10
+ isMaintenanceResponse,
11
+ isWriteAction,
12
+ keyFingerprint,
13
+ maintenanceDelayMs,
14
+ retryAfterMs,
15
+ stripSecrets,
16
+ type MaintenanceRetryPolicy,
17
+ } from "./maintenance.js";
18
+ import {
19
+ EMPTY_DRAIN_REPORT,
20
+ inFailureBackoff,
21
+ type DrainReport,
22
+ type DrainVerdict,
23
+ type PendingWrite,
24
+ type PendingWriteQueue,
25
+ } from "./writeQueue.js";
26
+ import type { MuninAction, MuninCapabilities, MuninClientConfig, MuninError } from "./types.js";
27
+
28
+ const DEFAULT_TIMEOUT_MS = 15_000;
29
+ const DEFAULT_FLUSH_BEFORE_WRITE_MS = 5_000;
30
+
31
+ // ponytail (local delta 3): exported so the vendored version and the write-gate
32
+ // comparison can be asserted by tests — the incident was an envelope that
33
+ // advertised a version nothing compared.
34
+ export const CLIENT_VERSION = "1.6.0";
35
+
36
+ /** The client name the server's `clients` gate keys on. */
37
+ const CLIENT_NAME = "@kalera/munin-sdk";
38
+
39
+ /** Numeric-segment compare: >0 when a is newer, <0 when b is newer, 0 when equal.
40
+ * Missing/malformed segments count as 0, so a junk minimum fails open. */
41
+ function compareVersions(a: string, b: string): number {
42
+ const pa = a.split(".");
43
+ const pb = b.split(".");
44
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
45
+ const na = Number.parseInt(pa[i] ?? "0", 10);
46
+ const nb = Number.parseInt(pb[i] ?? "0", 10);
47
+ const diff = (Number.isFinite(na) ? na : 0) - (Number.isFinite(nb) ? nb : 0);
48
+ if (diff !== 0) return diff;
49
+ }
50
+ return 0;
51
+ }
52
+
53
+ /**
54
+ * ponytail (local delta 4): refuse a write the server will reject anyway, with a
55
+ * message naming ceulen (the SDK is vendored, so "install the npm package" is
56
+ * wrong advice). Missing/malformed `minimum` fails open — the server stays
57
+ * authoritative.
58
+ */
59
+ function ensureWritableClientVersion(caps: MuninCapabilities): void {
60
+ const minimum = caps.clients?.[CLIENT_NAME]?.minimum;
61
+ if (!minimum || typeof minimum !== "string") return;
62
+ if (compareVersions(CLIENT_VERSION, minimum) >= 0) return;
63
+ throw new MuninSdkError({
64
+ code: "ERR_CLIENT_OUTDATED",
65
+ message: `Munin client ${CLIENT_NAME} ${CLIENT_VERSION} is too old to write to this server (minimum ${minimum}). This write was NOT saved.`,
66
+ });
67
+ }
68
+
69
+ const isNode = (): boolean => typeof process !== "undefined" && Boolean(process.versions?.node);
70
+
71
+ type Reply = {
72
+ ok: boolean;
73
+ status: number;
74
+ body: any;
75
+ jsonBody: boolean;
76
+ maintenance: boolean;
77
+ retryAfterMs: number | null;
78
+ };
79
+
80
+ /** How a replayed write's answer moves the queue (see DrainVerdict). */
81
+ function replayVerdict(reply: Reply, action: string): DrainVerdict {
82
+ if (reply.ok) return "done";
83
+ if (reply.maintenance) return "stop"; // waits for the window to end, without limit
84
+ if (isGatewayResponse(reply.status, reply.jsonBody)) return "stop"; // proxy outage: like offline
85
+ if (reply.status === 404 && isDeleteAction(action)) return "done"; // already gone
86
+ if (reply.status >= 500 || reply.status === 429 || reply.status === 408) return "fail"; // counted, bounded
87
+ return "dead";
88
+ }
89
+
90
+ function toSdkError(body: any, action: string): MuninSdkError {
91
+ let errObj: MuninError | undefined = body?.error;
92
+ if (typeof errObj === "string") {
93
+ // The server may return `error` as a bare string code (e.g. "ERR_STALE_PROTOCOL").
94
+ errObj = { code: errObj as MuninError["code"], message: errObj as unknown as string };
95
+ }
96
+ if (!errObj) {
97
+ errObj = { code: "INTERNAL_ERROR", message: `Unexpected failure invoking action '${action}'` };
98
+ }
99
+ // A top-level `remediation` (e.g. ERR_STALE_PROTOCOL) is folded into `details`.
100
+ if (body?.remediation !== undefined) {
101
+ errObj = { ...errObj, details: { ...(errObj.details ?? {}), remediation: body.remediation } };
102
+ }
103
+ return new MuninSdkError(errObj);
104
+ }
105
+
106
+ export class MuninClient {
107
+ private readonly baseUrl: string;
108
+ private readonly apiKey?: string;
109
+ private readonly timeoutMs: number;
110
+ private readonly fetchImpl: typeof fetch;
111
+ private readonly retryPolicy: MaintenanceRetryPolicy;
112
+ private readonly flushBeforeWriteMs: number;
113
+ private readonly sleep: (ms: number) => Promise<void>;
114
+ private readonly writeQueueOption: PendingWriteQueue | false | undefined;
115
+ private readonly rehydratePayload?: (payload: Record<string, unknown>, strippedKeys: string[]) => Record<string, unknown> | null;
116
+ private defaultQueue?: Promise<PendingWriteQueue>;
117
+ private flushing: Promise<DrainReport> | null = null;
118
+ /** Entries dead-lettered by this client's flushes since takeDeadLetterCount() last ran. */
119
+ private deadLettered = 0;
120
+ /** Deadline (epoch ms) of the running flush; a later caller may only tighten it. */
121
+ private flushDeadline: number | undefined;
122
+
123
+ constructor(config?: MuninClientConfig) {
124
+ this.baseUrl = (config?.baseUrl || "https://munin.kalera.dev").replace(/\/$/, "");
125
+ this.apiKey = config?.apiKey;
126
+ this.timeoutMs = config?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
127
+ this.fetchImpl = config?.fetchImpl ?? fetch;
128
+ this.retryPolicy = { ...DEFAULT_MAINTENANCE_RETRY, ...(config?.maintenanceRetry ?? {}) };
129
+ this.flushBeforeWriteMs = config?.flushBeforeWriteMs ?? DEFAULT_FLUSH_BEFORE_WRITE_MS;
130
+ this.sleep = config?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
131
+ this.writeQueueOption = config?.writeQueue;
132
+ this.rehydratePayload = config?.rehydratePayload;
133
+ }
134
+
135
+ async capabilities(forceRefresh = false): Promise<MuninCapabilities> {
136
+ // ponytail (local delta 1): the cache is keyed by endpoint+key. Upstream
137
+ // stored one un-keyed global, so a session that switched munin servers (or
138
+ // API keys) read the OTHER server's capabilities — and so its write gate.
139
+ // Single slot on purpose: two keys in flight is rare, and the cost of an
140
+ // eviction is one extra GET.
141
+ const cacheKey = `${this.baseUrl}|${this.apiKey ?? ""}`;
142
+ if (!forceRefresh && globalThis.__munin_caps?.key === cacheKey) {
143
+ return globalThis.__munin_caps.caps;
144
+ }
145
+ const caps = await fetchCapabilities(this.baseUrl, this.apiKey, this.fetchImpl, this.timeoutMs);
146
+ globalThis.__munin_caps = { key: cacheKey, caps };
147
+ return caps;
148
+ }
149
+
150
+ async invoke<TPayload extends Record<string, unknown>>(
151
+ projectId: string,
152
+ action: MuninAction,
153
+ payload: TPayload,
154
+ options?: { requestId?: string; ensureCapability?: boolean },
155
+ ): Promise<any> {
156
+ if (options?.ensureCapability) {
157
+ const caps = await this.capabilities();
158
+ if (!isActionSupported(caps, action)) {
159
+ throw new MuninSdkError({
160
+ code: "FEATURE_DISABLED",
161
+ message: `Action '${action}' is not supported by current server capabilities`,
162
+ });
163
+ }
164
+ // ponytail (local delta 4): pre-write version gate, AFTER the capability check.
165
+ if (isWriteAction(action)) ensureWritableClientVersion(caps);
166
+ } else if (isWriteAction(action)) {
167
+ // ponytail (local delta 4): the capability check is skippable (delete and
168
+ // acknowledge_setup are real actions the server does not advertise), but
169
+ // the WRITE GATE is not — an unadvertised write is still a write. Delta 1
170
+ // keys the cache, so this costs no extra GET once capabilities are warm.
171
+ ensureWritableClientVersion(await this.capabilities());
172
+ }
173
+ // A write never overtakes an older queued write: send the queue first, and
174
+ // if something of this project is still waiting, queue behind it.
175
+ if (isWriteAction(action) && !(await this.flushBeforeWrite(projectId))) {
176
+ return this.onMaintenance(projectId, action, payload, null, "pending");
177
+ }
178
+ let reply = await this.sendOnce(projectId, action, payload, options?.requestId);
179
+ for (let attempt = 0; reply.maintenance && attempt < this.retryPolicy.retries; attempt++) {
180
+ await this.sleep(maintenanceDelayMs(attempt, reply.retryAfterMs, this.retryPolicy));
181
+ reply = await this.sendOnce(projectId, action, payload, options?.requestId);
182
+ }
183
+ if (reply.maintenance) return this.onMaintenance(projectId, action, payload, reply.retryAfterMs);
184
+ if (!reply.ok) throw toSdkError(reply.body, action);
185
+ // Munin accepts calls again: send anything a maintenance window left behind.
186
+ void this.flushPendingWrites().catch(() => undefined);
187
+ return reply.body;
188
+ }
189
+
190
+ /**
191
+ * Sends queued writes in order. Single-flight per client; safe to call at
192
+ * process start. With a deadline (epoch ms), entries not yet sent when it
193
+ * passes stay queued, in order (an in-flight request still completes). A
194
+ * deadline given while a flush is running tightens that flush, so no caller
195
+ * waits longer than its own deadline plus one request.
196
+ */
197
+ async flushPendingWrites(deadlineMs?: number): Promise<DrainReport> {
198
+ if (this.flushing) {
199
+ if (deadlineMs !== undefined) this.flushDeadline = Math.min(this.flushDeadline ?? Infinity, deadlineMs);
200
+ return this.flushing;
201
+ }
202
+ this.flushDeadline = deadlineMs;
203
+ this.flushing = this.drainQueue().finally(() => {
204
+ this.flushing = null;
205
+ this.flushDeadline = undefined;
206
+ });
207
+ return this.flushing;
208
+ }
209
+
210
+ /** How many queued writes this client's flushes dead-lettered since the last call; resets to 0. */
211
+ takeDeadLetterCount(): number {
212
+ const count = this.deadLettered;
213
+ this.deadLettered = 0;
214
+ return count;
215
+ }
216
+
217
+ /**
218
+ * Before a write: wait for a flush already running, then flush with a
219
+ * deadline. True when nothing of this client for this project is still
220
+ * queued, i.e. the new write cannot overtake an older store or delete.
221
+ * Bounded by flushBeforeWriteMs plus at most one request timeout.
222
+ */
223
+ private async flushBeforeWrite(projectId: string): Promise<boolean> {
224
+ const queue = await this.resolveQueue();
225
+ if (!queue) return true;
226
+ const deadline = Date.now() + this.flushBeforeWriteMs;
227
+ // A flush already running is tightened to this deadline and awaited; then
228
+ // one pass of our own, which stops at once if the deadline has passed.
229
+ const wasFlushing = this.flushing !== null;
230
+ await this.flushPendingWrites(deadline).catch(() => undefined);
231
+ if (wasFlushing) await this.flushPendingWrites(deadline).catch(() => undefined);
232
+ const fingerprint = await keyFingerprint(this.apiKey);
233
+ return !(await queue.has((w) => w.baseUrl === this.baseUrl && w.keyFingerprint === fingerprint && w.projectId === projectId));
234
+ }
235
+
236
+ private async drainQueue(): Promise<DrainReport> {
237
+ const queue = await this.resolveQueue();
238
+ if (!queue || (await queue.size()) === 0) return EMPTY_DRAIN_REPORT;
239
+ const fingerprint = await keyFingerprint(this.apiKey);
240
+ const report = await queue.drain(async (write: PendingWrite) => {
241
+ if (write.baseUrl !== this.baseUrl || write.keyFingerprint !== fingerprint) return "keep";
242
+ const deadlineMs = this.flushDeadline;
243
+ if (deadlineMs !== undefined && Date.now() >= deadlineMs) return "stop"; // out of time: keep it and everything after it
244
+ if (inFailureBackoff(write, Date.now())) return "stop"; // failed recently: wait, uncounted
245
+ try {
246
+ const reply = await this.sendOnce(write.projectId, write.action as MuninAction, this.rehydrate(write), `replay-${write.id}`);
247
+ return replayVerdict(reply, write.action);
248
+ } catch {
249
+ return "stop"; // offline: try again on a later call, without limit
250
+ }
251
+ });
252
+ this.deadLettered += report.dead;
253
+ return report;
254
+ }
255
+
256
+ /**
257
+ * The stored payload is complete: /api/mcp/action ignores payload.encryptionKey
258
+ * and payload.apiKey, so a missing secret never stops a replay. A rehydrator
259
+ * may still re-add them; null or an exception sends the stored payload.
260
+ */
261
+ private rehydrate(write: PendingWrite): Record<string, unknown> {
262
+ if (write.strippedKeys.length === 0 || !this.rehydratePayload) return write.payload;
263
+ try {
264
+ return this.rehydratePayload(write.payload, write.strippedKeys) ?? write.payload;
265
+ } catch {
266
+ return write.payload;
267
+ }
268
+ }
269
+
270
+ private async onMaintenance(
271
+ projectId: string,
272
+ action: string,
273
+ payload: Record<string, unknown>,
274
+ retryAfter: number | null,
275
+ reason: MaintenanceReason = "maintenance",
276
+ ): Promise<never> {
277
+ const queue = isWriteAction(action) ? await this.resolveQueue() : null;
278
+ if (!queue) throw new MuninMaintenanceError({ queued: false, action, retryAfterMs: retryAfter, reason });
279
+ const { payload: safePayload, strippedKeys } = stripSecrets(payload);
280
+ const write: PendingWrite = {
281
+ id: globalThis.crypto.randomUUID(),
282
+ queuedAt: new Date().toISOString(),
283
+ baseUrl: this.baseUrl,
284
+ keyFingerprint: await keyFingerprint(this.apiKey),
285
+ projectId,
286
+ action,
287
+ payload: safePayload,
288
+ strippedKeys,
289
+ };
290
+ await queue.enqueue(write);
291
+ throw new MuninMaintenanceError({ queued: true, action, retryAfterMs: retryAfter, queueId: write.id, reason });
292
+ }
293
+
294
+ private async resolveQueue(): Promise<PendingWriteQueue | null> {
295
+ if (this.writeQueueOption === false) return null;
296
+ if (this.writeQueueOption) return this.writeQueueOption;
297
+ if (!isNode()) return null;
298
+ this.defaultQueue ??= import("./node/fileWriteQueue.js").then((m) => m.createFileWriteQueue());
299
+ return this.defaultQueue;
300
+ }
301
+
302
+ private async sendOnce(projectId: string, action: MuninAction, payload: Record<string, unknown>, requestId?: string): Promise<Reply> {
303
+ const controller = new AbortController();
304
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
305
+ let response: Response;
306
+ try {
307
+ response = await this.fetchImpl(`${this.baseUrl}/api/mcp/action`, {
308
+ method: "POST",
309
+ headers: { "Content-Type": "application/json" },
310
+ body: JSON.stringify({
311
+ apiKey: this.apiKey,
312
+ project: projectId,
313
+ projectId, // Fallback for un-restarted server
314
+ action,
315
+ payload,
316
+ requestId,
317
+ client: { name: CLIENT_NAME, version: CLIENT_VERSION },
318
+ }),
319
+ signal: controller.signal,
320
+ });
321
+ } catch (error) {
322
+ throw new MuninTransportError(`Request failed for action '${action}': ${String(error)}`);
323
+ } finally {
324
+ clearTimeout(timeout);
325
+ }
326
+ const text = await response.text();
327
+ let body: any;
328
+ try {
329
+ body = text ? JSON.parse(text) : null;
330
+ } catch {
331
+ body = null;
332
+ }
333
+ const jsonBody = body !== null && typeof body === "object" && !Array.isArray(body);
334
+ if (!jsonBody && !text) body = {};
335
+ else if (!jsonBody) body = { ok: false, error: { code: "INTERNAL_ERROR", message: `Non-JSON response (${response.status})` } };
336
+ const maintenance = isMaintenanceResponse(response.status, body);
337
+ return {
338
+ ok: response.ok && body.ok !== false && body.success !== false,
339
+ status: response.status,
340
+ body,
341
+ jsonBody,
342
+ maintenance,
343
+ retryAfterMs: maintenance ? retryAfterMs(response.headers.get("retry-after"), body) : null,
344
+ };
345
+ }
346
+
347
+ async store(projectId: string, payload: Record<string, unknown>): Promise<any> {
348
+ return this.invoke(projectId, "store", payload, { ensureCapability: true });
349
+ }
350
+ async retrieve(projectId: string, payload: Record<string, unknown>): Promise<any> {
351
+ return this.invoke(projectId, "retrieve", payload, { ensureCapability: true });
352
+ }
353
+ async search(projectId: string, payload: Record<string, unknown>): Promise<any> {
354
+ return this.invoke(projectId, "search", payload, { ensureCapability: true });
355
+ }
356
+ async list(projectId: string, payload: Record<string, unknown> = {}): Promise<any> {
357
+ return this.invoke(projectId, "list", payload, { ensureCapability: true });
358
+ }
359
+ async recent(projectId: string, payload: Record<string, unknown> = {}): Promise<any> {
360
+ return this.invoke(projectId, "recent", payload, { ensureCapability: true });
361
+ }
362
+ async share(projectId: string, memoryIds: string[], targetProjectIds: string[]): Promise<any> {
363
+ return this.invoke(projectId, "share", { memoryIds, targetProjectIds }, { ensureCapability: true });
364
+ }
365
+ }
366
+
367
+ declare global {
368
+ // eslint-disable-next-line no-var
369
+ var __munin_caps: { key: string; caps: MuninCapabilities } | undefined;
370
+ }
@@ -0,0 +1,70 @@
1
+ // ponytail: vendored from @kalera/munin-sdk 1.6.0 (dist/errors.js + errors.d.ts) — verbatim.
2
+
3
+ import type { MuninError } from "./types.js";
4
+
5
+ export class MuninSdkError extends Error {
6
+ readonly code: MuninError["code"];
7
+ readonly details?: Record<string, unknown>;
8
+ constructor(error: MuninError) {
9
+ super(error.message);
10
+ this.name = "MuninSdkError";
11
+ this.code = error.code;
12
+ this.details = error.details;
13
+ }
14
+ }
15
+
16
+ export class MuninTransportError extends Error {
17
+ constructor(message: string) {
18
+ super(message);
19
+ this.name = "MuninTransportError";
20
+ }
21
+ }
22
+
23
+ /**
24
+ * maintenance: the server answered MAINTENANCE_READ_ONLY · pending: older
25
+ * queued writes of the project could not be sent yet, so this write waits
26
+ * behind them (the server may well be up).
27
+ */
28
+ export type MaintenanceReason = "maintenance" | "pending";
29
+
30
+ export interface MaintenanceInfo {
31
+ queued: boolean;
32
+ reason?: MaintenanceReason;
33
+ action: string;
34
+ retryAfterMs: number | null;
35
+ queueId?: string;
36
+ }
37
+
38
+ function maintenanceMessage(info: MaintenanceInfo): string {
39
+ if (info.reason === "pending") {
40
+ return info.queued
41
+ ? "Older Munin writes for this project are still waiting to be sent. The write was saved locally behind them and will be retried automatically."
42
+ : "Older Munin writes for this project are still waiting to be sent. Please try again later.";
43
+ }
44
+ return info.queued
45
+ ? "Munin is in maintenance (read-only). The write was saved locally and will be retried automatically."
46
+ : "Munin is in maintenance (read-only). Please try again later.";
47
+ }
48
+
49
+ /**
50
+ * Munin is in a maintenance window (server MUNIN_READ_ONLY). Not retryable by
51
+ * the caller: the client already retried, and a write was queued locally when
52
+ * `queued` is true.
53
+ */
54
+ export class MuninMaintenanceError extends MuninSdkError {
55
+ readonly queued: boolean;
56
+ readonly retryAfterMs: number | null;
57
+ readonly queueId?: string;
58
+ readonly retryable = false;
59
+ constructor(info: MaintenanceInfo) {
60
+ super({
61
+ code: "MAINTENANCE_READ_ONLY",
62
+ message: maintenanceMessage(info),
63
+ details: { ...info },
64
+ });
65
+ this.name = "MuninMaintenanceError";
66
+ this.queued = info.queued;
67
+ this.retryAfterMs = info.retryAfterMs;
68
+ this.queueId = info.queueId;
69
+ }
70
+ }
@@ -0,0 +1,38 @@
1
+ // ponytail: vendored from @kalera/munin-sdk 1.6.0
2
+ // (dist/{client,capabilities,errors,maintenance,types,writeQueue}.js +
3
+ // node/fileWriteQueue.js) — zero deps, so the bundle keeps its no-runtime-deps rule.
4
+ //
5
+ // Server write gate (as of 2026-11-26): the capabilities response advertises
6
+ // `clients["@kalera/munin-sdk"].minimum = 1.6.0`, and /api/mcp/action rejects a
7
+ // write whose envelope `client.version` is below it with ERR_CLIENT_OUTDATED.
8
+ // The envelope version comes from CLIENT_VERSION in client.ts, so bumping the
9
+ // vendored SDK means bumping that constant in the same commit — sdk.test.ts
10
+ // case 1 parses THIS header and fails when the two drift.
11
+ //
12
+ // Local deltas vs upstream (each marked inline):
13
+ // 1. capabilities cache is keyed `${baseUrl}|${apiKey}` — upstream cached one
14
+ // un-keyed global, so a session that switched munin servers read the other
15
+ // server's capabilities (and its write gate).
16
+ // 2. fetchCapabilities takes a timeoutMs and arms AbortSignal.timeout —
17
+ // upstream could hang forever on a dead capabilities endpoint.
18
+ // 3. CLIENT_VERSION is exported (and is 1.6.0, matching the server's minimum).
19
+ // 4. NEW pre-write version gate in invoke(): when the server advertises a
20
+ // higher minimum for this client, a write fails BEFORE the POST with
21
+ // ERR_CLIENT_OUTDATED instead of after it. Missing/malformed minimum fails
22
+ // open — the server stays authoritative.
23
+ // 5. types: ERR_CLIENT_OUTDATED in MuninError["code"], optional `clients` on
24
+ // MuninCapabilities.
25
+ //
26
+ // ponytail: ceiling — this module constructs the client with `writeQueue: false`
27
+ // (see index.ts), so the maintenance/queue machinery below (maintenance.ts,
28
+ // writeQueue.ts, node/fileWriteQueue.ts) is dormant: a write during a server
29
+ // maintenance window surfaces MuninMaintenanceError with queued:false rather
30
+ // than being saved and replayed. Flipping that one boolean (and nothing else)
31
+ // turns local queueing on; the vendored files are kept so that path is real.
32
+
33
+ export * from "./types.js";
34
+ export * from "./errors.js";
35
+ export * from "./capabilities.js";
36
+ export * from "./client.js";
37
+ export * from "./maintenance.js";
38
+ export * from "./writeQueue.js";
@@ -0,0 +1,97 @@
1
+ // ponytail: vendored from @kalera/munin-sdk 1.6.0 (dist/maintenance.js + maintenance.d.ts) — verbatim.
2
+
3
+ /**
4
+ * Client side of the Munin write freeze (server: MUNIN_READ_ONLY). During a
5
+ * maintenance window every write answers 503 with error MAINTENANCE_READ_ONLY
6
+ * and a Retry-After header; reads keep working.
7
+ */
8
+ export const MAINTENANCE_ERROR_CODE = "MAINTENANCE_READ_ONLY";
9
+
10
+ /** Mutating actions by every alias the server accepts (server/config/maintenance.ts MCP_WRITE_ACTIONS). */
11
+ export const WRITE_ACTIONS: ReadonlySet<string> = new Set([
12
+ "store",
13
+ "store_memory",
14
+ "store_batch",
15
+ "share",
16
+ "delete",
17
+ "delete_memory",
18
+ "rollback",
19
+ "acknowledge_setup",
20
+ ]);
21
+
22
+ export function isWriteAction(action: string): boolean {
23
+ return WRITE_ACTIONS.has(String(action).toLowerCase());
24
+ }
25
+
26
+ export function isDeleteAction(action: string): boolean {
27
+ const name = String(action).toLowerCase();
28
+ return name === "delete" || name === "delete_memory";
29
+ }
30
+
31
+ function errorCodeOf(body: unknown): string {
32
+ if (!body || typeof body !== "object") return "";
33
+ const error = (body as { error?: unknown }).error;
34
+ if (typeof error === "string") return error;
35
+ if (error && typeof error === "object" && typeof (error as { code?: unknown }).code === "string") {
36
+ return (error as { code: string }).code;
37
+ }
38
+ return "";
39
+ }
40
+
41
+ export function isMaintenanceResponse(status: number, body: unknown): boolean {
42
+ return status === 503 && errorCodeOf(body) === MAINTENANCE_ERROR_CODE;
43
+ }
44
+
45
+ /**
46
+ * A reverse proxy or CDN answering for a Munin that is restarting or
47
+ * unreachable (502, 503 without MAINTENANCE_READ_ONLY, 504, Cloudflare 52x),
48
+ * or any 5xx whose body is not a JSON object (Munin always answers JSON).
49
+ * Treated like a transport error: the replay stops, nothing is counted.
50
+ */
51
+ export function isGatewayResponse(status: number, jsonBody: boolean): boolean {
52
+ if (status < 500) return false;
53
+ if (!jsonBody) return true;
54
+ return status === 502 || status === 503 || status === 504 || (status >= 520 && status <= 529);
55
+ }
56
+
57
+ /** Retry-After in ms: the header (seconds or an HTTP date) wins over the body's `retryAfter` seconds. */
58
+ export function retryAfterMs(header: string | null, body: unknown, now = Date.now()): number | null {
59
+ if (header) {
60
+ const seconds = Number(header);
61
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
62
+ const date = Date.parse(header);
63
+ if (Number.isFinite(date)) return Math.max(0, date - now);
64
+ }
65
+ const fromBody = Number((body as { retryAfter?: unknown } | null)?.retryAfter);
66
+ return Number.isFinite(fromBody) && fromBody >= 0 ? fromBody * 1000 : null;
67
+ }
68
+
69
+ export interface MaintenanceRetryPolicy {
70
+ /** Retries after the first attempt. */
71
+ retries: number;
72
+ /** Longest single wait whatever Retry-After says: the server advertises 900 s. */
73
+ maxWaitMs: number;
74
+ }
75
+
76
+ export const DEFAULT_MAINTENANCE_RETRY: MaintenanceRetryPolicy = { retries: 2, maxWaitMs: 5_000 };
77
+
78
+ /** Exponential from 1 s, at least Retry-After, never above maxWaitMs. */
79
+ export function maintenanceDelayMs(attempt: number, retryAfter: number | null, policy: MaintenanceRetryPolicy): number {
80
+ return Math.min(Math.max(1_000 * 2 ** attempt, retryAfter ?? 0), policy.maxWaitMs);
81
+ }
82
+
83
+ /** Payload keys that must never be written to the local queue. */
84
+ export const SECRET_PAYLOAD_KEYS: readonly string[] = ["encryptionKey", "apiKey"];
85
+
86
+ export function stripSecrets(payload: Record<string, unknown>): { payload: Record<string, unknown>; strippedKeys: string[] } {
87
+ const strippedKeys = SECRET_PAYLOAD_KEYS.filter((key) => key in payload);
88
+ const kept = Object.fromEntries(Object.entries(payload).filter(([key]) => !SECRET_PAYLOAD_KEYS.includes(key)));
89
+ return { payload: kept, strippedKeys };
90
+ }
91
+
92
+ /** sha-256 of the API key, first 16 hex chars: ties a queued write to its key without storing the key. */
93
+ export async function keyFingerprint(apiKey: string | undefined): Promise<string> {
94
+ if (!apiKey) return "anonymous";
95
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(apiKey));
96
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
97
+ }