ceulen 0.31.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 -27
- 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/test/think.test.ts +1 -1
- package/package.json +3 -3
- package/extensions/modules/munin/lib/sdk.ts +0 -218
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Regression tests for the vendored Munin SDK (lib/sdk/, upstream
|
|
2
|
+
// @kalera/munin-sdk 1.6.0). The incident these guard: the envelope advertised
|
|
3
|
+
// a client version that the server's write gate rejected, and nothing in the
|
|
4
|
+
// repo compared the advertised version with the vendored vendor header.
|
|
5
|
+
|
|
6
|
+
import { describe, it, beforeEach } from "node:test";
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { MuninClient, CLIENT_VERSION, MuninTransportError, fetchCapabilities } from "../lib/sdk/index.js";
|
|
10
|
+
|
|
11
|
+
type FetchInit = RequestInit & { signal?: AbortSignal | null };
|
|
12
|
+
|
|
13
|
+
/** A `typeof fetch` fake with a call log. */
|
|
14
|
+
function makeFetch(handler: (url: string, init?: FetchInit) => Response | Promise<Response>) {
|
|
15
|
+
const calls: { url: string; init?: FetchInit }[] = [];
|
|
16
|
+
const impl = (async (input: unknown, init?: FetchInit) => {
|
|
17
|
+
const url = String(input);
|
|
18
|
+
calls.push({ url, init });
|
|
19
|
+
return handler(url, init);
|
|
20
|
+
}) as unknown as typeof fetch;
|
|
21
|
+
return { calls, impl };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const json = (body: unknown, status = 200): Response =>
|
|
25
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
26
|
+
|
|
27
|
+
/** A capabilities payload; `extra` merges into the data envelope. */
|
|
28
|
+
function caps(extra: Record<string, unknown> = {}, serverVersion = "9.9.9") {
|
|
29
|
+
return {
|
|
30
|
+
ok: true,
|
|
31
|
+
data: {
|
|
32
|
+
specVersion: "1.0",
|
|
33
|
+
actions: { core: ["store", "search", "retrieve", "list", "recent", "delete"], optional: [] },
|
|
34
|
+
features: {},
|
|
35
|
+
metadata: { serverVersion, timestamp: "2026-11-26T00:00:00.000Z" },
|
|
36
|
+
...extra,
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isAction = (url: string): boolean => url.endsWith("/api/mcp/action");
|
|
42
|
+
|
|
43
|
+
beforeEach(() => {
|
|
44
|
+
globalThis.__munin_caps = undefined;
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe("vendored SDK — envelope version", () => {
|
|
48
|
+
it("sends CLIENT_VERSION in the action envelope, and the vendored SDK IS that version", async () => {
|
|
49
|
+
const { calls, impl } = makeFetch((url) => (isAction(url) ? json({ ok: true, data: {} }) : json(caps())));
|
|
50
|
+
const client = new MuninClient({ baseUrl: "https://munin.test", apiKey: "k", fetchImpl: impl, writeQueue: false });
|
|
51
|
+
await client.store("proj", { key: "k" });
|
|
52
|
+
|
|
53
|
+
const post = calls.find((c) => isAction(c.url));
|
|
54
|
+
assert.ok(post, "an action POST happened");
|
|
55
|
+
const body = JSON.parse(String(post!.init?.body)) as { client?: unknown };
|
|
56
|
+
assert.deepEqual(body.client, { name: "@kalera/munin-sdk", version: CLIENT_VERSION });
|
|
57
|
+
|
|
58
|
+
assert.match(CLIENT_VERSION, /^\d+\.\d+\.\d+$/, "CLIENT_VERSION is a semver triple");
|
|
59
|
+
|
|
60
|
+
// The load-bearing half: the constant must match the vendor header of the
|
|
61
|
+
// file that ships it. Bumping one without the other is the incident.
|
|
62
|
+
const source = readFileSync(new URL("../lib/sdk/index.ts", import.meta.url), "utf8");
|
|
63
|
+
const escaped = CLIENT_VERSION.replace(/\./g, "\\.");
|
|
64
|
+
assert.match(
|
|
65
|
+
source,
|
|
66
|
+
new RegExp(`vendored from @kalera/munin-sdk ${escaped}\\b`),
|
|
67
|
+
`lib/sdk/index.ts must declare "vendored from @kalera/munin-sdk ${CLIENT_VERSION}"`,
|
|
68
|
+
);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("vendored SDK — capabilities cache delta", () => {
|
|
73
|
+
it("caches per baseUrl (keyed), not one un-keyed global", async () => {
|
|
74
|
+
const counters: Record<string, number> = {};
|
|
75
|
+
const { calls, impl } = makeFetch((url) => {
|
|
76
|
+
const host = new URL(url).host;
|
|
77
|
+
counters[host] = (counters[host] ?? 0) + 1;
|
|
78
|
+
return json(caps({}, `server-of-${host}`));
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const a = new MuninClient({ baseUrl: "https://a.munin.test", apiKey: "k", fetchImpl: impl, writeQueue: false });
|
|
82
|
+
const b = new MuninClient({ baseUrl: "https://b.munin.test", apiKey: "k", fetchImpl: impl, writeQueue: false });
|
|
83
|
+
|
|
84
|
+
const capsA = await a.capabilities();
|
|
85
|
+
assert.equal(counters["a.munin.test"], 1);
|
|
86
|
+
assert.equal(capsA.metadata.serverVersion, "server-of-a.munin.test");
|
|
87
|
+
|
|
88
|
+
// Upstream's un-keyed global would answer 0 fetches here AND hand B A's
|
|
89
|
+
// capabilities — which, with the write gate, means the wrong server's
|
|
90
|
+
// minimum version silently allows/blocks the write.
|
|
91
|
+
const capsB = await b.capabilities();
|
|
92
|
+
assert.equal(counters["b.munin.test"], 1, "B fetched its own capabilities");
|
|
93
|
+
assert.equal(capsB.metadata.serverVersion, "server-of-b.munin.test");
|
|
94
|
+
|
|
95
|
+
// Single-slot ceiling, on purpose: B's fetch evicted A's slot, so A pays
|
|
96
|
+
// one extra GET. A Map cache would avoid it; the tradeoff (unbounded
|
|
97
|
+
// module-scope state across servers/keys) is worse than one GET.
|
|
98
|
+
const again = await a.capabilities();
|
|
99
|
+
assert.equal(counters["a.munin.test"], 2, "A re-fetched after B evicted it");
|
|
100
|
+
assert.equal(again.metadata.serverVersion, "server-of-a.munin.test");
|
|
101
|
+
|
|
102
|
+
assert.equal(calls.length, 3);
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe("vendored SDK — capabilities timeout delta", () => {
|
|
107
|
+
it("arms a timeout so a dead capabilities endpoint cannot hang the call", async () => {
|
|
108
|
+
const impl = (async (_input: unknown, init?: FetchInit) => {
|
|
109
|
+
// Never answers on its own: only the abort signal settles it.
|
|
110
|
+
return await new Promise<Response>((_resolve, reject) => {
|
|
111
|
+
init?.signal?.addEventListener("abort", () => reject(new Error("aborted")));
|
|
112
|
+
});
|
|
113
|
+
}) as unknown as typeof fetch;
|
|
114
|
+
|
|
115
|
+
await assert.rejects(
|
|
116
|
+
fetchCapabilities("https://munin.test", "k", impl, 25),
|
|
117
|
+
(e: unknown) => e instanceof MuninTransportError && /capabilities endpoint/.test((e as Error).message),
|
|
118
|
+
);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
describe("vendored SDK — writeQueue:false under maintenance", () => {
|
|
123
|
+
it("surfaces MuninMaintenanceError queued:false instead of saving locally", async () => {
|
|
124
|
+
const { impl } = makeFetch((url) =>
|
|
125
|
+
isAction(url)
|
|
126
|
+
? json({ ok: false, error: { code: "MAINTENANCE_READ_ONLY", message: "read only" } }, 503)
|
|
127
|
+
: json(caps()));
|
|
128
|
+
const client = new MuninClient({
|
|
129
|
+
baseUrl: "https://munin.test",
|
|
130
|
+
apiKey: "k",
|
|
131
|
+
fetchImpl: impl,
|
|
132
|
+
writeQueue: false,
|
|
133
|
+
maintenanceRetry: { retries: 0 },
|
|
134
|
+
sleep: async () => {},
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
await assert.rejects(client.store("proj", { key: "k" }), (e: unknown) => {
|
|
138
|
+
const err = e as Error & { queued?: boolean };
|
|
139
|
+
return err.name === "MuninMaintenanceError" && err.queued === false && /try again later/.test(err.message);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe("vendored SDK — pre-write version gate", () => {
|
|
145
|
+
it("refuses a write BEFORE the POST when the server requires a newer client", async () => {
|
|
146
|
+
const { calls, impl } = makeFetch((url) =>
|
|
147
|
+
isAction(url) ? json({ ok: true, data: {} }) : json(caps({ clients: { "@kalera/munin-sdk": { minimum: "99.0.0" } } })));
|
|
148
|
+
const client = new MuninClient({ baseUrl: "https://munin.test", apiKey: "k", fetchImpl: impl, writeQueue: false });
|
|
149
|
+
|
|
150
|
+
await assert.rejects(client.store("proj", { key: "k" }), (e: unknown) => {
|
|
151
|
+
const err = e as Error & { code?: string };
|
|
152
|
+
return err.code === "ERR_CLIENT_OUTDATED" && /too old to write/.test(err.message);
|
|
153
|
+
});
|
|
154
|
+
assert.equal(calls.filter((c) => isAction(c.url)).length, 0, "the write never reached the server");
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it("gates a write that SKIPS the capability check (delete): ensureCapability:false is not a gate bypass", async () => {
|
|
158
|
+
// callMunin dispatches delete with ensureCapability:false (the server does
|
|
159
|
+
// not advertise it), but delete IS in WRITE_ACTIONS — so the gate has to
|
|
160
|
+
// run on that path too.
|
|
161
|
+
const { calls, impl } = makeFetch((url) =>
|
|
162
|
+
isAction(url) ? json({ ok: true, data: {} }) : json(caps({ clients: { "@kalera/munin-sdk": { minimum: "99.0.0" } } })));
|
|
163
|
+
const client = new MuninClient({ baseUrl: "https://munin.test", apiKey: "k", fetchImpl: impl, writeQueue: false });
|
|
164
|
+
|
|
165
|
+
await assert.rejects(
|
|
166
|
+
client.invoke("proj", "delete", { key: "k" }, { ensureCapability: false }),
|
|
167
|
+
(e: unknown) => (e as Error & { code?: string }).code === "ERR_CLIENT_OUTDATED",
|
|
168
|
+
);
|
|
169
|
+
assert.equal(calls.filter((c) => isAction(c.url)).length, 0, "the delete never reached the server");
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("fails open: an old/served minimum lets the write through", async () => {
|
|
173
|
+
const oldMinimum = makeFetch((url) =>
|
|
174
|
+
isAction(url) ? json({ ok: true, data: {} }) : json(caps({ clients: { "@kalera/munin-sdk": { minimum: "0.0.1" } } })));
|
|
175
|
+
await new MuninClient({ baseUrl: "https://m.test", apiKey: "k", fetchImpl: oldMinimum.impl, writeQueue: false })
|
|
176
|
+
.store("proj", { key: "k" });
|
|
177
|
+
assert.equal(oldMinimum.calls.filter((c) => isAction(c.url)).length, 1);
|
|
178
|
+
|
|
179
|
+
const noClients = makeFetch((url) => (isAction(url) ? json({ ok: true, data: {} }) : json(caps())));
|
|
180
|
+
await new MuninClient({ baseUrl: "https://m.test", apiKey: "k", fetchImpl: noClients.impl, writeQueue: false })
|
|
181
|
+
.store("proj", { key: "k" });
|
|
182
|
+
assert.equal(noClients.calls.filter((c) => isAction(c.url)).length, 1);
|
|
183
|
+
|
|
184
|
+
// Malformed minimum (non-string / empty entry) is treated as absent.
|
|
185
|
+
const junk = makeFetch((url) =>
|
|
186
|
+
isAction(url) ? json({ ok: true, data: {} }) : json(caps({ clients: { "@kalera/munin-sdk": {} } })));
|
|
187
|
+
await new MuninClient({ baseUrl: "https://m.test", apiKey: "k", fetchImpl: junk.impl, writeQueue: false })
|
|
188
|
+
.store("proj", { key: "k" });
|
|
189
|
+
assert.equal(junk.calls.filter((c) => isAction(c.url)).length, 1);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("fails open: an unreachable capabilities endpoint is a transport error, never a gate error", async () => {
|
|
193
|
+
// A capabilities fetch that cannot answer still blocks the write — that is
|
|
194
|
+
// upstream's ensureCapability behavior for every munin_* call, not the
|
|
195
|
+
// gate's. What must NOT happen is the gate inventing ERR_CLIENT_OUTDATED.
|
|
196
|
+
const { calls, impl } = makeFetch((url) =>
|
|
197
|
+
isAction(url) ? json({ ok: true, data: {} }) : Promise.reject(new Error("boom")));
|
|
198
|
+
const client = new MuninClient({ baseUrl: "https://munin.test", apiKey: "k", fetchImpl: impl, writeQueue: false });
|
|
199
|
+
|
|
200
|
+
await assert.rejects(client.store("proj", { key: "k" }), (e: unknown) => {
|
|
201
|
+
const err = e as Error & { code?: string };
|
|
202
|
+
return err instanceof MuninTransportError && err.code === undefined && /capabilities endpoint/.test(err.message);
|
|
203
|
+
});
|
|
204
|
+
assert.equal(calls.filter((c) => isAction(c.url)).length, 0);
|
|
205
|
+
});
|
|
206
|
+
});
|
|
@@ -5,7 +5,7 @@ import { describe, it } from "node:test";
|
|
|
5
5
|
import assert from "node:assert/strict";
|
|
6
6
|
import { classifyError, extractRemediation, formatRemediation } from "../lib/helpers.js";
|
|
7
7
|
import { callMunin } from "../index.js";
|
|
8
|
-
import { MuninClient } from "../lib/sdk.js";
|
|
8
|
+
import { MuninClient } from "../lib/sdk/index.js";
|
|
9
9
|
|
|
10
10
|
/** Build an SDK-like error carrying code + details.remediation. */
|
|
11
11
|
function makeStaleError(remediation: Record<string, unknown>): Error & { code: string; details: unknown } {
|
|
@@ -453,6 +453,50 @@ describe("callMunin direct-method dispatch", () => {
|
|
|
453
453
|
});
|
|
454
454
|
});
|
|
455
455
|
|
|
456
|
+
describe("callMunin ERR_CLIENT_OUTDATED", () => {
|
|
457
|
+
it("replaces the server's npm-install remediation with a ceulen upgrade", async () => {
|
|
458
|
+
const original = new Error("ERR_CLIENT_OUTDATED") as Error & { code: string; details: unknown };
|
|
459
|
+
original.code = "ERR_CLIENT_OUTDATED";
|
|
460
|
+
original.details = {
|
|
461
|
+
remediation: { url: "https://munin.example/npm-install", version_to: "1.6.0" },
|
|
462
|
+
};
|
|
463
|
+
const { client } = makeFakeClient({ invoke: () => { throw original; } });
|
|
464
|
+
|
|
465
|
+
await assert.rejects(callMunin(client, "proj", "store", { key: "k" }), (e: unknown) => {
|
|
466
|
+
const err = e as Error & { code?: string; cause?: unknown };
|
|
467
|
+
assert.match(err.message, /ceulen vendors the Munin SDK/);
|
|
468
|
+
// The server's advice (install the npm package / open the setup guide)
|
|
469
|
+
// must never reach the model — it cannot fix a vendored SDK.
|
|
470
|
+
assert.doesNotMatch(err.message, /npm-install|Setup guide/);
|
|
471
|
+
assert.equal(err.code, "ERR_CLIENT_OUTDATED");
|
|
472
|
+
assert.equal(err.cause, original, "the original error is preserved as cause");
|
|
473
|
+
return true;
|
|
474
|
+
});
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
it("cuts the server's install advice from the head, keeping the diagnostic", async () => {
|
|
478
|
+
// The LIVE server message (2026-11-26) ends in npm/plugin install steps —
|
|
479
|
+
// relaying them after "ceulen vendors the SDK" would contradict itself.
|
|
480
|
+
const original = new Error(
|
|
481
|
+
"Munin client @kalera/munin-sdk 1.5.0 is too old to write to this server (minimum 1.6.0). This write was NOT saved. " +
|
|
482
|
+
"Update the Munin client, restart the agent session, then retry. " +
|
|
483
|
+
"Claude Code: npm install -g @kalera/munin-claude@latest && claude plugin update munin-claude-code. " +
|
|
484
|
+
"Other MCP configs: npx -y @kalera/munin-mcp-server@latest.",
|
|
485
|
+
) as Error & { code: string };
|
|
486
|
+
original.code = "ERR_CLIENT_OUTDATED";
|
|
487
|
+
const { client } = makeFakeClient({ invoke: () => { throw original; } });
|
|
488
|
+
|
|
489
|
+
await assert.rejects(callMunin(client, "proj", "store", { key: "k" }), (e: unknown) => {
|
|
490
|
+
const message = (e as Error).message;
|
|
491
|
+
assert.match(message, /too old to write to this server \(minimum 1\.6\.0\)/, "diagnostic head kept");
|
|
492
|
+
assert.match(message, /This write was NOT saved\./);
|
|
493
|
+
assert.match(message, /ceulen vendors the Munin SDK/);
|
|
494
|
+
assert.doesNotMatch(message, /npm install|npx -y|claude plugin update|\/npm-install/, "install advice never relayed");
|
|
495
|
+
return true;
|
|
496
|
+
});
|
|
497
|
+
});
|
|
498
|
+
});
|
|
499
|
+
|
|
456
500
|
describe("remediation helpers", () => {
|
|
457
501
|
it("classifyError carries remediation for ERR_STALE_PROTOCOL with details", () => {
|
|
458
502
|
const remediation = { version_to: "2026-04-17", url: "https://example.com/setup" };
|
|
@@ -44,7 +44,7 @@ describe("think tool", () => {
|
|
|
44
44
|
for (const c of [call, result]) {
|
|
45
45
|
assert.equal(typeof c, "object");
|
|
46
46
|
assert.equal(typeof (c as { render?: unknown }).render, "function", "must be a pi-tui Component");
|
|
47
|
-
const rendered = (c as { render(width?: number): string[] }).render(80);
|
|
47
|
+
const rendered = (c as unknown as { render(width?: number): readonly string[] }).render(80);
|
|
48
48
|
assert.ok(Array.isArray(rendered) && rendered.every((l) => typeof l === "string"));
|
|
49
49
|
}
|
|
50
50
|
assert.match((call as unknown as { render(w: number): string[] }).render(80).join(""), /· think \(4 chars\)/);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ceulen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.0",
|
|
4
4
|
"description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
]
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
|
-
"@earendil-works/pi-coding-agent": ">=0.99.1 <1.
|
|
57
|
-
"@earendil-works/pi-tui": ">=0.99.1 <1.
|
|
56
|
+
"@earendil-works/pi-coding-agent": ">=0.99.1 <1.7.0",
|
|
57
|
+
"@earendil-works/pi-tui": ">=0.99.1 <1.7.0",
|
|
58
58
|
"typebox": "*"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
// ponytail: vendored from @kalera/munin-sdk 1.5.0 (dist/{client,errors,capabilities}.js +
|
|
2
|
-
// types.d.ts) — 152 lines, zero deps, so the bundle keeps its no-runtime-deps rule.
|
|
3
|
-
// Local changes vs upstream: capabilities cache is keyed by `${baseUrl}|${apiKey}`
|
|
4
|
-
// (upstream cached one global `globalThis.__munin_caps`, which went stale when a
|
|
5
|
-
// user switched munin servers per project), and fetchCapabilities arms a timeout
|
|
6
|
-
// like invoke() (upstream could hang forever on a dead server).
|
|
7
|
-
// Upgrade = re-vendor this one file.
|
|
8
|
-
|
|
9
|
-
export type MuninAction = "store" | "retrieve" | "search" | "list" | "recent" | "share" | "versions" | "rollback" | "encrypt" | "decrypt" | "diff" | "delete" | "acknowledge_setup";
|
|
10
|
-
|
|
11
|
-
export interface MuninActionEnvelope<TPayload = Record<string, unknown>> {
|
|
12
|
-
action: MuninAction;
|
|
13
|
-
project: string;
|
|
14
|
-
payload: TPayload;
|
|
15
|
-
requestId?: string;
|
|
16
|
-
client?: {
|
|
17
|
-
name: string;
|
|
18
|
-
version: string;
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export interface MuninCapabilities {
|
|
23
|
-
specVersion: string;
|
|
24
|
-
actions: {
|
|
25
|
-
core: string[];
|
|
26
|
-
optional: string[];
|
|
27
|
-
};
|
|
28
|
-
features: Record<string, {
|
|
29
|
-
supported: boolean;
|
|
30
|
-
reason?: string;
|
|
31
|
-
}>;
|
|
32
|
-
metadata: {
|
|
33
|
-
serverVersion: string;
|
|
34
|
-
timestamp: string;
|
|
35
|
-
[key: string]: unknown;
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface MuninError {
|
|
40
|
-
code: "AUTH_INVALID" | "FEATURE_DISABLED" | "NOT_FOUND" | "RATE_LIMITED" | "VALIDATION_ERROR" | "INTERNAL_ERROR" | "ERR_STALE_PROTOCOL";
|
|
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
|
-
}
|
|
58
|
-
|
|
59
|
-
export class MuninSdkError extends Error {
|
|
60
|
-
code: MuninError["code"] | string;
|
|
61
|
-
details?: Record<string, unknown>;
|
|
62
|
-
constructor(error: MuninError) {
|
|
63
|
-
super(error.message);
|
|
64
|
-
this.name = "MuninSdkError";
|
|
65
|
-
this.code = error.code;
|
|
66
|
-
this.details = error.details;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export class MuninTransportError extends Error {
|
|
71
|
-
constructor(message: string) {
|
|
72
|
-
super(message);
|
|
73
|
-
this.name = "MuninTransportError";
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export async function fetchCapabilities(baseUrl: string, apiKey: string | undefined, fetchImpl: typeof fetch = fetch, timeoutMs = DEFAULT_TIMEOUT_MS): Promise<MuninCapabilities> {
|
|
78
|
-
const response = await fetchImpl(`${baseUrl}/api/mcp/capabilities`, {
|
|
79
|
-
method: "GET",
|
|
80
|
-
headers: {
|
|
81
|
-
"Content-Type": "application/json",
|
|
82
|
-
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
83
|
-
},
|
|
84
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
85
|
-
}).catch((error) => {
|
|
86
|
-
throw new MuninTransportError(`Failed to call capabilities endpoint: ${String(error)}`);
|
|
87
|
-
});
|
|
88
|
-
if (!response.ok) {
|
|
89
|
-
throw new MuninTransportError(`Capabilities request failed with status ${response.status}`);
|
|
90
|
-
}
|
|
91
|
-
const body = (await response.json()) as MuninResponse<MuninCapabilities>;
|
|
92
|
-
if (!body.ok || !body.data) {
|
|
93
|
-
throw new MuninSdkError(body.error ?? {
|
|
94
|
-
code: "INTERNAL_ERROR",
|
|
95
|
-
message: "Capabilities response missing data",
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
return body.data;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export function isActionSupported(capabilities: MuninCapabilities, action: string): boolean {
|
|
102
|
-
return capabilities.actions.core.includes(action) ||
|
|
103
|
-
capabilities.actions.optional.includes(action);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
107
|
-
|
|
108
|
-
export class MuninClient {
|
|
109
|
-
baseUrl: string;
|
|
110
|
-
apiKey: string | undefined;
|
|
111
|
-
timeoutMs: number;
|
|
112
|
-
fetchImpl: typeof fetch;
|
|
113
|
-
constructor(config?: MuninClientConfig) {
|
|
114
|
-
this.baseUrl = (config?.baseUrl || "https://munin.kalera.dev").replace(/\/$/, "");
|
|
115
|
-
this.apiKey = config?.apiKey;
|
|
116
|
-
this.timeoutMs = config?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
117
|
-
this.fetchImpl = config?.fetchImpl ?? fetch;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async capabilities(forceRefresh = false): Promise<MuninCapabilities> {
|
|
121
|
-
const cacheKey = `${this.baseUrl}|${this.apiKey ?? ""}`;
|
|
122
|
-
if (!forceRefresh && globalThis.__munin_caps?.key === cacheKey) {
|
|
123
|
-
return globalThis.__munin_caps.caps;
|
|
124
|
-
}
|
|
125
|
-
const caps = await fetchCapabilities(this.baseUrl, this.apiKey, this.fetchImpl, this.timeoutMs);
|
|
126
|
-
globalThis.__munin_caps = { key: cacheKey, caps };
|
|
127
|
-
return caps;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
async invoke(projectId: string, action: string, payload: Record<string, unknown> = {}, options?: { ensureCapability?: boolean; requestId?: string }): Promise<unknown> {
|
|
131
|
-
if (options?.ensureCapability) {
|
|
132
|
-
const caps = await this.capabilities();
|
|
133
|
-
if (!isActionSupported(caps, action)) {
|
|
134
|
-
throw new MuninSdkError({
|
|
135
|
-
code: "FEATURE_DISABLED",
|
|
136
|
-
message: `Action '${action}' is not supported by current server capabilities`,
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
const controller = new AbortController();
|
|
141
|
-
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
142
|
-
const response = await this.fetchImpl(`${this.baseUrl}/api/mcp/action`, {
|
|
143
|
-
method: "POST",
|
|
144
|
-
headers: {
|
|
145
|
-
"Content-Type": "application/json",
|
|
146
|
-
},
|
|
147
|
-
body: JSON.stringify({
|
|
148
|
-
apiKey: this.apiKey,
|
|
149
|
-
project: projectId,
|
|
150
|
-
projectId, // Fallback for un-restarted server
|
|
151
|
-
action,
|
|
152
|
-
payload,
|
|
153
|
-
requestId: options?.requestId,
|
|
154
|
-
client: {
|
|
155
|
-
name: "@kalera/munin-sdk",
|
|
156
|
-
version: "1.5.0",
|
|
157
|
-
},
|
|
158
|
-
}),
|
|
159
|
-
signal: controller.signal,
|
|
160
|
-
}).catch((error) => {
|
|
161
|
-
clearTimeout(timeout);
|
|
162
|
-
throw new MuninTransportError(`Request failed for action '${action}': ${String(error)}`);
|
|
163
|
-
});
|
|
164
|
-
clearTimeout(timeout);
|
|
165
|
-
const body = (await response.json()) as MuninResponse & { success?: boolean };
|
|
166
|
-
if (!response.ok || (body.ok === false) || (body.success === false)) {
|
|
167
|
-
let errObj: MuninError | undefined = body.error;
|
|
168
|
-
if (typeof errObj === "string") {
|
|
169
|
-
// The server may return `error` as a bare string code
|
|
170
|
-
// (e.g. "ERR_STALE_PROTOCOL"); use it as both the code and message
|
|
171
|
-
// instead of flattening every string error into INTERNAL_ERROR.
|
|
172
|
-
errObj = { code: errObj as MuninError["code"], message: errObj };
|
|
173
|
-
}
|
|
174
|
-
if (!errObj) {
|
|
175
|
-
errObj = {
|
|
176
|
-
code: "INTERNAL_ERROR",
|
|
177
|
-
message: `Unexpected failure invoking action '${action}'`,
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
// A top-level `remediation` (sent alongside the error envelope, e.g. for
|
|
181
|
-
// ERR_STALE_PROTOCOL) is folded into `details` so callers can read it via
|
|
182
|
-
// MuninSdkError.details without losing any existing structured details.
|
|
183
|
-
const remediation = (body as { remediation?: unknown }).remediation;
|
|
184
|
-
if (remediation !== undefined) {
|
|
185
|
-
errObj = {
|
|
186
|
-
...errObj,
|
|
187
|
-
details: { ...(errObj.details ?? {}), remediation },
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
throw new MuninSdkError(errObj);
|
|
191
|
-
}
|
|
192
|
-
return body;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
async store(projectId: string, payload: Record<string, unknown> = {}): Promise<unknown> {
|
|
196
|
-
return this.invoke(projectId, "store", payload, { ensureCapability: true });
|
|
197
|
-
}
|
|
198
|
-
async retrieve(projectId: string, payload: Record<string, unknown> = {}): Promise<unknown> {
|
|
199
|
-
return this.invoke(projectId, "retrieve", payload, { ensureCapability: true });
|
|
200
|
-
}
|
|
201
|
-
async search(projectId: string, payload: Record<string, unknown> = {}): Promise<unknown> {
|
|
202
|
-
return this.invoke(projectId, "search", payload, { ensureCapability: true });
|
|
203
|
-
}
|
|
204
|
-
async list(projectId: string, payload: Record<string, unknown> = {}): Promise<unknown> {
|
|
205
|
-
return this.invoke(projectId, "list", payload, { ensureCapability: true });
|
|
206
|
-
}
|
|
207
|
-
async recent(projectId: string, payload: Record<string, unknown> = {}): Promise<unknown> {
|
|
208
|
-
return this.invoke(projectId, "recent", payload, { ensureCapability: true });
|
|
209
|
-
}
|
|
210
|
-
async share(projectId: string, memoryIds: string[], targetProjectIds: string[]): Promise<unknown> {
|
|
211
|
-
return this.invoke(projectId, "share", { memoryIds, targetProjectIds }, { ensureCapability: true });
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
declare global {
|
|
216
|
-
// eslint-disable-next-line no-var
|
|
217
|
-
var __munin_caps: { key: string; caps: MuninCapabilities } | undefined;
|
|
218
|
-
}
|