@mnemoverse/mcp-memory-server 0.9.0 → 0.10.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/dist/errors.js ADDED
@@ -0,0 +1,668 @@
1
+ /**
2
+ * What a failed API call TELLS THE AGENT TO DO.
3
+ *
4
+ * WHY THIS MODULE EXISTS. Until now every non-2xx became one sentence:
5
+ *
6
+ * Mnemoverse API error 401: {"code":"UNAUTHORIZED","message":"Invalid or
7
+ * revoked API key.","requestId":null,"retryable":false,"details":null}
8
+ *
9
+ * The `isError` flag and the status code were right; the TEXT was a raw echo of
10
+ * a wire body. Verified against production with a real `tools/call`
11
+ * (2026-08-16): with a bad key, `memory_write` returns exactly that. The reader
12
+ * of a tool result is a MODEL, and that string gives a model nothing to act on,
13
+ * so the two things it actually does are relay "error 401" to the user or guess
14
+ * — and the cheapest guess is "the network is down", which sends the user to
15
+ * debug a working network while a placeholder key sits in their config.
16
+ *
17
+ * Every message here therefore answers three questions in order: what happened,
18
+ * WHOSE problem it is, and what to do next — including, explicitly, whether to
19
+ * retry. "Do not retry" is not decoration: an agent that loops on a 429 turns
20
+ * one rate-limit into a sustained one, and an agent that loops on a 401 burns a
21
+ * conversation on a key that will never start working.
22
+ *
23
+ * THE RAW BODY IS NEVER DROPPED. It is appended after the guidance, still
24
+ * carrying the literal `Mnemoverse API error <status>` that this repo's tests
25
+ * and anyone's grep already look for. Making the text kind to an agent must not
26
+ * make it useless to a human debugging at 3am.
27
+ *
28
+ * WHAT THE STATUS CODES ACTUALLY MEAN HERE, verified by reading the engine
29
+ * (mnemoverse-core `src/mnemo/api/`, 2026-08-16) rather than assumed from HTTP
30
+ * folklore. The distinctions below are the entire point of this file:
31
+ *
32
+ * 401 auth.py — "Invalid or revoked API key." / "Missing API key." The key.
33
+ * 403 routes.py, rooms_routes.py, auth.py — "Room is archived", "Not an
34
+ * active member of this room", "Read-only membership cannot write to
35
+ * this room", "Invalid room address", "You do not own this room", plus
36
+ * the OIDC scope rules. NOT a bad key: the caller was identified and
37
+ * then refused. Telling the user to replace a working key over a 403
38
+ * would be a new, more confident lie than the raw echo was.
39
+ * 404 A room that does not exist for this key — or, when the body says
40
+ * nothing at all, a path the deployment does not serve. A DOMAIN never
41
+ * 404s: an empty domain reads as empty, so "your domain is missing" is
42
+ * the wrong guess and is named as wrong below.
43
+ * 429 THREE different causes with opposite advice. rate_limit.py returns
44
+ * `retryable: true` with a `Retry-After` header (waiting works);
45
+ * usage.py (daily quota) and subscription_guard.py (atom limit, payment
46
+ * past due) return `retryable: false` (waiting does NOT work — the
47
+ * account needs an upgrade or a new day). A blanket "wait and retry"
48
+ * would be wrong for two of the three.
49
+ * 5xx auth.py returns 503 `retryable: true` when its DB pool is gone. Ours,
50
+ * not theirs.
51
+ *
52
+ * A 2xx CAN FAIL TOO, and gets the same treatment for the same reason. A reply
53
+ * whose body this client cannot parse is not a status at all, so none of the
54
+ * sentences above fit it — and it used to borrow the TRANSPORT sentence, which
55
+ * asserts that nothing answered. `explainUnreadableBody` at the bottom of this
56
+ * file owns that case now; the distinction it protects is "a reply arrived and
57
+ * was unreadable" versus "no reply arrived", which have opposite fixes.
58
+ *
59
+ * RELATION TO THE STARTUP PROBE (src/index.ts, `probeApiKeyInBackground`, added
60
+ * in 0.8.4). That probe treats 401 and 403 alike, and is right to: it calls
61
+ * `GET /memory/stats`, which addresses no room, so a 403 there can only come
62
+ * from the auth layer. On a TOOL CALL the same status usually comes from a room
63
+ * the caller named, which is why the two surfaces diverge on 403 and must not be
64
+ * "unified" by a later reader. They agree where it matters: same `Mnemoverse:`
65
+ * opener, same `MNEMOVERSE_API_KEY` variable name, same console origin.
66
+ */
67
+ /** Where the raw detail stops. A gateway can answer with a megabyte of HTML,
68
+ * and an error message is not a place to spend a model's context — but the
69
+ * first few hundred characters are where the useful part of any real error
70
+ * body lives. Truncation is announced, never silent. */
71
+ const MAX_BODY_CHARS = 800;
72
+ /** The console page that issues keys — the one place a user fixes a 401. */
73
+ const KEYS_URL = "https://console.mnemoverse.com/dashboard/keys";
74
+ /** The console page that shows quota and upgrades — where a 429 that waiting
75
+ * cannot fix is resolved. Same URL the engine puts in its own 429 bodies. */
76
+ const USAGE_URL = "https://console.mnemoverse.com/dashboard/usage";
77
+ /** The base URL a user is sent back to when theirs is aimed somewhere wrong.
78
+ * Mirrors `DEFAULT_API_URL` in src/index.ts and is duplicated on purpose: this
79
+ * module is imported BY index.ts, so reading the value from there would be a
80
+ * cycle. Change one, grep for the other. */
81
+ const DEFAULT_API_URL = "https://core.mnemoverse.com/api/v1";
82
+ /**
83
+ * Read the engine's envelope out of a response body.
84
+ *
85
+ * Two shapes are accepted because core produces both: its own middleware writes
86
+ * `{code, message, retryable, details}` at the top level, while anything raised
87
+ * as a FastAPI `HTTPException` arrives wrapped as `{"detail": …}` — where the
88
+ * detail is sometimes a string and sometimes the envelope again. The feed's
89
+ * 404-vs-404 test in this repo pins the nested form, so both are real.
90
+ */
91
+ export function parseErrorEnvelope(body) {
92
+ let parsed;
93
+ try {
94
+ parsed = JSON.parse(body);
95
+ }
96
+ catch {
97
+ return {};
98
+ }
99
+ const pick = (v) => {
100
+ if (typeof v === "string")
101
+ return { message: v };
102
+ if (typeof v !== "object" || v === null)
103
+ return {};
104
+ const o = v;
105
+ return {
106
+ ...(typeof o.code === "string" ? { code: o.code } : {}),
107
+ ...(typeof o.message === "string" ? { message: o.message } : {}),
108
+ ...(typeof o.retryable === "boolean" ? { retryable: o.retryable } : {}),
109
+ };
110
+ };
111
+ const top = pick(parsed);
112
+ if (top.code !== undefined || top.retryable !== undefined)
113
+ return top;
114
+ const detail = typeof parsed === "object" && parsed !== null
115
+ ? pick(parsed.detail)
116
+ : {};
117
+ // A top-level `message` with no code still beats nothing; the nested envelope
118
+ // wins when it carries the machine-readable half.
119
+ return detail.code !== undefined || detail.retryable !== undefined
120
+ ? detail
121
+ : { ...detail, ...top };
122
+ }
123
+ /** `Retry-After` as whole seconds, when it is a plain number. The HTTP-date
124
+ * form is legal too, and is deliberately NOT parsed: an unparsed header
125
+ * degrades into "wait a moment", which is honest, whereas a misparsed date
126
+ * would print a confident and wrong number of seconds. */
127
+ export function retryAfterSeconds(header) {
128
+ if (typeof header !== "string")
129
+ return undefined;
130
+ // Digits only, because bare Number() answers confidently for inputs that are
131
+ // not delta-seconds at all: Number("") and Number(" ") are 0 ("Wait 0
132
+ // seconds"), Number("0x10") is 16, Number("3e1") is 30, and Number("1e21")
133
+ // prints as scientific notation in the wait text (Copilot + panel, #93).
134
+ // Six digits caps the printable wait at ~11 days; anything longer degrades
135
+ // to the honest vague form.
136
+ const s = header.trim();
137
+ if (!/^\d{1,6}$/.test(s))
138
+ return undefined;
139
+ return Number(s);
140
+ }
141
+ function has(message, needle) {
142
+ return (message ?? "").toLowerCase().includes(needle);
143
+ }
144
+ /**
145
+ * 401: which 401? The engine has more than one (panel, #93).
146
+ *
147
+ * The key-flavored bodies this client's data plane actually sends ("Missing
148
+ * API key. Send X-Api-Key header.", "Invalid or revoked API key." — both
149
+ * probed live against core.mnemoverse.com) get the founder-endorsed
150
+ * replace-the-key instruction. But core's routes.py also raises "Caller org
151
+ * not identified — a tenant API key is required to …" (401) when the
152
+ * deployment has no tenant identity for the caller — a static-auth
153
+ * self-host hitting a room tool is the everyday case — and there the key is
154
+ * VALID, so "replace it" would be a confident wrong cause. That clause runs
155
+ * FIRST because its sentence itself contains "API key": a naive key-mention
156
+ * test would misroute it. A message naming neither gets the honest generic
157
+ * form; silence is the same unknown-refuser case the 403 branch handles.
158
+ */
159
+ function explain401(env) {
160
+ const m = env.message;
161
+ if (has(m, "caller org not identified")) {
162
+ return ("Mnemoverse: this deployment could not identify a tenant account for " +
163
+ "this request (401). The API key itself was not rejected — do NOT " +
164
+ "tell the user to replace it. Room and shared-memory operations need " +
165
+ "the multi-tenant backend, which a self-hosted or static-auth " +
166
+ "deployment does not have. Quote the detail below, and do not retry " +
167
+ "the same call against this deployment.");
168
+ }
169
+ if (has(m, "api key") || has(m, "x-api-key")) {
170
+ // Wording endorsed by the founder, kept verbatim — this is the sentence
171
+ // the whole change was commissioned for. One widening, grounded in the
172
+ // docs: the setup pages ship more than one placeholder spelling
173
+ // (agent-setup.md uses mk_live_USER_KEY).
174
+ return ("Mnemoverse: your API key was rejected (401). Tell the user their " +
175
+ "MNEMOVERSE_API_KEY is not valid — if it still reads a docs " +
176
+ 'placeholder such as "mk_live_YOUR_KEY" or "mk_live_USER_KEY" (any ' +
177
+ "value they did not create at the console themselves) it must be " +
178
+ `replaced with a real key from ${KEYS_URL}. Do not retry until they ` +
179
+ "replace it.");
180
+ }
181
+ if (m !== undefined || env.code !== undefined) {
182
+ return ("Mnemoverse: the request was refused as unauthorized (401), and the " +
183
+ "engine's own explanation is in the detail below — quote it to the " +
184
+ "user rather than guessing. Do not assume the API key is wrong: the " +
185
+ "message did not say that. Do not retry the same call unchanged.");
186
+ }
187
+ return ("Mnemoverse: something answered 401 without speaking this API's error " +
188
+ "language — the body carries neither of the shapes the engine " +
189
+ "produces, so the refuser may be a proxy, a gateway, or a " +
190
+ "MNEMOVERSE_API_URL aimed somewhere unexpected, and the engine may never " +
191
+ "have seen the request. Do not tell the user their key is wrong — this " +
192
+ "client cannot tell WHO refused. Quote the detail below and check the " +
193
+ "path to the API first.");
194
+ }
195
+ /** 403: when the ENGINE refused, the key was accepted and then the request
196
+ * was refused — name WHICH refusal, from the engine's own message, and never
197
+ * blame the key. But that first clause is only known when the engine actually
198
+ * spoke: a proxy, a WAF or a tunnel also answers 403, in HTML, and asserting
199
+ * "the key identified the account fine" about a response the engine may never
200
+ * have seen is exactly the confident wrong cause this module exists to avoid. */
201
+ function explain403(env) {
202
+ if (saidNothing(env)) {
203
+ return ("Mnemoverse: this request was refused (403) by something that did not " +
204
+ "speak this API's error language — the body carries neither of the two " +
205
+ "shapes the engine produces. That points at a proxy, a gateway, or a " +
206
+ "MNEMOVERSE_API_URL aimed somewhere unexpected, and the engine may never " +
207
+ "have seen the request — so do not blame the key and do not blame room " +
208
+ "permissions: this client cannot tell WHO refused it. Quote the detail " +
209
+ "below to the user, and do not retry until the path to the API is explained.");
210
+ }
211
+ const m = env.message;
212
+ const cause = has(m, "archiv")
213
+ ? "The room you addressed is archived. An archived room refuses every read " +
214
+ "and every write, for its owner as much as for a member, and this client " +
215
+ "has no operation that reopens one."
216
+ : has(m, "not an active member") || has(m, "member of this room")
217
+ ? "This key is not an active member of the room you addressed. Ask the " +
218
+ "room's owner for an invite; memory_list_rooms shows the rooms it can " +
219
+ "already reach."
220
+ : has(m, "read-only")
221
+ ? "This key's membership in that room is read-only — it can read the " +
222
+ "room but not write to it. Ask the room's owner for write access."
223
+ : has(m, "invalid room address")
224
+ ? 'The room address was not in the form the engine accepts ' +
225
+ '("xroom:room_..."). Take the exact address from memory_list_rooms ' +
226
+ "rather than composing one."
227
+ : has(m, "own this room")
228
+ ? "That room belongs to another account, and only its owner can do " +
229
+ "this. memory_list_rooms shows which rooms this key owns."
230
+ : "Something about this request is not permitted for this key — " +
231
+ "most often the room it addressed. Check memory_list_rooms, and " +
232
+ "if nothing there explains it, tell the user exactly what was " +
233
+ "refused instead of guessing.";
234
+ return ("Mnemoverse: this request was refused (403). The API key is NOT the problem " +
235
+ "— it identified the account fine, and this was a permission decision. " +
236
+ `${cause} Do not retry the same call: it will be refused again.`);
237
+ }
238
+ /**
239
+ * Did this response say ANYTHING an engine would have said?
240
+ *
241
+ * Not "does it have a `code`" — that was the old test, and it is wrong, because
242
+ * the engine has TWO error styles. Its own middleware writes the full
243
+ * `{code, message, retryable}` envelope, but every route that raises a FastAPI
244
+ * `HTTPException` — the whole of `rooms_routes.py`, and there is no custom
245
+ * handler to normalise them — serialises to a bare `{"detail": "Room not
246
+ * found."}` with no code at all. Under a code-only test, a real 404 from the
247
+ * room routes would be diagnosed as "your MNEMOVERSE_API_URL is wrong": a
248
+ * confident, checkable falsehood about the user's config.
249
+ *
250
+ * A message with no code is still the engine speaking. Silence — an unparseable
251
+ * body, or JSON carrying neither field — is what a proxy, a tunnel or a base URL
252
+ * pointing elsewhere produces.
253
+ */
254
+ function saidNothing(env) {
255
+ return env.code === undefined && env.message === undefined;
256
+ }
257
+ /**
258
+ * Did the ENGINE answer this 404 — or just the framework's router?
259
+ *
260
+ * Core registers no HTTPException handler, so an unmatched route is answered
261
+ * by Starlette's literal default `{"detail":"Not Found"}` (verified live
262
+ * against production) — a body with a message but no code, which
263
+ * `saidNothing` alone would mistake for an engine answer (Copilot + panel,
264
+ * #93). Every 404 the data plane actually sends is a MnemoError carrying a
265
+ * code. Match the router defaults case-sensitively so engine prose that
266
+ * merely contains "not found" cannot collide.
267
+ */
268
+ function engineSilentOn404(env) {
269
+ return (saidNothing(env) ||
270
+ (env.code === undefined &&
271
+ (env.message === "Not Found" || env.message === "Method Not Allowed")));
272
+ }
273
+ /**
274
+ * 404: three producers with three different honest answers (panel, #93).
275
+ *
276
+ * (1) POST /memory/rooms/join — the engine's "Invite code not found." No
277
+ * room address was involved and memory_list_rooms cannot help a
278
+ * non-member, so the room story would be a confident wrong cause.
279
+ * (2) An engine 404 carrying a code — every 404 the data plane sends is a
280
+ * MnemoError with one — is about something the request addressed,
281
+ * usually a room.
282
+ * (3) No code — the router default, a foreign API, a proxy, or silence: the
283
+ * ENGINE did not answer this, so point at the endpoint and the base URL,
284
+ * not at rooms.
285
+ */
286
+ function explain404(f, env) {
287
+ if (f.path === "/memory/rooms/join") {
288
+ return ("Mnemoverse: this invite code was not recognized (404). Most often it " +
289
+ "was copied with a typo or was never issued — have the user re-check " +
290
+ 'the exact code (it starts with "mnvr_"), and if it is right, ask ' +
291
+ "whoever sent it for a fresh one. memory_list_rooms will not help " +
292
+ "here: the user is not a member yet. Do not retry the same code.");
293
+ }
294
+ if (env.code === undefined) {
295
+ return (`Mnemoverse: the API answered 404 for ${f.method} ${f.path} without ` +
296
+ "the engine's error envelope — which is what a route the deployment " +
297
+ "does not serve looks like, not what a missing memory looks like. " +
298
+ "Either MNEMOVERSE_API_URL is aimed at something that is not the " +
299
+ "Mnemoverse API, or this server is newer than the deployment it is " +
300
+ "talking to. If the user's MCP client config sets MNEMOVERSE_API_URL, " +
301
+ "have them check it; if it sets none (the desktop extension exposes " +
302
+ "only the API key), the deployment likely needs updating. Do not retry.");
303
+ }
304
+ return ("Mnemoverse: what this call addressed does not exist for this key (404). " +
305
+ "The usual cause is a room address that is mistyped, or a room that was " +
306
+ "deleted — call memory_list_rooms for the addresses this key can actually " +
307
+ "reach. Note that a DOMAIN never causes this: a domain holding nothing " +
308
+ "simply reads as empty, so do not tell the user their domain is missing. " +
309
+ "Do not retry this call unchanged.");
310
+ }
311
+ /** 429: three causes, opposite advice. The envelope's `retryable` is the
312
+ * discriminator, because it is the only thing the engine states outright. */
313
+ function explain429(f, env) {
314
+ const secs = retryAfterSeconds(f.retryAfter);
315
+ const wait = secs === undefined ? "about a minute" : `${secs} seconds`;
316
+ if (env.retryable === true) {
317
+ return ("Mnemoverse: rate-limited (429). This is the per-minute request limit and " +
318
+ `it clears by itself. Wait ${wait}, then make AT MOST ONE more attempt — ` +
319
+ "do not retry in a loop and do not fan out into more calls, which is what " +
320
+ "turns a one-minute limit into a sustained one. If the retry also fails, " +
321
+ "stop and tell the user this key is hitting its rate limit.");
322
+ }
323
+ if (env.retryable === false) {
324
+ return ("Mnemoverse: refused for quota, not for speed (429). Waiting will NOT " +
325
+ "clear this one — the account is at its daily limit, at its stored-memory " +
326
+ "limit, or its subscription is blocking writes. Do not retry. Tell the " +
327
+ `user what the detail below says and point them at ${USAGE_URL}.`);
328
+ }
329
+ return ("Mnemoverse: refused as too many requests (429), and the body does not say " +
330
+ "whether waiting helps. Do not retry in a loop. Wait a moment, make at most " +
331
+ "one more attempt, and if that fails tell the user rather than continuing — " +
332
+ `if this is a quota rather than a rate, ${USAGE_URL} is where they resolve it.`);
333
+ }
334
+ /**
335
+ * The agent-facing explanation for one failed call, with the raw body kept
336
+ * after it.
337
+ *
338
+ * Total by construction: every status reaches a sentence, and the fallback says
339
+ * that it has no specific guidance instead of inventing some.
340
+ */
341
+ export function explainApiFailure(f) {
342
+ const env = parseErrorEnvelope(f.body);
343
+ let guidance;
344
+ if (f.status === 401) {
345
+ guidance = explain401(env);
346
+ }
347
+ else if (f.status === 403) {
348
+ guidance = explain403(env);
349
+ }
350
+ else if (f.status === 404) {
351
+ guidance = explain404(f, env);
352
+ }
353
+ else if (f.status === 429) {
354
+ guidance = explain429(f, env);
355
+ }
356
+ else if (f.status === 400 || f.status === 422) {
357
+ guidance =
358
+ "Mnemoverse: the engine rejected the CONTENTS of this request " +
359
+ `(${f.status}). This is about the arguments you sent — not the API key, ` +
360
+ "not the network, and not the user's setup. Read the detail below, fix " +
361
+ "the argument it names, and do not resend the same body.";
362
+ }
363
+ else if (f.status === 409) {
364
+ guidance = explain409(f);
365
+ }
366
+ else if (f.status >= 500) {
367
+ guidance =
368
+ `Mnemoverse: the memory service failed (${f.status}). This is OUR side, ` +
369
+ "not the user's — their API key, their config and their network are all " +
370
+ "fine, so do not send them to check any of those. One retry after a few " +
371
+ "seconds is reasonable. If it fails again, say plainly that Mnemoverse is " +
372
+ "having a problem and continue without memory rather than retrying.";
373
+ }
374
+ else {
375
+ guidance =
376
+ `Mnemoverse: the API returned HTTP ${f.status}, and this client has no ` +
377
+ "specific guidance for that status. Do not invent a cause for the user — " +
378
+ "quote the detail below. One retry is acceptable; a loop is not.";
379
+ }
380
+ return `${guidance}\n\n${rawDetail(f)}`;
381
+ }
382
+ /**
383
+ * A server-controlled string, made safe to quote inside model-facing text.
384
+ *
385
+ * The body is server-controlled — or, on the misconfigured-URL and proxy paths
386
+ * this module itself names, controlled by whoever answered instead. Spliced raw
387
+ * into model-facing text, a body with newlines could open its own paragraph and
388
+ * speak in this module's instruction voice (panel, #93). Strip control,
389
+ * format/bidi and line/paragraph separators so the quoted body stays one inert
390
+ * line; the guidance above it is the only voice here.
391
+ *
392
+ * Shared with {@link explainUnreadableBody}, whose preview is quoted from
393
+ * exactly the same kind of source — a body written by whoever answered.
394
+ */
395
+ function inertOneLine(s) {
396
+ return s.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, " ");
397
+ }
398
+ /** The debugging half: what the wire actually said, still carrying the literal
399
+ * `Mnemoverse API error <status>` that predates this module. */
400
+ function rawDetail(f) {
401
+ const body = f.body.length > MAX_BODY_CHARS
402
+ ? `${f.body.slice(0, MAX_BODY_CHARS)}… [body truncated at ${MAX_BODY_CHARS} chars]`
403
+ : f.body;
404
+ return `Raw detail — Mnemoverse API error ${f.status} on ${f.method} ${f.path}: ${inertOneLine(body)}`;
405
+ }
406
+ /**
407
+ * Was this transport failure a REDIRECT this client refused to follow?
408
+ *
409
+ * `redirect: "error"` (src/index.ts, apiFetch) makes undici reject with
410
+ * `TypeError: fetch failed` whose `cause` is `Error: unexpected redirect` —
411
+ * verified by executing the case against a real local 302
412
+ * (test/redirect-refusal.test.ts, which uses a real server precisely because a
413
+ * stubbed fetch has no redirect handling to exercise). The literal string is
414
+ * `makeNetworkError('unexpected redirect')` and is identical in undici 5
415
+ * (Node 18), 6 (Node 20 / 22) and 7 (Node 24) — read in all three, because the
416
+ * CI matrix and this package's `engines` span them.
417
+ *
418
+ * WITHOUT THIS BRANCH the failure is indistinguishable from a dead host: same
419
+ * `TypeError: fetch failed`, and the message below would tell the user to debug
420
+ * a "connectivity or DNS problem" on a network that is working perfectly, while
421
+ * the actual cause — a base URL aimed at something that bounces — sat in their
422
+ * config. That is the confident wrong cause this whole module exists against.
423
+ *
424
+ * The cause chain is WALKED rather than read at one depth, since the nesting is
425
+ * undici's to change; the match is the exact sentinel rather than the word
426
+ * "redirect", because a DNS failure against a host whose NAME contains
427
+ * "redirect" would otherwise be diagnosed as one. If a future runtime renames
428
+ * the sentinel this stops firing and the honest generic sentence takes over —
429
+ * a degradation, not a lie — and the real-server test goes red, which is where
430
+ * the rename gets noticed.
431
+ */
432
+ function refusedRedirect(cause) {
433
+ let e = cause;
434
+ for (let depth = 0; depth < 5; depth++) {
435
+ if (!(e instanceof Error))
436
+ return false;
437
+ if (e.message.toLowerCase().includes("unexpected redirect"))
438
+ return true;
439
+ e = e.cause;
440
+ }
441
+ return false;
442
+ }
443
+ /**
444
+ * The request never got an answer at all: DNS, connectivity, a host that does
445
+ * not listen, or this client's own probe deadline firing.
446
+ *
447
+ * Included even though the brief was about HTTP statuses, because it is the
448
+ * OTHER half of the same defect and the two are easy to confuse. The 401
449
+ * message above tells an agent not to blame the network; this is the case where
450
+ * the network genuinely IS the answer, and `TypeError: fetch failed` — which is
451
+ * all a model saw before — is no more actionable than the raw 401 body was.
452
+ *
453
+ * A timeout is named separately because the advice differs in one word: an
454
+ * unreachable host is unlikely to become reachable in three seconds, whereas a
455
+ * request that ran out of time may well succeed on a second try.
456
+ *
457
+ * NARROWED to `fetch()` itself rejecting. Reading the BODY of a response that
458
+ * did arrive used to land here too, so a 200 carrying a sign-in page printed
459
+ * "no HTTP response came back" — see {@link explainUnreadableBody}, which owns
460
+ * that case now. Every sentence below asserts that nothing answered, so it may
461
+ * only be reached when nothing did.
462
+ */
463
+ export function explainNetworkFailure(method, path, cause) {
464
+ const name = cause instanceof Error ? cause.name : "";
465
+ const timedOut = name === "TimeoutError" || name === "AbortError";
466
+ const detail = cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
467
+ if (refusedRedirect(cause)) {
468
+ return (`Mnemoverse: ${method} ${path} was answered with a REDIRECT, and this ` +
469
+ "client refused to follow it — so the API key was never sent to whatever " +
470
+ "the redirect pointed at. That refusal is the whole point: following a " +
471
+ "redirect re-sends the request headers to the new host, which hands a " +
472
+ "live key to whoever answered. This API serves one stable base path and " +
473
+ "never redirects legitimately, so this means MNEMOVERSE_API_URL is aimed " +
474
+ "at something else — a proxy, a tunnel, a captive portal, or an address " +
475
+ "that has been tampered with. It is NOT a rejected key and NOT a broken " +
476
+ "network: the request arrived somewhere and was answered. Tell the user " +
477
+ "to check MNEMOVERSE_API_URL and point it straight at the API (the " +
478
+ `default is ${DEFAULT_API_URL}). Do not retry: the same address will ` +
479
+ `redirect again.\n\n${rawTransportDetail(method, path, detail)}`);
480
+ }
481
+ const head = timedOut
482
+ ? `Mnemoverse: the memory service did not answer ${method} ${path} in time.`
483
+ : `Mnemoverse: the memory service could not be reached at all — ${method} ` +
484
+ `${path} failed before any HTTP response came back.`;
485
+ const cause_ = timedOut
486
+ ? "The service may just be slow right now."
487
+ : "That is a connectivity or DNS problem, or MNEMOVERSE_API_URL pointing at " +
488
+ "a host that does not answer.";
489
+ return (`${head} ${cause_} This is NOT a rejected API key and NOT a quota — no ` +
490
+ "reply arrived to say anything about either, so do not send the user to " +
491
+ "check their key. One retry is reasonable. If that also fails, tell the " +
492
+ "user memory is unreachable and carry on without it rather than retrying.\n\n" +
493
+ rawTransportDetail(method, path, detail));
494
+ }
495
+ /** The debugging half of a transport failure, in one place so the redirect
496
+ * branch and the generic one cannot drift into two spellings of it. */
497
+ function rawTransportDetail(method, path, detail) {
498
+ return `Raw detail — request to ${method} ${path} failed: ${detail}`;
499
+ }
500
+ /** How much of an unreadable body is worth quoting. A sign-in page, an SPA
501
+ * shell or a proxy notice announces itself in its first line; the rest is
502
+ * markup, and an error message is not a place to spend a model's context. */
503
+ const MAX_PREVIEW_CHARS = 200;
504
+ /**
505
+ * A reply ARRIVED and could not be read — which is not a dead network.
506
+ *
507
+ * WHY THIS IS SEPARATE FROM {@link explainNetworkFailure}. Both failures used
508
+ * to throw the same NetworkError, so `JSON.parse` choking on a 200 printed
509
+ * "the memory service could not be reached at all — POST /memory/read failed
510
+ * before any HTTP response came back… That is a connectivity or DNS problem".
511
+ * Against a captive portal, a MITM proxy, an SPA that serves its shell with a
512
+ * 200, or a body that stops mid-stream, every clause of that is false: a reply
513
+ * came, with a status, and the Raw detail underneath it quoted a SyntaxError
514
+ * out of the body it had just called nonexistent.
515
+ *
516
+ * The cost is the same one this module exists to remove — a confident wrong
517
+ * cause. "Connectivity or DNS" sends the user to debug working wifi while a
518
+ * portal or a mis-set MNEMOVERSE_API_URL answers every request with a page.
519
+ *
520
+ * WHAT THIS MESSAGE MAY CLAIM. Only what the status proves: something answered,
521
+ * and its answer is not this API's JSON. It does NOT name who answered — this
522
+ * client cannot tell the engine from a gateway in front of it — and it does NOT
523
+ * say whether the operation ran, because a body it cannot read is no evidence
524
+ * either way. That last clause matters most for a write.
525
+ */
526
+ export function explainUnreadableBody(f) {
527
+ // TWO ARMS, because the two failures have different causes and the wrong one
528
+ // is a wrong instruction. A body that PARSED WRONG is a foreign answer — a
529
+ // portal, a proxy, a base URL aimed elsewhere. A body that stopped ARRIVING
530
+ // is a dropped connection, where "check MNEMOVERSE_API_URL" would be the
531
+ // same kind of confident wrong cause this module removes everywhere else.
532
+ const body = typeof f.bodyPreview === "string"
533
+ ? `the body is not JSON this API produces — this client could not read ` +
534
+ `the result. A reply DID arrive, so this is neither a dead network ` +
535
+ `nor a rejected key: nothing here failed to connect, and nothing here ` +
536
+ `refused anything. Do not send the user to debug their connection, ` +
537
+ `and do not tell them their key is the problem. A 2xx in a foreign ` +
538
+ `shape comes from something in FRONT of the API — a captive portal or ` +
539
+ `sign-in page, a proxy or gateway, or MNEMOVERSE_API_URL aimed at ` +
540
+ `something that is not the Mnemoverse API. One retry is reasonable; ` +
541
+ `if it repeats, quote the detail below and have the user check ` +
542
+ `MNEMOVERSE_API_URL and whatever sits between them and the API.`
543
+ : `the body could not be read to the end — it stopped part-way, after ` +
544
+ `that status had already arrived. That is a dropped connection ` +
545
+ `or a deadline firing mid-body; it is NOT a refusal and it says ` +
546
+ `nothing about the user's key. One retry is reasonable; if it ` +
547
+ `repeats, tell the user the reply is arriving incomplete and quote ` +
548
+ `the detail below, status included.`;
549
+ return (`Mnemoverse: something answered HTTP ${f.status} for ${f.method} ` +
550
+ `${f.path}, but ${body} Whether the operation itself ran is unknown ` +
551
+ `either way — if this was a write, treat it as neither saved nor ` +
552
+ `refused.\n\n${rawUnreadableDetail(f)}`);
553
+ }
554
+ /** The debugging half for an unreadable body: what stopped the read, and the
555
+ * first bytes of what arrived — through the same inert filter as
556
+ * {@link rawDetail}, because the preview has exactly the same provenance. */
557
+ function rawUnreadableDetail(f) {
558
+ const detail = f.cause instanceof Error ? `${f.cause.name}: ${f.cause.message}` : String(f.cause);
559
+ const head = `Raw detail — HTTP ${f.status} on ${f.method} ${f.path}, body this client ` +
560
+ `could not read: ${inertOneLine(detail)}`;
561
+ if (typeof f.bodyPreview !== "string" || f.bodyPreview === "")
562
+ return head;
563
+ const note = f.bodyPreview.length > MAX_PREVIEW_CHARS
564
+ ? ` … [preview truncated at ${MAX_PREVIEW_CHARS} chars]`
565
+ : "";
566
+ return `${head} First bytes: ${inertOneLine(f.bodyPreview.slice(0, MAX_PREVIEW_CHARS))}${note}`;
567
+ }
568
+ /**
569
+ * {@link explainUnreadableBody} as an error, so a caller can tell "a reply
570
+ * arrived and was unreadable" from "no reply arrived" by TYPE rather than by
571
+ * matching a sentence — the same reason {@link ApiError} carries fields.
572
+ */
573
+ export class UnreadableBodyError extends Error {
574
+ status;
575
+ method;
576
+ path;
577
+ constructor(f) {
578
+ super(explainUnreadableBody(f), { cause: f.cause });
579
+ this.name = "UnreadableBodyError";
580
+ this.status = f.status;
581
+ this.method = f.method;
582
+ this.path = f.path;
583
+ }
584
+ }
585
+ /**
586
+ * 409: name the conflict this tool actually produced (panel, #93). The two
587
+ * real producers on this server are the join tool (used/expired/revoked
588
+ * invite) and memory_create_room (core: "A room with this name already
589
+ * exists.", 409). The old single sentence gave the invite advice to a
590
+ * duplicate-name conflict, misdirecting the agent to a nonexistent inviter.
591
+ */
592
+ function explain409(f) {
593
+ if (f.path === "/memory/rooms/join") {
594
+ return ("Mnemoverse: this invite code cannot be used (409) — it has already " +
595
+ "been used, has expired, or was revoked. Ask whoever invited the user " +
596
+ "for a fresh one. Retrying the same code will conflict again.");
597
+ }
598
+ if (f.path === "/memory/rooms" && f.method === "POST") {
599
+ return ("Mnemoverse: a room with this name already exists for this account " +
600
+ "(409). Pick a different name, or reuse the existing room — " +
601
+ "memory_list_rooms shows its address. Retrying the same name will " +
602
+ "conflict again.");
603
+ }
604
+ return ("Mnemoverse: this request conflicts with the current state (409). The " +
605
+ "engine's own explanation is in the detail below — quote it to the " +
606
+ "user. Retrying the same request will conflict again.");
607
+ }
608
+ /** {@link explainNetworkFailure} as an error, so `instanceof` can tell a
609
+ * transport failure from an HTTP one without reading either message. */
610
+ export class NetworkError extends Error {
611
+ method;
612
+ path;
613
+ constructor(method, path, cause) {
614
+ super(explainNetworkFailure(method, path, cause), { cause });
615
+ this.name = "NetworkError";
616
+ this.method = method;
617
+ this.path = path;
618
+ }
619
+ }
620
+ /**
621
+ * A failed API call, as an ERROR OBJECT rather than a parsed string.
622
+ *
623
+ * The status and the body are fields because a caller that needs to branch on
624
+ * them must not do it by matching the message. `memory_list_recent` used to
625
+ * decide between "the endpoint is not deployed" and "this room does not exist"
626
+ * with `message.startsWith("Mnemoverse API error 404:")`, which coupled a
627
+ * behavioural branch to the exact prefix of a user-facing sentence — so
628
+ * improving the sentence, which is this change, would have silently flipped
629
+ * that branch. Structured fields make the wording free to change.
630
+ */
631
+ export class ApiError extends Error {
632
+ status;
633
+ body;
634
+ method;
635
+ path;
636
+ /** The engine's envelope, already parsed — so a caller never re-parses. */
637
+ envelope;
638
+ constructor(f) {
639
+ super(explainApiFailure(f));
640
+ this.name = "ApiError";
641
+ this.status = f.status;
642
+ this.body = f.body;
643
+ this.method = f.method;
644
+ this.path = f.path;
645
+ this.envelope = parseErrorEnvelope(f.body);
646
+ }
647
+ /**
648
+ * A 404 the ENGINE did not answer: silence, or the router's literal
649
+ * defaults. This is what a path the deployment does not serve looks like
650
+ * — the first version of this predicate tested silence alone, mistook the
651
+ * real framework body `{"detail":"Not Found"}` for an engine answer, and
652
+ * un-fired the feed's degrade branch for the exact rollout case it exists
653
+ * for (panel, #93).
654
+ *
655
+ * NAMED FOR WHAT IT TESTS, not for what it implies: a gateway, a proxy or a
656
+ * wrong MNEMOVERSE_API_URL can produce the same shapes and is
657
+ * indistinguishable from here. Known, accepted edge: a foreign API whose
658
+ * 404 nests its error under a key this parser does not read
659
+ * (`{"error":{…}}`) also reads as bare, so the feed degrades to its
660
+ * not-supported notice instead of surfacing the foreign body — bounded
661
+ * harm, since against a wrong base URL the very next call fails with the
662
+ * instructive no-envelope wording.
663
+ */
664
+ get isBare404() {
665
+ return this.status === 404 && engineSilentOn404(this.envelope);
666
+ }
667
+ }
668
+ //# sourceMappingURL=errors.js.map