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.
- package/CHANGELOG.md +86 -2
- package/extensions/modules/config/index.ts +37 -5
- package/extensions/modules/config/piSettings.ts +15 -6
- package/extensions/modules/config/test/panel.test.ts +63 -0
- package/extensions/modules/config/test/piSettings.test.ts +25 -0
- package/extensions/modules/munin/index.ts +32 -6
- package/extensions/modules/munin/lib/helpers.ts +10 -0
- package/extensions/modules/munin/lib/sdk/capabilities.ts +42 -0
- package/extensions/modules/munin/lib/sdk/client.ts +370 -0
- package/extensions/modules/munin/lib/sdk/errors.ts +70 -0
- package/extensions/modules/munin/lib/sdk/index.ts +38 -0
- package/extensions/modules/munin/lib/sdk/maintenance.ts +97 -0
- package/extensions/modules/munin/lib/sdk/node/fileWriteQueue.ts +296 -0
- package/extensions/modules/munin/lib/sdk/types.ts +74 -0
- package/extensions/modules/munin/lib/sdk/writeQueue.ts +220 -0
- package/extensions/modules/munin/test/extension.test.ts +19 -1
- package/extensions/modules/munin/test/helpers.test.ts +9 -0
- package/extensions/modules/munin/test/sdk.test.ts +206 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +45 -1
- package/extensions/modules/steering/lib/guidance.ts +13 -3
- package/extensions/modules/steering/test/guidance.test.ts +7 -1
- package/extensions/modules/steering/test/think.test.ts +1 -1
- package/package.json +3 -3
- package/extensions/modules/munin/lib/sdk.ts +0 -218
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// ponytail: vendored from @kalera/munin-sdk 1.6.0 (dist/node/fileWriteQueue.js +
|
|
2
|
+
// node/fileWriteQueue.d.ts) — verbatim. Dormant under `writeQueue: false` (the
|
|
3
|
+
// munin module's ceiling), but the dynamic-import specifier in client.ts must
|
|
4
|
+
// typecheck so flipping that one boolean stays a real option.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* File-backed PendingWriteQueue for Node: ~/.munin/pending-writes.jsonl
|
|
8
|
+
* (MUNIN_QUEUE_DIR overrides). Shared by every Munin process of the user (one
|
|
9
|
+
* MCP server per Claude Code session). Two lock files, both created with
|
|
10
|
+
* O_EXCL:
|
|
11
|
+
* - the queue lock guards every read-modify-write of the files and is only
|
|
12
|
+
* ever held for local file work, never across a network request;
|
|
13
|
+
* - the drain lock makes one process at a time send queued writes. A drain
|
|
14
|
+
* claims a snapshot under the queue lock, sends it holding only the drain
|
|
15
|
+
* lock, then applies the outcome under the queue lock again, so writes
|
|
16
|
+
* appended meanwhile are kept, in order.
|
|
17
|
+
* The directory is 0700 and the files 0600: a queued memory can be private
|
|
18
|
+
* content. Dead letters are capped by age and size; the letters a call adds
|
|
19
|
+
* are always written (truncated if one alone exceeds the size cap).
|
|
20
|
+
*/
|
|
21
|
+
import fs from "node:fs/promises";
|
|
22
|
+
import os from "node:os";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import {
|
|
25
|
+
EMPTY_DRAIN_REPORT,
|
|
26
|
+
MAX_PENDING_WRITES,
|
|
27
|
+
WriteQueueFullError,
|
|
28
|
+
applyOutcome,
|
|
29
|
+
drainEntries,
|
|
30
|
+
reportOf,
|
|
31
|
+
type DeadLetter,
|
|
32
|
+
type DrainReport,
|
|
33
|
+
type DrainVerdict,
|
|
34
|
+
type PendingWrite,
|
|
35
|
+
type PendingWriteQueue,
|
|
36
|
+
} from "../writeQueue.js";
|
|
37
|
+
|
|
38
|
+
const FILE_MODE = 0o600;
|
|
39
|
+
const DIR_MODE = 0o700;
|
|
40
|
+
const MAX_BYTES = 10 * 1024 * 1024;
|
|
41
|
+
const LOCK_STALE_MS = 60_000;
|
|
42
|
+
const LOCK_WAIT_MS = 5_000;
|
|
43
|
+
/** Applying a finished drain may wait longer: giving up means resending what was sent. */
|
|
44
|
+
const RECONCILE_LOCK_WAIT_MS = 30_000;
|
|
45
|
+
const LOCK_POLL_MS = 50;
|
|
46
|
+
const PENDING = "pending-writes.jsonl";
|
|
47
|
+
const DEAD = "pending-writes.dead.jsonl";
|
|
48
|
+
const LOCK = "pending-writes.lock";
|
|
49
|
+
const DRAIN_LOCK = "pending-writes.drain.lock";
|
|
50
|
+
|
|
51
|
+
/** Dead letters older than this are pruned whenever new ones are written. */
|
|
52
|
+
export const DEAD_LETTER_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
|
|
53
|
+
|
|
54
|
+
/** The dead-letter file keeps its newest lines within this many bytes. */
|
|
55
|
+
export const DEAD_LETTER_MAX_BYTES = 1024 * 1024;
|
|
56
|
+
|
|
57
|
+
type MalformedLetter = {
|
|
58
|
+
malformed: string;
|
|
59
|
+
deadAt: string;
|
|
60
|
+
deadReason: "malformed";
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type Letter = DeadLetter | MalformedLetter;
|
|
64
|
+
|
|
65
|
+
export function defaultQueueDir(): string {
|
|
66
|
+
return process.env.MUNIN_QUEUE_DIR || path.join(os.homedir(), ".munin");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function lineBytes(line: string): number {
|
|
70
|
+
return Buffer.byteLength(line) + 1; // with its newline
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isYoung(line: string, now: number): boolean {
|
|
74
|
+
try {
|
|
75
|
+
const deadAt = Date.parse(String(JSON.parse(line).deadAt));
|
|
76
|
+
return Number.isFinite(deadAt) && now - deadAt <= DEAD_LETTER_MAX_AGE_MS;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Ways to shrink an oversized letter, tried in order: the text to cut and the line rebuilt around a cut. */
|
|
83
|
+
function shrinkStrategies(letter: Letter): [string, (cut: string) => string][] {
|
|
84
|
+
if ("malformed" in letter) {
|
|
85
|
+
return [[letter.malformed, (cut) => JSON.stringify({ ...letter, malformed: cut, truncated: true })]];
|
|
86
|
+
}
|
|
87
|
+
const payload = letter.payload ?? {};
|
|
88
|
+
const strategies: [string, (cut: string) => string][] = [];
|
|
89
|
+
if (typeof payload.content === "string") {
|
|
90
|
+
strategies.push([payload.content, (cut) => JSON.stringify({ ...letter, payload: { ...payload, content: cut }, truncated: true })]);
|
|
91
|
+
}
|
|
92
|
+
strategies.push([JSON.stringify(payload), (cut) => JSON.stringify({ ...letter, payload: { truncatedPayload: cut }, truncated: true })]);
|
|
93
|
+
return strategies;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The letter as one JSON line that fits DEAD_LETTER_MAX_BYTES: an oversized
|
|
98
|
+
* letter keeps the longest prefix of its payload content (or of the whole
|
|
99
|
+
* payload, or of the malformed line) that fits, marked `truncated: true`.
|
|
100
|
+
*/
|
|
101
|
+
export function fitDeadLetter(letter: Letter): string {
|
|
102
|
+
const line = JSON.stringify(letter);
|
|
103
|
+
if (lineBytes(line) <= DEAD_LETTER_MAX_BYTES) return line;
|
|
104
|
+
for (const [text, rebuild] of shrinkStrategies(letter)) {
|
|
105
|
+
let best = rebuild("");
|
|
106
|
+
if (lineBytes(best) > DEAD_LETTER_MAX_BYTES) continue;
|
|
107
|
+
let lo = 0;
|
|
108
|
+
let hi = Math.min(text.length, DEAD_LETTER_MAX_BYTES);
|
|
109
|
+
while (lo <= hi) {
|
|
110
|
+
const mid = (lo + hi) >> 1;
|
|
111
|
+
const candidate = rebuild(text.slice(0, mid));
|
|
112
|
+
if (lineBytes(candidate) <= DEAD_LETTER_MAX_BYTES) {
|
|
113
|
+
best = candidate;
|
|
114
|
+
lo = mid + 1;
|
|
115
|
+
} else {
|
|
116
|
+
hi = mid - 1;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return best;
|
|
120
|
+
}
|
|
121
|
+
const { deadAt, deadReason } = letter;
|
|
122
|
+
return JSON.stringify("malformed" in letter ? { deadAt, deadReason, truncated: true } : {
|
|
123
|
+
id: letter.id, projectId: letter.projectId, action: letter.action, deadAt, deadReason, truncated: true,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The dead-letter file after adding `added` (lines from fitDeadLetter): every
|
|
129
|
+
* added line is kept, so a letter the user is told about is always there; the
|
|
130
|
+
* older lines are pruned by age, then newest first within what is left of
|
|
131
|
+
* DEAD_LETTER_MAX_BYTES.
|
|
132
|
+
*/
|
|
133
|
+
export function boundDeadLetters(existing: readonly string[], added: readonly string[], now: number): string[] {
|
|
134
|
+
let budget = DEAD_LETTER_MAX_BYTES - added.reduce((sum, line) => sum + lineBytes(line), 0);
|
|
135
|
+
const kept: string[] = [];
|
|
136
|
+
for (let i = existing.length - 1; i >= 0; i--) {
|
|
137
|
+
if (!isYoung(existing[i]!, now)) continue;
|
|
138
|
+
budget -= lineBytes(existing[i]!);
|
|
139
|
+
if (budget < 0) break;
|
|
140
|
+
kept.unshift(existing[i]!);
|
|
141
|
+
}
|
|
142
|
+
return [...kept, ...added];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export class FileWriteQueue implements PendingWriteQueue {
|
|
146
|
+
private readonly dir: string;
|
|
147
|
+
|
|
148
|
+
constructor(dir: string = defaultQueueDir()) {
|
|
149
|
+
this.dir = dir;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private file(name: string): string {
|
|
153
|
+
return path.join(this.dir, name);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Where undeliverable writes end up (reported to the user, never replayed). */
|
|
157
|
+
get deadLetterFile(): string {
|
|
158
|
+
return this.file(DEAD);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** O_EXCL lock with stale takeover; null when still busy after waitMs. */
|
|
162
|
+
private async acquire(name: string, waitMs: number): Promise<{ touch: () => Promise<void>; release: () => Promise<void> } | null> {
|
|
163
|
+
await fs.mkdir(this.dir, { recursive: true, mode: DIR_MODE });
|
|
164
|
+
await fs.chmod(this.dir, DIR_MODE);
|
|
165
|
+
const lock = this.file(name);
|
|
166
|
+
const deadline = Date.now() + waitMs;
|
|
167
|
+
for (;;) {
|
|
168
|
+
try {
|
|
169
|
+
await (await fs.open(lock, "wx", FILE_MODE)).close();
|
|
170
|
+
break;
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
173
|
+
const stat = await fs.stat(lock).catch(() => null);
|
|
174
|
+
if (stat && Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
|
|
175
|
+
await fs.rm(lock, { force: true });
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (Date.now() >= deadline) return null;
|
|
179
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
touch: async () => {
|
|
184
|
+
const now = new Date();
|
|
185
|
+
await fs.utimes(lock, now, now).catch(() => undefined);
|
|
186
|
+
},
|
|
187
|
+
release: () => fs.rm(lock, { force: true }),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private async withQueueLock<T>(fn: () => Promise<T>, waitMs = LOCK_WAIT_MS): Promise<T | null> {
|
|
192
|
+
const lock = await this.acquire(LOCK, waitMs);
|
|
193
|
+
if (!lock) return null;
|
|
194
|
+
try {
|
|
195
|
+
return await fn();
|
|
196
|
+
} finally {
|
|
197
|
+
await lock.release();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private async readAll(): Promise<{ entries: PendingWrite[]; malformed: string[] }> {
|
|
202
|
+
const text = await fs.readFile(this.file(PENDING), "utf8").catch(() => "");
|
|
203
|
+
const entries: PendingWrite[] = [];
|
|
204
|
+
const malformed: string[] = [];
|
|
205
|
+
for (const line of text.split("\n")) {
|
|
206
|
+
if (!line.trim()) continue;
|
|
207
|
+
try {
|
|
208
|
+
entries.push(JSON.parse(line) as PendingWrite);
|
|
209
|
+
} catch {
|
|
210
|
+
malformed.push(line); // never dropped silently: moved to the dead-letter file
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { entries, malformed };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private async append(name: string, lines: string[]): Promise<void> {
|
|
217
|
+
if (lines.length === 0) return;
|
|
218
|
+
const handle = await fs.open(this.file(name), "a", FILE_MODE);
|
|
219
|
+
try {
|
|
220
|
+
await handle.appendFile(lines.join(""), "utf8");
|
|
221
|
+
await handle.sync();
|
|
222
|
+
} finally {
|
|
223
|
+
await handle.close();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async writeAtomic(name: string, lines: string[]): Promise<void> {
|
|
228
|
+
const target = this.file(name);
|
|
229
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
230
|
+
await fs.writeFile(tmp, lines.map((line) => `${line}\n`).join(""), { mode: FILE_MODE });
|
|
231
|
+
await fs.rename(tmp, target);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Under the queue lock. */
|
|
235
|
+
private async addDeadLetters(letters: Letter[], now: number): Promise<void> {
|
|
236
|
+
if (letters.length === 0) return;
|
|
237
|
+
const existing = (await fs.readFile(this.file(DEAD), "utf8").catch(() => "")).split("\n").filter((l) => l.trim());
|
|
238
|
+
await this.writeAtomic(DEAD, boundDeadLetters(existing, letters.map(fitDeadLetter), now));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async enqueue(write: PendingWrite): Promise<void> {
|
|
242
|
+
const line = `${JSON.stringify(write)}\n`;
|
|
243
|
+
const saved = await this.withQueueLock(async () => {
|
|
244
|
+
const size = (await fs.stat(this.file(PENDING)).catch(() => null))?.size ?? 0;
|
|
245
|
+
if (size + Buffer.byteLength(line) > MAX_BYTES) throw new WriteQueueFullError();
|
|
246
|
+
if ((await this.readAll()).entries.length >= MAX_PENDING_WRITES) throw new WriteQueueFullError();
|
|
247
|
+
await this.append(PENDING, [line]);
|
|
248
|
+
return true;
|
|
249
|
+
});
|
|
250
|
+
if (saved === null) throw new Error("Munin local write queue is busy; the write was NOT saved");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async drain(send: (write: PendingWrite) => Promise<DrainVerdict>): Promise<DrainReport> {
|
|
254
|
+
const drainLock = await this.acquire(DRAIN_LOCK, 0);
|
|
255
|
+
// Another process is draining right now: nothing to do here.
|
|
256
|
+
if (!drainLock) return { ...EMPTY_DRAIN_REPORT, remaining: await this.size() };
|
|
257
|
+
try {
|
|
258
|
+
const snapshot = await this.withQueueLock(async () => (await this.readAll()).entries);
|
|
259
|
+
if (snapshot === null) return { ...EMPTY_DRAIN_REPORT, remaining: await this.size() };
|
|
260
|
+
const outcome = await drainEntries(snapshot, send, { afterEach: drainLock.touch });
|
|
261
|
+
const report = await this.withQueueLock(async () => {
|
|
262
|
+
const now = Date.now();
|
|
263
|
+
const { entries, malformed } = await this.readAll();
|
|
264
|
+
const next = applyOutcome(entries, outcome);
|
|
265
|
+
const deadAt = new Date(now).toISOString();
|
|
266
|
+
const malformedLetters = malformed.map((raw) => ({ malformed: raw, deadAt, deadReason: "malformed" as const }));
|
|
267
|
+
await this.addDeadLetters([...outcome.dead, ...malformedLetters], now);
|
|
268
|
+
await this.writeAtomic(PENDING, next.map((e) => JSON.stringify(e)));
|
|
269
|
+
const base = reportOf(outcome, next.length);
|
|
270
|
+
return { ...base, dead: base.dead + malformed.length };
|
|
271
|
+
}, RECONCILE_LOCK_WAIT_MS);
|
|
272
|
+
if (report === null) throw new Error("Munin local write queue stayed busy; sent writes may be sent again");
|
|
273
|
+
return report;
|
|
274
|
+
} finally {
|
|
275
|
+
await drainLock.release();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async size(): Promise<number> {
|
|
280
|
+
return (await this.readAll()).entries.length;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* No lock: the file is only ever appended to under the lock or replaced by
|
|
285
|
+
* an atomic rename, so a reader sees a whole snapshot (a half-written last
|
|
286
|
+
* line parses as malformed and is ignored here). While a drain is sending,
|
|
287
|
+
* its entries are still in the file: conservative.
|
|
288
|
+
*/
|
|
289
|
+
async has(match: (write: PendingWrite) => boolean): Promise<boolean> {
|
|
290
|
+
return (await this.readAll()).entries.some(match);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function createFileWriteQueue(dir?: string): FileWriteQueue {
|
|
295
|
+
return new FileWriteQueue(dir);
|
|
296
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// ponytail: vendored from @kalera/munin-sdk 1.6.0 (dist/types.d.ts + the
|
|
2
|
+
// `export {}` of types.js). Local delta 5: ERR_CLIENT_OUTDATED added to
|
|
3
|
+
// MuninError["code"] and the optional `clients` advertisement on
|
|
4
|
+
// MuninCapabilities (both exist on the server, neither is in the published
|
|
5
|
+
// .d.ts). Kept in its own file so an upstream re-vendor is a diff, not a merge.
|
|
6
|
+
|
|
7
|
+
export type MuninAction = "store" | "retrieve" | "search" | "list" | "recent" | "share" | "versions" | "rollback" | "encrypt" | "decrypt" | "diff" | "delete" | "acknowledge_setup";
|
|
8
|
+
|
|
9
|
+
export interface MuninActionEnvelope<TPayload = Record<string, unknown>> {
|
|
10
|
+
action: MuninAction;
|
|
11
|
+
project: string;
|
|
12
|
+
payload: TPayload;
|
|
13
|
+
requestId?: string;
|
|
14
|
+
client?: {
|
|
15
|
+
name: string;
|
|
16
|
+
version: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface MuninCapabilities {
|
|
21
|
+
specVersion: string;
|
|
22
|
+
actions: {
|
|
23
|
+
core: string[];
|
|
24
|
+
optional: string[];
|
|
25
|
+
};
|
|
26
|
+
features: Record<string, {
|
|
27
|
+
supported: boolean;
|
|
28
|
+
reason?: string;
|
|
29
|
+
}>;
|
|
30
|
+
metadata: {
|
|
31
|
+
serverVersion: string;
|
|
32
|
+
timestamp: string;
|
|
33
|
+
[key: string]: unknown;
|
|
34
|
+
};
|
|
35
|
+
/** Local delta: the server's per-client version gate (name → minimum/latest). */
|
|
36
|
+
clients?: Record<string, { minimum?: string; latest?: string }>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface MuninError {
|
|
40
|
+
code: "AUTH_INVALID" | "FEATURE_DISABLED" | "NOT_FOUND" | "RATE_LIMITED" | "VALIDATION_ERROR" | "INTERNAL_ERROR" | "ERR_STALE_PROTOCOL" | "MAINTENANCE_READ_ONLY" | "ERR_CLIENT_OUTDATED";
|
|
41
|
+
message: string;
|
|
42
|
+
details?: Record<string, unknown>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface MuninResponse<TData = unknown> {
|
|
46
|
+
ok: boolean;
|
|
47
|
+
data?: TData;
|
|
48
|
+
error?: MuninError;
|
|
49
|
+
requestId?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface MuninClientConfig {
|
|
53
|
+
baseUrl?: string;
|
|
54
|
+
apiKey?: string;
|
|
55
|
+
timeoutMs?: number;
|
|
56
|
+
fetchImpl?: typeof fetch;
|
|
57
|
+
/** Where refused writes wait. Default: ~/.munin under Node, none elsewhere. `false` disables queueing. */
|
|
58
|
+
writeQueue?: import("./writeQueue.js").PendingWriteQueue | false;
|
|
59
|
+
maintenanceRetry?: Partial<import("./maintenance.js").MaintenanceRetryPolicy>;
|
|
60
|
+
/**
|
|
61
|
+
* Before a write, how long the client may spend sending older queued writes
|
|
62
|
+
* (default 5000). Whatever is still queued for the same project after that
|
|
63
|
+
* makes the new write queue behind it instead of overtaking it.
|
|
64
|
+
*/
|
|
65
|
+
flushBeforeWriteMs?: number;
|
|
66
|
+
/**
|
|
67
|
+
* Optionally re-adds stripped secrets (e.g. encryptionKey) at flush time.
|
|
68
|
+
* Never required: the server ignores payload secrets on /api/mcp/action, so
|
|
69
|
+
* null (or no rehydrator) sends the stored payload as is.
|
|
70
|
+
*/
|
|
71
|
+
rehydratePayload?: (payload: Record<string, unknown>, strippedKeys: string[]) => Record<string, unknown> | null;
|
|
72
|
+
/** Test seam. */
|
|
73
|
+
sleep?: (ms: number) => Promise<void>;
|
|
74
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// ponytail: vendored from @kalera/munin-sdk 1.6.0 (dist/writeQueue.js + writeQueue.d.ts) — verbatim.
|
|
2
|
+
|
|
3
|
+
/** A write refused by a maintenance window, kept until Munin accepts writes again. */
|
|
4
|
+
export interface PendingWrite {
|
|
5
|
+
id: string;
|
|
6
|
+
queuedAt: string;
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
keyFingerprint: string;
|
|
9
|
+
projectId: string;
|
|
10
|
+
action: string;
|
|
11
|
+
/** Without SECRET_PAYLOAD_KEYS; `strippedKeys` says which ones a rehydrator may re-add. */
|
|
12
|
+
payload: Record<string, unknown>;
|
|
13
|
+
strippedKeys: string[];
|
|
14
|
+
/** Replays that failed with something other than maintenance, a gateway or a transport error. */
|
|
15
|
+
failedAttempts?: number;
|
|
16
|
+
firstFailedAt?: string;
|
|
17
|
+
lastFailedAt?: string;
|
|
18
|
+
/** Not sent again before this time: a burst of calls counts one failure, not one per call. */
|
|
19
|
+
nextAttemptAt?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* done: sent, drop it · dead: the server rejected it for good, dead-letter it ·
|
|
24
|
+
* keep: not ours (another key or server), leave it · stop: still in
|
|
25
|
+
* maintenance, offline, a gateway answer, in its failure backoff or out of
|
|
26
|
+
* time; keep it and every later entry (order is preserved) · fail: any other
|
|
27
|
+
* server failure (5xx, 429); counted on the entry and backed off, dead-lettered
|
|
28
|
+
* once the failure budget is spent, otherwise it stops the pass like `stop`.
|
|
29
|
+
*/
|
|
30
|
+
export type DrainVerdict = "done" | "dead" | "keep" | "stop" | "fail";
|
|
31
|
+
export type DeadReason = "rejected" | "failed" | "expired";
|
|
32
|
+
export type DeadLetter = PendingWrite & {
|
|
33
|
+
deadAt: string;
|
|
34
|
+
deadReason: DeadReason;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export interface DrainReport {
|
|
38
|
+
sent: number;
|
|
39
|
+
/** Every entry moved to the dead letters, expired ones included. */
|
|
40
|
+
dead: number;
|
|
41
|
+
/** Dead-lettered because they were queued more than MAX_PENDING_AGE_MS ago. */
|
|
42
|
+
expired: number;
|
|
43
|
+
remaining: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface PendingWriteQueue {
|
|
47
|
+
enqueue(write: PendingWrite): Promise<void>;
|
|
48
|
+
drain(send: (write: PendingWrite) => Promise<DrainVerdict>): Promise<DrainReport>;
|
|
49
|
+
size(): Promise<number>;
|
|
50
|
+
/** Whether any pending write (including one a drain is sending right now) matches. */
|
|
51
|
+
has(match: (write: PendingWrite) => boolean): Promise<boolean>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const MAX_PENDING_WRITES = 1_000;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* An entry is dead-lettered only once it has failed at least MAX_FAILED_ATTEMPTS
|
|
58
|
+
* times (not maintenance, not offline, not a gateway) AND its first failure is
|
|
59
|
+
* at least FAILURE_WINDOW_MS old.
|
|
60
|
+
*/
|
|
61
|
+
export const MAX_FAILED_ATTEMPTS = 5;
|
|
62
|
+
export const FAILURE_WINDOW_MS = 30 * 60_000;
|
|
63
|
+
|
|
64
|
+
/** Wait after the first failure before the entry is sent again; doubles per failure. */
|
|
65
|
+
export const FAILURE_BACKOFF_BASE_MS = 30_000;
|
|
66
|
+
export const FAILURE_BACKOFF_MAX_MS = 5 * 60_000;
|
|
67
|
+
|
|
68
|
+
/** A queued write older than this is never replayed: it could overwrite newer edits. */
|
|
69
|
+
export const MAX_PENDING_AGE_MS = 24 * 60 * 60_000;
|
|
70
|
+
|
|
71
|
+
export const EMPTY_DRAIN_REPORT: DrainReport = { sent: 0, dead: 0, expired: 0, remaining: 0 };
|
|
72
|
+
|
|
73
|
+
export class WriteQueueFullError extends Error {
|
|
74
|
+
constructor() {
|
|
75
|
+
super("Munin local write queue is full; the write was NOT saved");
|
|
76
|
+
this.name = "WriteQueueFullError";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function isExpired(write: PendingWrite, now: number): boolean {
|
|
81
|
+
const queuedAt = Date.parse(write.queuedAt);
|
|
82
|
+
return !Number.isFinite(queuedAt) || now - queuedAt > MAX_PENDING_AGE_MS;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Backoff after the n-th failure (n >= 1). */
|
|
86
|
+
export function failureBackoffMs(failedAttempts: number): number {
|
|
87
|
+
return Math.min(FAILURE_BACKOFF_BASE_MS * 2 ** Math.max(0, failedAttempts - 1), FAILURE_BACKOFF_MAX_MS);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function recordFailure(write: PendingWrite, now: number): PendingWrite {
|
|
91
|
+
const failedAttempts = (write.failedAttempts ?? 0) + 1;
|
|
92
|
+
return {
|
|
93
|
+
...write,
|
|
94
|
+
failedAttempts,
|
|
95
|
+
firstFailedAt: write.firstFailedAt ?? new Date(now).toISOString(),
|
|
96
|
+
lastFailedAt: new Date(now).toISOString(),
|
|
97
|
+
nextAttemptAt: new Date(now + failureBackoffMs(failedAttempts)).toISOString(),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Whether the entry is still waiting out the backoff of its last failure: not sent, not counted. */
|
|
102
|
+
export function inFailureBackoff(write: PendingWrite, now: number): boolean {
|
|
103
|
+
const next = write.nextAttemptAt ? Date.parse(write.nextAttemptAt) : NaN;
|
|
104
|
+
return Number.isFinite(next) && now < next;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function failureBudgetSpent(write: PendingWrite, now: number): boolean {
|
|
108
|
+
if ((write.failedAttempts ?? 0) < MAX_FAILED_ATTEMPTS) return false;
|
|
109
|
+
const first = write.firstFailedAt ? Date.parse(write.firstFailedAt) : NaN;
|
|
110
|
+
return Number.isFinite(first) && now - first >= FAILURE_WINDOW_MS;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function deadLetter(write: PendingWrite, reason: DeadReason, now: number): DeadLetter {
|
|
114
|
+
return { ...write, deadAt: new Date(now).toISOString(), deadReason: reason };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** What one drain pass did, by entry id, so a queue can apply it to entries appended meanwhile. */
|
|
118
|
+
export interface DrainOutcome {
|
|
119
|
+
sent: number;
|
|
120
|
+
/** Ids to drop: sent or dead-lettered. */
|
|
121
|
+
removed: ReadonlySet<string>;
|
|
122
|
+
/** Entries whose failure count changed. */
|
|
123
|
+
updated: ReadonlyMap<string, PendingWrite>;
|
|
124
|
+
dead: DeadLetter[];
|
|
125
|
+
expired: number;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface DrainOptions {
|
|
129
|
+
/** Called after every send (a file queue keeps its drain lock fresh). */
|
|
130
|
+
afterEach?: () => Promise<void>;
|
|
131
|
+
now?: () => number;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** One drain pass, shared by every implementation so they agree on order and verdicts. */
|
|
135
|
+
export async function drainEntries(
|
|
136
|
+
entries: readonly PendingWrite[],
|
|
137
|
+
send: (write: PendingWrite) => Promise<DrainVerdict>,
|
|
138
|
+
options: DrainOptions = {},
|
|
139
|
+
): Promise<DrainOutcome> {
|
|
140
|
+
const now = options.now ?? Date.now;
|
|
141
|
+
const removed = new Set<string>();
|
|
142
|
+
const updated = new Map<string, PendingWrite>();
|
|
143
|
+
const dead: DeadLetter[] = [];
|
|
144
|
+
let sent = 0;
|
|
145
|
+
let expired = 0;
|
|
146
|
+
let stopped = false;
|
|
147
|
+
for (const entry of entries) {
|
|
148
|
+
if (isExpired(entry, now())) {
|
|
149
|
+
removed.add(entry.id);
|
|
150
|
+
dead.push(deadLetter(entry, "expired", now()));
|
|
151
|
+
expired += 1;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (stopped) continue;
|
|
155
|
+
const verdict = await send(entry);
|
|
156
|
+
await options.afterEach?.();
|
|
157
|
+
if (verdict === "done") {
|
|
158
|
+
removed.add(entry.id);
|
|
159
|
+
sent += 1;
|
|
160
|
+
} else if (verdict === "dead") {
|
|
161
|
+
removed.add(entry.id);
|
|
162
|
+
dead.push(deadLetter(entry, "rejected", now()));
|
|
163
|
+
} else if (verdict === "fail") {
|
|
164
|
+
const failed = recordFailure(entry, now());
|
|
165
|
+
if (failureBudgetSpent(failed, now())) {
|
|
166
|
+
removed.add(entry.id);
|
|
167
|
+
dead.push(deadLetter(failed, "failed", now()));
|
|
168
|
+
} else {
|
|
169
|
+
updated.set(entry.id, failed);
|
|
170
|
+
stopped = true;
|
|
171
|
+
}
|
|
172
|
+
} else if (verdict === "stop") {
|
|
173
|
+
stopped = true;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { sent, removed, updated, dead, expired };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The queue after a pass: entries appended while it ran are kept, in order. */
|
|
180
|
+
export function applyOutcome(current: readonly PendingWrite[], outcome: DrainOutcome): PendingWrite[] {
|
|
181
|
+
return current.filter((e) => !outcome.removed.has(e.id)).map((e) => outcome.updated.get(e.id) ?? e);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function reportOf(outcome: DrainOutcome, remaining: number): DrainReport {
|
|
185
|
+
return { sent: outcome.sent, dead: outcome.dead.length, expired: outcome.expired, remaining };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** In-process queue: tests, browsers, or callers that persist elsewhere. */
|
|
189
|
+
export class MemoryWriteQueue implements PendingWriteQueue {
|
|
190
|
+
private entries: PendingWrite[] = [];
|
|
191
|
+
private draining = false;
|
|
192
|
+
readonly deadLetters: DeadLetter[] = [];
|
|
193
|
+
|
|
194
|
+
async enqueue(write: PendingWrite): Promise<void> {
|
|
195
|
+
if (this.entries.length >= MAX_PENDING_WRITES) throw new WriteQueueFullError();
|
|
196
|
+
this.entries = [...this.entries, write];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async drain(send: (write: PendingWrite) => Promise<DrainVerdict>): Promise<DrainReport> {
|
|
200
|
+
if (this.draining) return { ...EMPTY_DRAIN_REPORT, remaining: this.entries.length };
|
|
201
|
+
this.draining = true;
|
|
202
|
+
try {
|
|
203
|
+
// Entries stay queued while they are sent, so has() sees them.
|
|
204
|
+
const outcome = await drainEntries(this.entries, send);
|
|
205
|
+
this.entries = applyOutcome(this.entries, outcome);
|
|
206
|
+
this.deadLetters.push(...outcome.dead);
|
|
207
|
+
return reportOf(outcome, this.entries.length);
|
|
208
|
+
} finally {
|
|
209
|
+
this.draining = false;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async size(): Promise<number> {
|
|
214
|
+
return this.entries.length;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async has(match: (write: PendingWrite) => boolean): Promise<boolean> {
|
|
218
|
+
return this.entries.some(match);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -8,7 +8,7 @@ import { join } from "node:path";
|
|
|
8
8
|
import { describe, it, beforeEach, afterEach } from "node:test";
|
|
9
9
|
import assert from "node:assert/strict";
|
|
10
10
|
import { projectSettingsPath, OUTPUT_MAX_BYTES } from "../lib/helpers.js";
|
|
11
|
-
import { MuninClient } from "../lib/sdk.js";
|
|
11
|
+
import { MuninClient } from "../lib/sdk/index.js";
|
|
12
12
|
import muninExtension, { MUNIN_PROTOCOL_HEADER } from "../index.js";
|
|
13
13
|
|
|
14
14
|
const ENV_KEYS = ["MUNIN_API_KEY", "MUNIN_PROJECT", "MUNIN_BASE_URL", "PI_CODING_AGENT_DIR"] as const;
|
|
@@ -215,6 +215,24 @@ describe("munin extension", () => {
|
|
|
215
215
|
assert.match(out.content[0].text, /fetch failed/);
|
|
216
216
|
});
|
|
217
217
|
|
|
218
|
+
it("tool_result hook classifies a rewritten client_outdated error by its message (no code on the wire)", async () => {
|
|
219
|
+
const h = harness();
|
|
220
|
+
const hook = h.handlers.tool_result[0];
|
|
221
|
+
// callMunin's client_outdated branch rewrites the message and drops the
|
|
222
|
+
// advice; only the "too old to write" phrasing survives for the hook,
|
|
223
|
+
// which re-classifies from text alone.
|
|
224
|
+
const out = await hook({
|
|
225
|
+
toolName: "munin_store",
|
|
226
|
+
isError: true,
|
|
227
|
+
content: [{
|
|
228
|
+
type: "text",
|
|
229
|
+
text: "Munin client @kalera/munin-sdk 1.6.0 is too old to write to this server (minimum 99.0.0). This write was NOT saved. ceulen vendors the Munin SDK — this is fixed by upgrading ceulen, not by installing the npm package.",
|
|
230
|
+
}],
|
|
231
|
+
});
|
|
232
|
+
assert.equal(out.details.errorType, "client_outdated");
|
|
233
|
+
assert.match(out.content[0].text, /^Munin client_outdated error: /);
|
|
234
|
+
});
|
|
235
|
+
|
|
218
236
|
it("tool_result hook ignores non-munin tools and successful results", async () => {
|
|
219
237
|
const h = harness();
|
|
220
238
|
const hook = h.handlers.tool_result[0];
|
|
@@ -267,6 +267,8 @@ describe("classifyError", () => {
|
|
|
267
267
|
["FEATURE_DISABLED", "feature_disabled"],
|
|
268
268
|
["RATE_LIMITED", "rate_limit"],
|
|
269
269
|
["ERR_STALE_PROTOCOL", "stale_protocol"],
|
|
270
|
+
["ERR_CLIENT_OUTDATED", "client_outdated"],
|
|
271
|
+
["MAINTENANCE_READ_ONLY", "maintenance"],
|
|
270
272
|
["NOT_FOUND", "not_found"],
|
|
271
273
|
] as const;
|
|
272
274
|
for (const [code, type] of cases) {
|
|
@@ -520,4 +522,11 @@ describe("formatCapabilities", () => {
|
|
|
520
522
|
assert.match(result, /experimental/);
|
|
521
523
|
assert.match(result, /✗/);
|
|
522
524
|
});
|
|
525
|
+
|
|
526
|
+
it("prints the client write gate (minimum/latest) so it is observable", () => {
|
|
527
|
+
const result = formatCapabilities({
|
|
528
|
+
clients: { "@kalera/munin-sdk": { minimum: "1.6.0", latest: "1.7.2" } },
|
|
529
|
+
});
|
|
530
|
+
assert.match(result, /Client @kalera\/munin-sdk: minimum 1\.6\.0, latest 1\.7\.2/);
|
|
531
|
+
});
|
|
523
532
|
});
|