@mysten-incubation/memwal 0.1.8 → 0.1.9-rc.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.
Files changed (50) hide show
  1. package/README.md +5 -1
  2. package/dist/account.d.ts.map +1 -1
  3. package/dist/account.js +2 -17
  4. package/dist/account.js.map +1 -1
  5. package/dist/ai/middleware.d.ts +5 -0
  6. package/dist/ai/middleware.d.ts.map +1 -1
  7. package/dist/ai/middleware.js +87 -9
  8. package/dist/ai/middleware.js.map +1 -1
  9. package/dist/index.d.ts +4 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +4 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/manual-entry.d.ts +2 -2
  14. package/dist/manual-entry.d.ts.map +1 -1
  15. package/dist/manual-entry.js +1 -1
  16. package/dist/manual.d.ts +26 -11
  17. package/dist/manual.d.ts.map +1 -1
  18. package/dist/manual.js +180 -127
  19. package/dist/manual.js.map +1 -1
  20. package/dist/memwal.d.ts +88 -32
  21. package/dist/memwal.d.ts.map +1 -1
  22. package/dist/memwal.js +563 -187
  23. package/dist/memwal.js.map +1 -1
  24. package/dist/mock.d.ts +27 -11
  25. package/dist/mock.d.ts.map +1 -1
  26. package/dist/mock.js +191 -47
  27. package/dist/mock.js.map +1 -1
  28. package/dist/polling-delay.d.ts +3 -0
  29. package/dist/polling-delay.d.ts.map +1 -0
  30. package/dist/polling-delay.js +13 -0
  31. package/dist/polling-delay.js.map +1 -0
  32. package/dist/recall-args.d.ts +12 -0
  33. package/dist/recall-args.d.ts.map +1 -0
  34. package/dist/recall-args.js +44 -0
  35. package/dist/recall-args.js.map +1 -0
  36. package/dist/sui-client.d.ts +10 -0
  37. package/dist/sui-client.d.ts.map +1 -0
  38. package/dist/sui-client.js +29 -0
  39. package/dist/sui-client.js.map +1 -0
  40. package/dist/tokens.d.ts +19 -4
  41. package/dist/tokens.d.ts.map +1 -1
  42. package/dist/tokens.js +51 -13
  43. package/dist/tokens.js.map +1 -1
  44. package/dist/types.d.ts +119 -9
  45. package/dist/types.d.ts.map +1 -1
  46. package/dist/utils.d.ts +72 -0
  47. package/dist/utils.d.ts.map +1 -1
  48. package/dist/utils.js +188 -2
  49. package/dist/utils.js.map +1 -1
  50. package/package.json +9 -5
package/dist/memwal.js CHANGED
@@ -27,9 +27,11 @@
27
27
  * console.log(result.results[0].text) // "I'm allergic to peanuts"
28
28
  * ```
29
29
  */
30
- import { sha256hex, hexToBytes, bytesToHex, normalizePrivateKey, normalizeServerUrl, sanitizeServerError, redactInternalUrls, clockDriftErrorFromResponse, scoringWeightsToWire, } from "./utils.js";
30
+ import { sha256hex, hexToBytes, bytesToHex, normalizePrivateKey, normalizeServerUrl, assertNonBlankText, sanitizeServerError, redactInternalUrls, clockDriftErrorFromResponse, scoringWeightsToWire, derivedIdempotencyKey, derivedBulkIdempotencyKey, DEFAULT_PREFLIGHT_TIMEOUT_MS, DEFAULT_RECALL_TIMEOUT_MS, RESTORE_REQUEST_TIMEOUT_MS, } from "./utils.js";
31
31
  import { assertCompatibleRelayer, compatibilityErrorFromStatus, } from "./compatibility.js";
32
- import { applyTokenBudget, estimateTokens } from "./tokens.js";
32
+ import { applyTokenBudget, estimateTokens, validateMaxTokens } from "./tokens.js";
33
+ import { pollingDelayMs } from "./polling-delay.js";
34
+ import { resolveRecallCall } from "./recall-args.js";
33
35
  // ============================================================
34
36
  // Ed25519 Signing (lazy-loaded)
35
37
  // ============================================================
@@ -45,50 +47,67 @@ const SEAL_SESSION_TTL_MIN = 5;
45
47
  // the client thinks the session is valid but a just-received request hits
46
48
  // a key server that sees it as expired.
47
49
  const SEAL_SESSION_SAFETY_MARGIN_MS = 30_000;
50
+ /** Path for one remember-job read, or undefined when `jobId` is not one safe segment.
51
+ *
52
+ * `fetch` rewrites the path after the request is signed. `.` becomes
53
+ * `/api/remember/`, `..` and `%2e%2e` become `/api/`, and a backslash becomes
54
+ * a slash. An allowlist keeps those from leaving the client. A UUID is
55
+ * unchanged. (#1087, #1216)
56
+ */
57
+ function rememberStatusPath(jobId) {
58
+ if (typeof jobId !== "string" || !/^[A-Za-z0-9_-]+$/.test(jobId)) {
59
+ return undefined;
60
+ }
61
+ return `/api/remember/${jobId}`;
62
+ }
48
63
  function sleep(ms) {
49
64
  return new Promise((resolve) => setTimeout(resolve, ms));
50
65
  }
51
- function pollingDelayMs(baseMs, attempt) {
52
- const base = Math.max(100, baseMs);
53
- const capped = Math.min(10_000, base * 1.5 ** Math.min(attempt, 6));
54
- const jitter = 0.75 + Math.random() * 0.5;
55
- return Math.floor(capped * jitter);
56
- }
57
- /** Window over which the same (namespace, text) resolves to one key.
58
- *
59
- * `pendingRememberKeys` only dedupes retries that reuse one client instance,
60
- * and callers such as the MCP sidecar build a fresh client per session — so a
61
- * random key let a reconnect replay mint a second paid blob. The bucket bounds
62
- * the collapse: `remember_jobs` rows are never pruned, so an unbucketed key
63
- * would dedupe against a job from any point in history. */
64
- const IDEMPOTENCY_BUCKET_MS = 30 * 60 * 1000;
65
- async function derivedIdempotencyKey(requestIdentity) {
66
- const bucket = Math.floor(Date.now() / IDEMPOTENCY_BUCKET_MS);
67
- return `r1-${await sha256hex(`${bucket}\0${requestIdentity}`)}`;
68
- }
69
66
  /** Deadline for a request that names no other.
70
67
  *
71
68
  * `fetch` imposes none, and a poll loop checks its budget only between polls —
72
69
  * so one stalled read ran past `timeoutMs` entirely. 30s mirrors the relayer's
73
70
  * own outbound client. */
74
71
  const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
75
- /** `POST /api/restore` bounds itself at 55s server-side and answers with an
76
- * error rather than going quiet, so the client must outlast that or it would
77
- * abandon a response already on its way. */
78
- const RESTORE_REQUEST_TIMEOUT_MS = 60_000;
72
+ /** The one confirming read a bulk wait makes after its budget is spent. It
73
+ * runs past the caller's deadline by design, so it gets a short bound of its
74
+ * own rather than the 30s default a stalled socket would hold it for. */
75
+ const CONFIRM_READ_TIMEOUT_MS = 5_000;
76
+ /** Matches the relayer's `MAX_BULK_ITEMS`. Reject before a signed request. */
77
+ const MAX_BULK_ITEMS = 20;
78
+ /**
79
+ * `remember(text, { idempotencyKey })` is the natural call when the namespace
80
+ * stays at the client default. A plain object in the namespace slot is those
81
+ * options, not a namespace name. (#1142)
82
+ */
83
+ function splitRememberArgs(namespaceOrOptions, options) {
84
+ // The third argument is the dedicated options bag. When the namespace
85
+ // slot is also an object, keep both and let the bag win on a clash.
86
+ // `rememberAndWait(text, { timeoutMs }, { idempotencyKey })` is typed
87
+ // and used to drop the key, so a retry minted a second blob. (#1142)
88
+ if (typeof namespaceOrOptions === "object" && namespaceOrOptions !== null) {
89
+ return { namespace: undefined, options: { ...namespaceOrOptions, ...options } };
90
+ }
91
+ return { namespace: namespaceOrOptions, options: options ?? {} };
92
+ }
93
+ function requireRememberText(text) {
94
+ if (typeof text !== "string") {
95
+ throw new TypeError(`remember() expects text as a string, received ${typeof text}. ` +
96
+ `Did you mean remember(text, namespace)? Unlike recall(), remember* does not take an options object.`);
97
+ }
98
+ }
99
+ function destroyedClientError() {
100
+ return new Error("Walrus Memory client was destroyed; its keys are zeroed. Create a new one.");
101
+ }
79
102
  /** `POST /api/analyze` runs the extractor LLM inline before it accepts, so it
80
103
  * is the one write that legitimately outruns the default. */
81
104
  const ANALYZE_REQUEST_TIMEOUT_MS = 60_000;
82
- /** `POST /api/recall` has carried its own 15s deadline since before the rest
83
- * had any; keeping it named makes that a decision rather than an accident. */
84
- const RECALL_REQUEST_TIMEOUT_MS = 15_000;
85
- /** What `recall()` tells the relayer it will wait, so the 504 naming the stuck
86
- * stage arrives before the abort above rather than after it. A second under
87
- * that abort because the two clocks start at different moments: this timer
88
- * starts before `fetch`, the relayer's when the request lands, and the margin
89
- * the relayer keeps for its reply cannot also cover DNS, TCP and TLS. Derived
90
- * from the timeout so the two can never drift apart. */
91
- const RECALL_DEADLINE_MS = RECALL_REQUEST_TIMEOUT_MS - 1_000;
105
+ /** How far under the client's own abort `recall()` asks the relayer to stop,
106
+ * so the 504 naming the stuck stage arrives before the abort rather than
107
+ * after it. A second, because the two clocks start at different moments: this
108
+ * timer starts before `fetch`, the relayer's when the request lands, and the
109
+ * margin the relayer keeps for its reply cannot also cover DNS, TCP and TLS. */
110
+ const RECALL_DEADLINE_MARGIN_MS = 1_000;
92
111
  /**
93
112
  * Abort signal that fires after `ms`, or when `caller` aborts — whichever is
94
113
  * first. Built by hand rather than with `AbortSignal.any`, which lands too
@@ -131,17 +150,53 @@ function deadlineSignal(ms, caller) {
131
150
  * `status: 504` is load-bearing, not decoration: `isTransientPollingStatus`
132
151
  * treats it as retryable, so one stalled poll inside a wait loop is abandoned
133
152
  * and retried against the remaining budget instead of failing the whole wait.
153
+ *
154
+ * `phase` names the round-trip that actually stalled — `"preflight GET
155
+ * /version"`, `"POST /api/recall"` — so WALM-598's diagnostic question ("which
156
+ * step ate the budget?") is answerable from the error alone. The name stays
157
+ * `MemWalRequestTimeout`: that is the shipped contract callers and
158
+ * `isTransientPollingStatus` already key off (WALM-648).
134
159
  */
135
- function requestTimeoutError(method, path, ms) {
136
- const err = new Error(`Walrus Memory request timed out after ${ms}ms (${method} ${path}). The relayer ` +
160
+ function requestTimeoutError(method, path, ms, phase) {
161
+ const stage = phase ?? `${method} ${path}`;
162
+ const err = new Error(`Walrus Memory request timed out after ${ms}ms during ${stage}. The relayer ` +
137
163
  `accepted the connection but did not answer in time.`);
138
164
  err.name = "MemWalRequestTimeout";
139
165
  err.status = 504;
166
+ err.phase = stage;
167
+ err.timeoutMs = ms;
140
168
  return err;
141
169
  }
170
+ /**
171
+ * The 504 a remember wait raises when its budget runs out.
172
+ *
173
+ * Under upload congestion the relayer keeps a job `running` for tens of
174
+ * minutes, far past a 60s wait, and says so in the job's `error`. Carrying the
175
+ * last status the relayer reported is what lets a caller tell "still retrying,
176
+ * wait on the same job" from "we never got an answer" (GH #966). The wait
177
+ * only times out on a job that is still pending/running/uploaded (a `failed`
178
+ * job throws), so the advice is always to keep waiting on the job id.
179
+ */
180
+ function rememberJobTimeoutError(jobId, timeoutMs, lastSeen, lastRefusal, sawRateLimit) {
181
+ const serverError = lastSeen?.error ? redactInternalUrls(lastSeen.error) : undefined;
182
+ // "no status read got through (last poll: HTTP 429)" already names the rate limit.
183
+ const rateLimited = sawRateLimit && (lastSeen || lastRefusal !== 429) ? "; wait hit a rate limit (429)" : "";
184
+ const detail = lastSeen
185
+ ? `last status: ${lastSeen.status}${serverError ? ` (${serverError})` : ""}. ` +
186
+ `The job is still in progress: call waitForRememberJob("${jobId}") to keep waiting on it. ` +
187
+ `Sending the text again under a new idempotency key stores it twice; a key you passed ` +
188
+ `as idempotencyKey is not remembered by the client, so pass it again on any retry.`
189
+ : `no status read got through (last poll: HTTP ${lastRefusal ?? 0}), so the job's state is unknown.`;
190
+ const err = new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})${rateLimited}; ${detail}`);
191
+ err.name = "MemWalRememberJobTimeout";
192
+ return Object.assign(err, { status: 504, jobId, lastStatus: lastSeen?.status, serverError });
193
+ }
142
194
  function isTransientPollingStatus(status) {
143
195
  return status === 0 || status === 429 || status >= 500;
144
196
  }
197
+ function jsonBodyError(status, message) {
198
+ return Object.assign(new Error(message), { status });
199
+ }
145
200
  /**
146
201
  * How long a transient polling rejection asked us to wait, in ms.
147
202
  *
@@ -164,6 +219,24 @@ function retryAfterDelayMs(err, deadline) {
164
219
  return 0;
165
220
  return Math.max(0, Math.min(seconds * 1000, deadline - Date.now()));
166
221
  }
222
+ /**
223
+ * Thrown when a bulk wait could not read a single status, the confirming read
224
+ * included. The status endpoint counts against the same delegate-key budget
225
+ * as writes, so a batch sent near the limit can have every poll refused. The
226
+ * old result then read as "still uploading" even when nothing had landed
227
+ * (GH #967). A refusal says nothing about the jobs, so do not report it as
228
+ * progress.
229
+ */
230
+ function bulkRateLimitedError(err, jobIds) {
231
+ const retryAfterSeconds = err.retryAfterSeconds
232
+ ?? retryAfterSecondsFromBody(err.cause);
233
+ const wait = retryAfterSeconds ? ` after ~${Math.ceil(retryAfterSeconds)}s` : "";
234
+ const e = new Error(`Walrus Memory rate-limited every status read for this batch, so none of its ${jobIds.length} writes ` +
235
+ `could be confirmed. Do not treat them as stored: check them with getRememberBulkStatus(jobIds)${wait}. ` +
236
+ `Status reads count against the same delegate-key budget as writes.`);
237
+ e.name = "MemWalRateLimited";
238
+ return Object.assign(e, { status: 429, jobIds, retryAfterSeconds });
239
+ }
167
240
  /**
168
241
  * The relayer states the backoff in the 429 body as well as in `Retry-After`.
169
242
  * A proxy that strips the header must not cost us the hint.
@@ -232,6 +305,13 @@ export class MemWal {
232
305
  accountId;
233
306
  /** Deadline applied to any request that does not name its own. */
234
307
  requestTimeoutMs;
308
+ /**
309
+ * Recall's abort budget, and the independent per-round-trip budget for the
310
+ * unauthenticated preflights that precede it. Separate so a slow
311
+ * `/version`, `/health` or `/config` is never charged against recall.
312
+ */
313
+ recallTimeoutMs;
314
+ preflightTimeoutMs;
235
315
  // ENG-1697 state — all internal, never surfaced to user code.
236
316
  // The public API (`MemWal.create({ key, accountId })`) is unchanged.
237
317
  sessionCache = null;
@@ -257,11 +337,23 @@ export class MemWal {
257
337
  typeof config.key === "string"
258
338
  ? hexToBytes(normalizePrivateKey(config.key))
259
339
  : config.key;
340
+ if (!(this.privateKey instanceof Uint8Array) || this.privateKey.length !== 32) {
341
+ const got = this.privateKey instanceof Uint8Array
342
+ ? String(this.privateKey.length)
343
+ : typeof this.privateKey;
344
+ throw new Error(`Ed25519 seed must be exactly 32 bytes, got ${got}`);
345
+ }
346
+ if (typeof config.accountId !== "string" || config.accountId.trim().length === 0) {
347
+ throw new TypeError(`MemWal.create: "accountId" is required (Walrus Memory object ID, e.g. 0x...); got ${config.accountId}`);
348
+ }
260
349
  this.accountId = config.accountId;
261
350
  // LOW-22: default to HTTPS for production usage; normalizeServerUrl
262
351
  // warns (does not throw) if a user passes plain http:// for a
263
352
  // non-localhost host.
264
353
  this.serverUrl = normalizeServerUrl(config.serverUrl ?? "https://relayer.memory.walrus.xyz");
354
+ if (config.namespace !== undefined && !config.namespace) {
355
+ throw new Error("namespace cannot be empty");
356
+ }
265
357
  this.namespace = config.namespace ?? "default";
266
358
  // A non-positive or non-finite override would disable the backstop
267
359
  // entirely, which is the bug this exists to prevent.
@@ -269,6 +361,8 @@ export class MemWal {
269
361
  Number.isFinite(config.requestTimeoutMs) && config.requestTimeoutMs > 0
270
362
  ? config.requestTimeoutMs
271
363
  : DEFAULT_REQUEST_TIMEOUT_MS;
364
+ this.recallTimeoutMs = config.recallTimeoutMs ?? DEFAULT_RECALL_TIMEOUT_MS;
365
+ this.preflightTimeoutMs = config.preflightTimeoutMs ?? DEFAULT_PREFLIGHT_TIMEOUT_MS;
272
366
  }
273
367
  /**
274
368
  * Create a new Walrus Memory client instance.
@@ -305,11 +399,14 @@ export class MemWal {
305
399
  /**
306
400
  * Submit a remember request and return as soon as the server accepts the job.
307
401
  */
308
- async rememberAsync(text, namespace, options = {}) {
309
- const resolvedNamespace = namespace ?? this.namespace;
402
+ async rememberAsync(text, namespaceOrOptions, options) {
403
+ requireRememberText(text);
404
+ assertNonBlankText(text);
405
+ const split = splitRememberArgs(namespaceOrOptions, options);
406
+ const resolvedNamespace = split.namespace ?? this.namespace;
310
407
  const requestIdentity = `${resolvedNamespace}\0${text}`;
311
- const generatedKey = options.idempotencyKey === undefined;
312
- const idempotencyKey = options.idempotencyKey
408
+ const generatedKey = split.options.idempotencyKey === undefined;
409
+ const idempotencyKey = split.options.idempotencyKey
313
410
  ?? this.pendingRememberKeys.get(requestIdentity)
314
411
  ?? (await derivedIdempotencyKey(requestIdentity));
315
412
  if (generatedKey)
@@ -329,7 +426,17 @@ export class MemWal {
329
426
  * resolves at the terminal state and hides progress.
330
427
  */
331
428
  async getRememberStatus(jobId) {
332
- const status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404]);
429
+ const path = rememberStatusPath(jobId);
430
+ if (path === undefined) {
431
+ return {
432
+ job_id: jobId,
433
+ status: "not_found",
434
+ error: `Job ${jobId} not found`,
435
+ };
436
+ }
437
+ const status = await this.signedRequest("GET", path, {}, [200, 404],
438
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
439
+ { includeDelegateKey: false });
333
440
  if (!("status" in status)) {
334
441
  return {
335
442
  job_id: jobId,
@@ -343,18 +450,34 @@ export class MemWal {
343
450
  * Poll an accepted remember job until it reaches a terminal state.
344
451
  */
345
452
  async waitForRememberJob(jobId, opts = {}) {
453
+ const path = rememberStatusPath(jobId);
454
+ if (path === undefined) {
455
+ throw Object.assign(new Error(`remember job not found: ${jobId}`), {
456
+ status: 404,
457
+ jobId,
458
+ });
459
+ }
346
460
  const { pollIntervalMs = 1500, timeoutMs = 60_000 } = opts;
347
461
  const deadline = Date.now() + timeoutMs;
348
462
  let attempt = 0;
349
463
  let retryAfterMs = 0;
350
- while (Date.now() < deadline) {
464
+ let sawRateLimit = false;
465
+ let lastSeen;
466
+ let lastRefusal;
467
+ while (true) {
351
468
  // A retry-after the server just gave us wins over our own curve;
352
469
  // the backoff resumes from where it was on the next normal poll.
353
- await sleep(retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++));
470
+ // Clamped to remaining budget so we never sleep past deadline (#1081).
471
+ const remainingBeforeSleep = Math.max(0, deadline - Date.now());
472
+ const requestedDelay = retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++);
354
473
  retryAfterMs = 0;
474
+ const delay = Math.min(requestedDelay, remainingBeforeSleep);
475
+ if (delay > 0) {
476
+ await sleep(delay);
477
+ }
355
478
  let status;
356
479
  try {
357
- status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404],
480
+ status = await this.signedRequest("GET", path, {}, [200, 404],
358
481
  // Bound each poll by the client deadline, and never past
359
482
  // what is left of the budget. Without this the loop only
360
483
  // checks the deadline between polls, so one stalled read
@@ -365,11 +488,17 @@ export class MemWal {
365
488
  // and the client deadline keeps ONE stalled poll from
366
489
  // swallowing the entire budget, so the loop still gets to
367
490
  // retry. An expired poll surfaces as a transient 504.
368
- { timeoutMs: this.pollDeadlineMs(deadline) });
491
+ { timeoutMs: this.pollDeadlineMs(deadline), includeDelegateKey: false });
369
492
  }
370
493
  catch (err) {
371
494
  const httpStatus = err.status ?? 0;
372
495
  if (isTransientPollingStatus(httpStatus)) {
496
+ lastRefusal = httpStatus;
497
+ if (httpStatus === 429)
498
+ sawRateLimit = true;
499
+ if (Date.now() >= deadline) {
500
+ break;
501
+ }
373
502
  retryAfterMs = retryAfterDelayMs(err, deadline);
374
503
  continue;
375
504
  }
@@ -381,6 +510,7 @@ export class MemWal {
381
510
  jobId,
382
511
  });
383
512
  }
513
+ lastSeen = status;
384
514
  if (status.status === "done") {
385
515
  return {
386
516
  id: status.job_id,
@@ -393,23 +523,30 @@ export class MemWal {
393
523
  if (status.status === "failed") {
394
524
  throw Object.assign(new Error(`remember job failed: ${redactInternalUrls(status.error ?? "unknown error")}`), { status: 500, jobId });
395
525
  }
526
+ if (Date.now() >= deadline) {
527
+ break;
528
+ }
396
529
  }
397
- throw Object.assign(new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})`), { status: 504, jobId });
530
+ throw rememberJobTimeoutError(jobId, timeoutMs, lastSeen, lastRefusal, sawRateLimit);
398
531
  }
399
532
  /**
400
533
  * Remember something and wait for the background job to complete.
401
534
  */
402
- async rememberAndWait(text, namespace, opts = {}) {
403
- const resolvedNamespace = namespace ?? this.namespace;
535
+ async rememberAndWait(text, namespaceOrOptions, opts) {
536
+ requireRememberText(text);
537
+ const split = splitRememberArgs(namespaceOrOptions, opts);
538
+ const resolvedNamespace = split.namespace ?? this.namespace;
404
539
  const requestIdentity = `${resolvedNamespace}\0${text}`;
405
- const generatedKey = opts.idempotencyKey === undefined;
406
- const idempotencyKey = opts.idempotencyKey
540
+ const generatedKey = split.options.idempotencyKey === undefined;
541
+ const idempotencyKey = split.options.idempotencyKey
407
542
  ?? this.pendingRememberKeys.get(requestIdentity)
408
543
  ?? (await derivedIdempotencyKey(requestIdentity));
409
544
  if (generatedKey)
410
545
  this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
546
+ // Pass the resolved string. rememberAsync would otherwise read the
547
+ // options object in this slot as a namespace. (#1142)
411
548
  const accepted = await this.rememberAsync(text, resolvedNamespace, { idempotencyKey });
412
- const completed = await this.waitForRememberJob(accepted.job_id, opts);
549
+ const completed = await this.waitForRememberJob(accepted.job_id, split.options);
413
550
  // Clear only after terminal success. A polling timeout/transport failure
414
551
  // keeps the key so retrying the high-level operation reuses the same job.
415
552
  if (generatedKey)
@@ -422,11 +559,11 @@ export class MemWal {
422
559
  * The relayer continues embedding, encrypting, uploading, and indexing in the background.
423
560
  * Use rememberAndWait() when the caller needs the final blob_id before continuing.
424
561
  *
425
- * @param text - The text to remember
426
- * @param namespace - Optional namespace override
562
+ * A plain object in the namespace position is options, so
563
+ * `remember(text, { idempotencyKey })` keeps the client namespace. (#1142)
427
564
  */
428
- async remember(text, namespace, options = {}) {
429
- return this.rememberAsync(text, namespace, options);
565
+ async remember(text, namespaceOrOptions, options) {
566
+ return this.rememberAsync(text, namespaceOrOptions, options);
430
567
  }
431
568
  /**
432
569
  * Remember multiple memories in one batched request (ENG-1408).
@@ -449,22 +586,43 @@ export class MemWal {
449
586
  * console.log(accepted.job_ids)
450
587
  * ```
451
588
  */
452
- async rememberBulkAsync(items) {
589
+ async rememberBulkAsync(items, options = {}) {
453
590
  if (!Array.isArray(items) || items.length === 0) {
454
591
  throw new Error("rememberBulkAsync: items must be a non-empty array");
455
592
  }
593
+ // The relayer rejects this after the request is signed. Say so first. (#1104)
594
+ if (items.length > MAX_BULK_ITEMS) {
595
+ throw new Error(`rememberBulkAsync: items exceeds maximum of ${MAX_BULK_ITEMS} per bulk request`);
596
+ }
597
+ items.forEach((item, i) => {
598
+ assertNonBlankText(item?.text, `items[${i}].text cannot be empty`);
599
+ });
456
600
  const normalised = items.map((item) => ({
457
601
  text: item.text,
458
602
  namespace: item.namespace ?? this.namespace,
459
603
  }));
460
- const accepted = await this.signedRequest("POST", "/api/remember/bulk", { items: normalised }, [200, 202]);
604
+ const requestIdentity = `bulk\0${normalised.map((item) => `${item.namespace}\0${item.text}`).join("\0\0")}`;
605
+ const generatedKey = options.idempotencyKey === undefined;
606
+ const idempotencyKey = options.idempotencyKey
607
+ ?? this.pendingRememberKeys.get(requestIdentity)
608
+ ?? (await derivedBulkIdempotencyKey(requestIdentity));
609
+ if (generatedKey)
610
+ this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
611
+ const accepted = await this.signedRequest("POST", "/api/remember/bulk", { items: normalised, idempotency_key: idempotencyKey }, [200, 202]);
612
+ if (generatedKey)
613
+ this.pendingRememberKeys.delete(requestIdentity);
461
614
  if (!accepted.job_ids || accepted.job_ids.length !== normalised.length) {
462
615
  throw new Error(`rememberBulkAsync: server returned ${accepted.job_ids?.length ?? 0} job_ids for ${normalised.length} items`);
463
616
  }
464
617
  return accepted;
465
618
  }
466
619
  async getRememberBulkStatus(jobIds, opts = {}) {
467
- return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200], { timeoutMs: opts.timeoutMs });
620
+ if (!Array.isArray(jobIds)) {
621
+ throw new Error("getRememberBulkStatus: jobIds must be an array");
622
+ }
623
+ return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200],
624
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
625
+ { timeoutMs: opts.timeoutMs, includeDelegateKey: false });
468
626
  }
469
627
  async waitForRememberJobs(jobIds, namespaces = [], opts = {}) {
470
628
  const { pollIntervalMs = 1500, timeoutMs = 120_000 } = opts;
@@ -479,11 +637,64 @@ export class MemWal {
479
637
  const pending = new Set(jobIds);
480
638
  let attempt = 0;
481
639
  let retryAfterMs = 0;
482
- while (pending.size > 0 && Date.now() < deadline) {
640
+ let sawRateLimit = false;
641
+ const lastSeen = new Map();
642
+ let lastRefusal;
643
+ // Whether any status read got through. An item missing from an answer
644
+ // was not refused, so it must not be reported as if it had been.
645
+ let answered = false;
646
+ const settle = (jobId, status) => {
647
+ lastSeen.set(jobId, status);
648
+ // The same id can occupy more than one slot. `indexOf` updated only
649
+ // the first, and `pending` is a Set, so the copies stayed `timeout`.
650
+ // (#1121, #1084)
651
+ const terminal = status.status === "done" ||
652
+ status.status === "failed" ||
653
+ status.status === "not_found";
654
+ for (let idx = 0; idx < jobIds.length; idx++) {
655
+ if (jobIds[idx] !== jobId)
656
+ continue;
657
+ if (namespaces[idx] === undefined && status.namespace) {
658
+ results[idx].namespace = status.namespace;
659
+ }
660
+ if (!terminal)
661
+ continue;
662
+ // Caller namespace, then the job's own, then the client default. (#1136)
663
+ const namespace = namespaces[idx] ?? status.namespace ?? this.namespace;
664
+ if (status.status === "done") {
665
+ results[idx] = {
666
+ id: jobId,
667
+ blob_id: status.blob_id ?? "",
668
+ status: "done",
669
+ namespace,
670
+ };
671
+ }
672
+ else {
673
+ results[idx] = {
674
+ id: jobId,
675
+ blob_id: "",
676
+ status: "failed",
677
+ namespace,
678
+ error: status.status === "not_found"
679
+ ? "job not found"
680
+ : redactInternalUrls(status.error ?? "unknown error"),
681
+ };
682
+ }
683
+ }
684
+ if (terminal)
685
+ pending.delete(jobId);
686
+ };
687
+ while (pending.size > 0) {
483
688
  // A retry-after the server just gave us wins over our own curve;
484
689
  // the backoff resumes from where it was on the next normal poll.
485
- await sleep(retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++));
690
+ // Clamped to remaining budget so we never sleep past deadline (#1081).
691
+ const remainingBeforeSleep = Math.max(0, deadline - Date.now());
692
+ const requestedDelay = retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++);
486
693
  retryAfterMs = 0;
694
+ const delay = Math.min(requestedDelay, remainingBeforeSleep);
695
+ if (delay > 0) {
696
+ await sleep(delay);
697
+ }
487
698
  const pendingIds = jobIds.filter((jobId) => pending.has(jobId));
488
699
  if (pendingIds.length === 0) {
489
700
  break;
@@ -498,11 +709,18 @@ export class MemWal {
498
709
  catch (err) {
499
710
  const httpStatus = err.status ?? 0;
500
711
  if (isTransientPollingStatus(httpStatus)) {
712
+ lastRefusal = httpStatus;
713
+ if (httpStatus === 429)
714
+ sawRateLimit = true;
715
+ if (Date.now() >= deadline) {
716
+ break;
717
+ }
501
718
  retryAfterMs = retryAfterDelayMs(err, deadline);
502
719
  continue;
503
720
  }
504
721
  throw err;
505
722
  }
723
+ answered = true;
506
724
  const statusById = new Map();
507
725
  for (const item of batchStatus.results) {
508
726
  const bucket = statusById.get(item.job_id);
@@ -518,29 +736,49 @@ export class MemWal {
518
736
  if (!status) {
519
737
  continue;
520
738
  }
521
- const idx = jobIds.indexOf(jobId);
522
- if (status.status === "done") {
523
- results[idx] = {
524
- id: jobId,
525
- blob_id: status.blob_id ?? "",
526
- status: "done",
527
- namespace: namespaces[idx] ?? this.namespace,
528
- };
529
- pending.delete(jobId);
530
- }
531
- else if (status.status === "failed" || status.status === "not_found") {
532
- results[idx] = {
533
- id: jobId,
534
- blob_id: "",
535
- status: "failed",
536
- namespace: namespaces[idx] ?? this.namespace,
537
- error: status.status === "not_found"
538
- ? "job not found"
539
- : redactInternalUrls(status.error ?? "unknown error"),
540
- };
541
- pending.delete(jobId);
739
+ settle(jobId, status);
740
+ }
741
+ if (pending.size === 0 || Date.now() >= deadline) {
742
+ break;
743
+ }
744
+ }
745
+ // Nothing settled and nothing was even seen: the polls may all have been
746
+ // refused rather than the jobs being slow. Confirm with one direct read,
747
+ // as the MCP bridge does, before reporting anything.
748
+ if (timeoutMs > 0 && pending.size === jobIds.length && lastSeen.size === 0) {
749
+ try {
750
+ const probed = await this.getRememberBulkStatus(jobIds, {
751
+ timeoutMs: Math.min(this.requestTimeoutMs, CONFIRM_READ_TIMEOUT_MS),
752
+ });
753
+ answered = true;
754
+ for (const item of probed.results) {
755
+ if (pending.has(item.job_id))
756
+ settle(item.job_id, item);
542
757
  }
543
758
  }
759
+ catch (err) {
760
+ if (err.status === 429)
761
+ throw bulkRateLimitedError(err, jobIds);
762
+ // Any other probe failure is not evidence about the jobs.
763
+ }
764
+ }
765
+ for (let idx = 0; idx < jobIds.length; idx++) {
766
+ const jobId = jobIds[idx];
767
+ if (!pending.has(jobId))
768
+ continue;
769
+ const seen = lastSeen.get(jobId);
770
+ results[idx].error = seen
771
+ ? `still ${seen.status} after ${timeoutMs}ms` + (seen.error ? `: ${redactInternalUrls(seen.error)}` : "")
772
+ : answered
773
+ ? "not in the relayer's status answer; this item may not be stored"
774
+ : lastRefusal !== undefined
775
+ ? `no status read got through (last poll: HTTP ${lastRefusal}); this item may not be stored`
776
+ : `polling timed out after ${timeoutMs}ms`;
777
+ // Only the "no status read got through" message already names the 429.
778
+ const namesRateLimit = !seen && !answered && lastRefusal === 429;
779
+ if (sawRateLimit && !namesRateLimit) {
780
+ results[idx].error += "; wait hit a rate limit (429)";
781
+ }
544
782
  }
545
783
  const succeeded = results.filter((r) => r.status === "done").length;
546
784
  return {
@@ -553,53 +791,40 @@ export class MemWal {
553
791
  /**
554
792
  * Remember multiple memories and return as soon as the server accepts the jobs.
555
793
  */
556
- async rememberBulk(items) {
557
- return this.rememberBulkAsync(items);
794
+ async rememberBulk(items, options = {}) {
795
+ return this.rememberBulkAsync(items, options);
558
796
  }
559
797
  /**
560
798
  * Remember multiple memories and wait until every job reaches a terminal state.
561
799
  */
562
800
  async rememberBulkAndWait(items, opts = {}) {
563
- const namespaces = items.map((item) => item.namespace ?? this.namespace);
564
- const accepted = await this.rememberBulkAsync(items);
565
- return this.waitForRememberJobs(accepted.job_ids, namespaces, opts);
801
+ if (!Array.isArray(items) || items.length === 0) {
802
+ throw new Error("rememberBulkAsync: items must be a non-empty array");
803
+ }
804
+ if (items.length > MAX_BULK_ITEMS) {
805
+ throw new Error(`rememberBulkAsync: items exceeds maximum of ${MAX_BULK_ITEMS} per bulk request`);
806
+ }
807
+ items.forEach((item, i) => {
808
+ assertNonBlankText(item?.text, `items[${i}].text cannot be empty`);
809
+ });
810
+ const normalised = items.map((item) => ({
811
+ text: item.text,
812
+ namespace: item.namespace ?? this.namespace,
813
+ }));
814
+ const requestIdentity = `bulk\0${normalised.map((item) => `${item.namespace}\0${item.text}`).join("\0\0")}`;
815
+ const generatedKey = opts.idempotencyKey === undefined;
816
+ const idempotencyKey = opts.idempotencyKey
817
+ ?? this.pendingRememberKeys.get(requestIdentity)
818
+ ?? (await derivedBulkIdempotencyKey(requestIdentity));
819
+ if (generatedKey)
820
+ this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
821
+ const namespaces = normalised.map((item) => item.namespace);
822
+ const accepted = await this.rememberBulkAsync(items, { ...opts, idempotencyKey });
823
+ const completed = await this.waitForRememberJobs(accepted.job_ids, namespaces, opts);
824
+ if (generatedKey)
825
+ this.pendingRememberKeys.delete(requestIdentity);
826
+ return completed;
566
827
  }
567
- /**
568
- * Recall memories similar to a query — server handles:
569
- * verify → embed query → search → Walrus download → decrypt → return plaintext.
570
- *
571
- * **Preferred call style**: pass a single `RecallParams` object
572
- * so call sites read self-describingly:
573
- * ```ts
574
- * memwal.recall({ query: "food allergies", limit: 5, namespace: "profile" })
575
- * ```
576
- *
577
- * The legacy positional forms remain supported for backwards compatibility:
578
- * - `recall(query)`
579
- * - `recall(query, limit)`
580
- * - `recall(query, limit, namespace)`
581
- * - `recall(query, { limit, namespace, maxDistance, topK })`
582
- *
583
- * `topK` and `limit` are aliases; if both are set, `topK` wins.
584
- *
585
- * @returns RecallResult with decrypted text results
586
- *
587
- * @example
588
- * ```typescript
589
- * // Object style — recommended
590
- * const result = await memwal.recall({
591
- * query: "food allergies",
592
- * limit: 5,
593
- * namespace: "profile",
594
- * });
595
- * for (const memory of result.results) {
596
- * console.log(memory.text, memory.distance);
597
- * }
598
- *
599
- * // Positional style — still works
600
- * const result2 = await memwal.recall("food allergies", 5, "profile");
601
- * ```
602
- */
603
828
  /**
604
829
  * Estimate the token cost of a string using the SDK's default
605
830
  * character-based approximation (~chars/4, code-point aware). Useful to weigh
@@ -619,64 +844,75 @@ export class MemWal {
619
844
  return estimateTokens(text);
620
845
  }
621
846
  async recall(queryOrParams, limitOrOptions = 10, namespace) {
622
- let query;
623
- let options;
624
- if (typeof queryOrParams === "object") {
625
- const { query: q, ...rest } = queryOrParams;
626
- query = q;
627
- options = rest;
847
+ const { query, options } = resolveRecallCall(queryOrParams, limitOrOptions, namespace);
848
+ validateMaxTokens(options.maxTokens);
849
+ assertNonBlankText(query, "query cannot be empty");
850
+ const rawLimit = options.topK !== undefined ? options.topK : options.limit;
851
+ const limit = rawLimit !== undefined ? rawLimit : 10;
852
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
853
+ throw new TypeError(`limit must be a positive integer, got ${limit}`);
628
854
  }
629
- else {
630
- query = queryOrParams;
631
- if (limitOrOptions == null) {
632
- options = { limit: 10, namespace };
633
- }
634
- else if (typeof limitOrOptions === "number") {
635
- options = { limit: limitOrOptions, namespace };
636
- }
637
- else {
638
- options = limitOrOptions;
855
+ const weights = options.scoringWeights;
856
+ if (weights) {
857
+ for (const [name, value] of Object.entries(weights)) {
858
+ if (value !== undefined && (typeof value !== "number" || !Number.isFinite(value))) {
859
+ throw new Error(`scoringWeights.${name} must be a finite number`);
860
+ }
639
861
  }
640
862
  }
641
- const limit = options.topK ?? options.limit ?? 10;
863
+ if (options.maxDistance !== undefined
864
+ && (typeof options.maxDistance !== "number"
865
+ || !Number.isFinite(options.maxDistance)
866
+ || options.maxDistance < 0)) {
867
+ throw new Error("maxDistance must be a non-negative finite number");
868
+ }
642
869
  const resolvedNamespace = options.namespace ?? this.namespace;
643
870
  {
871
+ // WALM-598: this budget is handed to `signedRequest`, which starts
872
+ // the clock on the `/api/recall` fetch itself — after
873
+ // `ensureCompatibleRelayer` (`/version`, falling back to `/health`)
874
+ // and `buildSealSession` (`/config` + Sui RPC) have already
875
+ // resolved. Those preflights carry their own independent
876
+ // deadlines, so a relayer whose `/health` p50 had crept to ~9s can
877
+ // no longer eat most of recall's window and make a perfectly
878
+ // healthy recall surface an `AbortError` (GH #438).
879
+ const budget = options.timeoutMs ?? this.recallTimeoutMs;
880
+ const optedOut = typeof budget !== "number" || !Number.isFinite(budget) || budget <= 0;
881
+ const timeoutMs = optedOut ? 0 : budget;
882
+ const wireDeadline = optedOut
883
+ ? undefined
884
+ : (timeoutMs > RECALL_DEADLINE_MARGIN_MS
885
+ ? timeoutMs - RECALL_DEADLINE_MARGIN_MS
886
+ : timeoutMs);
644
887
  const result = await this.signedRequest("POST", "/api/recall", {
645
888
  query,
646
889
  limit,
647
890
  namespace: resolvedNamespace,
648
- // `undefined` when no weights were supplied, which
649
- // JSON.stringify drops — so a default-weighted recall stays
650
- // byte-identical on the wire and the relayer keeps
651
- // short-circuiting to the plain pgvector cosine order.
652
891
  scoring_weights: scoringWeightsToWire(options.scoringWeights),
653
- // Same `undefined`-is-dropped trick: an unset sort leaves the
654
- // request byte-identical and the relayer applies its own
655
- // "relevance" default.
656
892
  sort: options.sort,
657
- // How long this call waits, so the relayer can stop just
658
- // short of it and name the step it was stuck in.
659
- deadline_ms: RECALL_DEADLINE_MS,
660
- }, { timeoutMs: RECALL_REQUEST_TIMEOUT_MS });
893
+ ...(wireDeadline === undefined ? {} : { deadline_ms: wireDeadline }),
894
+ }, { timeoutMs });
661
895
  let processed = result;
662
896
  if (typeof options.maxDistance === "number") {
663
897
  const filtered = result.results.filter((memory) => memory.distance < options.maxDistance);
898
+ // Keep the relayer's matching total so callers can distinguish
899
+ // "no memories exist" from "matches exist but were outside maxDistance" (#1066).
664
900
  processed = {
665
901
  ...processed,
666
902
  results: filtered,
667
- total: filtered.length,
668
903
  };
669
904
  }
670
- // Client-side token budgeting: trim the (already distance-sorted)
671
- // payload to fit maxTokens per the chosen strategy, and attach the
672
- // token estimate + truncated flag. Omitting maxTokens leaves the
673
- // result byte-identical to the pre-budget behavior (no meta).
674
- if (typeof options.maxTokens === "number") {
905
+ // Client-side token budgeting: trim the payload to fit maxTokens per
906
+ // the chosen strategy, and attach the token estimate + truncated flag.
907
+ // Under high-relevance-only, lowest-distance hits are retained and
908
+ // returned in the caller's requested order (WALM-756).
909
+ // Omitting maxTokens leaves the result byte-identical to the pre-budget
910
+ // behavior (no meta). Total preserves the matching hit count (#1068).
911
+ if (options.maxTokens !== undefined) {
675
912
  const { results: budgeted, meta } = applyTokenBudget(processed.results, options.maxTokens, options.truncationStrategy, options.countTokens);
676
913
  processed = {
677
914
  ...processed,
678
915
  results: budgeted,
679
- total: budgeted.length,
680
916
  meta,
681
917
  };
682
918
  }
@@ -725,7 +961,7 @@ export class MemWal {
725
961
  * @param opts.vector - Pre-computed query embedding vector
726
962
  * @param opts.limit - Max results (default: 10)
727
963
  * @param opts.scoringWeights - Optional composite-scoring weights
728
- * @returns RecallManualResult with blob_id + distance pairs (no decrypted text)
964
+ * @returns RecallManualHitResult with blob_id + distance pairs (no decrypted text)
729
965
  *
730
966
  * @example
731
967
  * ```typescript
@@ -744,9 +980,13 @@ export class MemWal {
744
980
  * ```
745
981
  */
746
982
  async recallManual(opts) {
983
+ const limit = opts.limit !== undefined ? opts.limit : 10;
984
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
985
+ throw new TypeError(`limit must be a positive integer, got ${limit}`);
986
+ }
747
987
  return this.signedRequest("POST", "/api/recall/manual", {
748
988
  vector: opts.vector,
749
- limit: opts.limit ?? 10,
989
+ limit,
750
990
  namespace: opts.namespace ?? this.namespace,
751
991
  scoring_weights: scoringWeightsToWire(opts.scoringWeights),
752
992
  }, { includeDelegateKey: false });
@@ -758,6 +998,7 @@ export class MemWal {
758
998
  * @returns EmbedResult with vector
759
999
  */
760
1000
  async embed(text) {
1001
+ assertNonBlankText(text, "text cannot be empty");
761
1002
  return this.signedRequest("POST", "/api/embed", { text }, { includeDelegateKey: false });
762
1003
  }
763
1004
  /**
@@ -776,6 +1017,7 @@ export class MemWal {
776
1017
  * ```
777
1018
  */
778
1019
  async analyze(text, namespaceOrOptions) {
1020
+ assertNonBlankText(text);
779
1021
  const options = normalizeAnalyzeOptions(namespaceOrOptions);
780
1022
  const body = {
781
1023
  text,
@@ -849,6 +1091,9 @@ export class MemWal {
849
1091
  * ```
850
1092
  */
851
1093
  async restore(namespace, limit = 10) {
1094
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
1095
+ throw new TypeError(`limit must be a positive integer, got ${limit}`);
1096
+ }
852
1097
  const result = await this.signedRequest("POST", "/api/restore", { namespace, limit }, [200], { timeoutMs: RESTORE_REQUEST_TIMEOUT_MS });
853
1098
  // Relayers older than WALM-319 omit `truncated` entirely — treat
854
1099
  // "not present" as "not known to be truncated" rather than drop
@@ -899,6 +1144,58 @@ export class MemWal {
899
1144
  includeDelegateKey: false,
900
1145
  });
901
1146
  }
1147
+ /**
1148
+ * List the memories this account holds, without a semantic query.
1149
+ *
1150
+ * Recall is similarity-ranked and limit-bounded, so it cannot confirm a
1151
+ * write or count a namespace. This walks the full inventory instead.
1152
+ * Returns metadata only — no blob fetch, no decryption; use `recall()`
1153
+ * for content.
1154
+ *
1155
+ * `namespace` is filtered client-side: the relayer lists every namespace,
1156
+ * so a filtered page can be short or empty while `has_more` is true.
1157
+ * Paginate with `has_more`, NOT page length.
1158
+ *
1159
+ * ```ts
1160
+ * let cursor: string | undefined;
1161
+ * let more = true;
1162
+ * let count = 0;
1163
+ * while (more) {
1164
+ * const page = await memwal.listMemories({ cursor, namespace: "work" });
1165
+ * count += page.memories.length;
1166
+ * cursor = page.next_cursor ?? undefined;
1167
+ * more = page.has_more;
1168
+ * }
1169
+ * ```
1170
+ */
1171
+ async listMemories(options = {}) {
1172
+ const owner = await this.resolveOwner();
1173
+ const params = new URLSearchParams();
1174
+ if (options.cursor !== undefined)
1175
+ params.set("updated_after", options.cursor);
1176
+ if (options.limit !== undefined)
1177
+ params.set("limit", String(options.limit));
1178
+ const query = params.toString();
1179
+ // Query string must be part of the signed path (see listNamespaces).
1180
+ const path = `/v1/owners/${owner}/memories${query ? `?${query}` : ""}`;
1181
+ const raw = await this.signedRequest("GET", path, {}, [200], {
1182
+ includeDelegateKey: false,
1183
+ });
1184
+ // Relayers older than WALM-363 omit the tombstone fields.
1185
+ const page = {
1186
+ ...raw,
1187
+ deleted: raw.deleted ?? [],
1188
+ must_resync: raw.must_resync ?? false,
1189
+ };
1190
+ if (options.namespace === undefined)
1191
+ return page;
1192
+ const namespace = options.namespace;
1193
+ return {
1194
+ ...page,
1195
+ memories: page.memories.filter((m) => m.namespace_id === namespace),
1196
+ deleted: page.deleted.filter((d) => d.namespace_id === namespace),
1197
+ };
1198
+ }
902
1199
  /**
903
1200
  * Resolve this account's owner address, memoised for the client's life.
904
1201
  *
@@ -937,7 +1234,7 @@ export class MemWal {
937
1234
  * Check server health. The endpoint is public and does not require request signing.
938
1235
  */
939
1236
  async health() {
940
- const res = await this.fetchWithDeadline(`${this.serverUrl}/health`);
1237
+ const res = await this.fetchWithDeadline(`${this.serverUrl}/health`, {}, this.preflightTimeoutMs, "GET /health");
941
1238
  if (!res.ok) {
942
1239
  throw new Error(`Health check failed: ${res.status}`);
943
1240
  }
@@ -954,17 +1251,32 @@ export class MemWal {
954
1251
  */
955
1252
  async getPublicKeyHex() {
956
1253
  const pk = await this.getPublicKey();
1254
+ // `await` yields even when the key was already cached. destroy()
1255
+ // zero-fills that cache in place, so encode only after a fresh check
1256
+ // or this resolves to 64 zero hex chars. (#1090)
1257
+ if (this.destroyed)
1258
+ throw destroyedClientError();
957
1259
  return bytesToHex(pk);
958
1260
  }
959
1261
  // ============================================================
960
1262
  // Internal: Signed HTTP Requests
961
1263
  // ============================================================
962
1264
  async getPublicKey() {
1265
+ // destroy() zero-fills the cache in place, and an uncached key would
1266
+ // otherwise derive the well-known key of the all-zero seed. Re-check
1267
+ // after every await, and never cache a key derived once wiped. (#1090)
1268
+ if (this.destroyed)
1269
+ throw destroyedClientError();
963
1270
  if (!this.publicKey) {
964
1271
  const ed = await getEd();
965
- this.publicKey = await ed.getPublicKeyAsync(this.privateKey);
1272
+ if (this.destroyed)
1273
+ throw destroyedClientError();
1274
+ const derived = await ed.getPublicKeyAsync(this.privateKey);
1275
+ if (this.destroyed)
1276
+ throw destroyedClientError();
1277
+ this.publicKey = derived;
966
1278
  }
967
- return this.publicKey;
1279
+ return this.publicKey.slice();
968
1280
  }
969
1281
  async ensureCompatibleRelayer() {
970
1282
  if (this.relayerVersionMetadata)
@@ -977,13 +1289,17 @@ export class MemWal {
977
1289
  return this.compatibilityPromise;
978
1290
  }
979
1291
  async fetchCompatibilityMetadata() {
980
- const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" });
1292
+ // WALM-598: both round-trips get their own bounded budget. They run
1293
+ // inside whatever signed request triggered the compatibility probe, so
1294
+ // leaving them untimed let a stalled relayer silently drain that
1295
+ // caller's deadline (and, with no signal at all, hang indefinitely).
1296
+ const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" }, this.preflightTimeoutMs, "preflight GET /version");
981
1297
  let body;
982
1298
  if (versionRes.ok) {
983
1299
  body = versionRes.body;
984
1300
  }
985
1301
  else if (versionRes.status === 404 || versionRes.status === 405) {
986
- const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" });
1302
+ const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" }, this.preflightTimeoutMs, "preflight GET /health");
987
1303
  if (!healthRes.ok) {
988
1304
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ` +
989
1305
  `${versionRes.status}, and GET /health returned ${healthRes.status}`);
@@ -1021,7 +1337,9 @@ export class MemWal {
1021
1337
  async fetchServerConfig() {
1022
1338
  if (this.serverConfig)
1023
1339
  return this.serverConfig;
1024
- const res = await this.fetchWithDeadline(`${this.serverUrl}/config`, { method: "GET" });
1340
+ // WALM-598: bounded like the other preflights — this one is awaited
1341
+ // inside `buildSealSession`, itself awaited inside a caller's budget.
1342
+ const res = await this.fetchWithDeadline(`${this.serverUrl}/config`, { method: "GET" }, this.preflightTimeoutMs, "preflight GET /config");
1025
1343
  if (!res.ok) {
1026
1344
  throw new Error(`GET /config returned ${res.status}`);
1027
1345
  }
@@ -1229,24 +1547,43 @@ export class MemWal {
1229
1547
  * one stalled socket there hangs every method on the client, not just one.
1230
1548
  */
1231
1549
  /** Deadline for one status poll: the client deadline, clamped so it can
1232
- * never outlive the wait budget it belongs to. */
1550
+ * never outlive the wait budget it belongs to, but given a usable minimum
1551
+ * at or past the deadline so a boundary check does not fail with an
1552
+ * artificial 1ms AbortError (#1081). */
1233
1553
  pollDeadlineMs(deadline) {
1234
- return Math.max(1, Math.min(this.requestTimeoutMs, deadline - Date.now()));
1554
+ const remaining = deadline - Date.now();
1555
+ const minPollTimeout = Math.min(this.requestTimeoutMs, 1_000);
1556
+ if (remaining <= 0) {
1557
+ return minPollTimeout;
1558
+ }
1559
+ return Math.min(this.requestTimeoutMs, Math.max(remaining, minPollTimeout));
1235
1560
  }
1236
- async fetchWithDeadline(url, init = {}, timeoutMs) {
1561
+ async fetchWithDeadline(url, init = {}, timeoutMs, phase) {
1237
1562
  const ms = timeoutMs ?? this.requestTimeoutMs;
1238
1563
  const deadline = deadlineSignal(ms);
1239
1564
  try {
1240
1565
  const res = await fetch(url, { ...init, signal: deadline.signal });
1241
- return {
1242
- ok: res.ok,
1243
- status: res.status,
1244
- body: res.ok ? (await res.json()) : undefined,
1245
- };
1566
+ let body;
1567
+ if (res.ok) {
1568
+ const raw = await res.text();
1569
+ if (raw.trim() === "") {
1570
+ throw jsonBodyError(res.status, `MemWal: HTTP ${res.status} response had an empty body; expected JSON`);
1571
+ }
1572
+ try {
1573
+ body = JSON.parse(raw);
1574
+ }
1575
+ catch (err) {
1576
+ if (err instanceof SyntaxError) {
1577
+ throw jsonBodyError(res.status, `MemWal: HTTP ${res.status} response was not JSON`);
1578
+ }
1579
+ throw err;
1580
+ }
1581
+ }
1582
+ return { ok: res.ok, status: res.status, body };
1246
1583
  }
1247
1584
  catch (err) {
1248
1585
  if (deadline.timedOut()) {
1249
- throw requestTimeoutError(init.method ?? "GET", url, ms);
1586
+ throw requestTimeoutError(init.method ?? "GET", url, ms, phase);
1250
1587
  }
1251
1588
  throw err;
1252
1589
  }
@@ -1261,6 +1598,9 @@ export class MemWal {
1261
1598
  const options = Array.isArray(acceptedStatusesOrOptions)
1262
1599
  ? requestOptions
1263
1600
  : acceptedStatusesOrOptions;
1601
+ // Before the version probe. A destroyed client must not open GET /version. (#1090)
1602
+ if (this.destroyed)
1603
+ throw destroyedClientError();
1264
1604
  await this.ensureCompatibleRelayer();
1265
1605
  const ed = await getEd();
1266
1606
  const timestamp = Math.floor(Date.now() / 1000).toString();
@@ -1275,12 +1615,19 @@ export class MemWal {
1275
1615
  // LOW-23: Build message to sign — now includes nonce AND account id
1276
1616
  const message = `${timestamp}.${method}.${path}.${bodySha256}.${nonce}.${this.accountId}`;
1277
1617
  const msgBytes = new TextEncoder().encode(message);
1278
- if (this.destroyed) {
1279
- throw new Error("Walrus Memory client was destroyed; its keys are zeroed. Create a new one.");
1280
- }
1618
+ // Again after the version await. A destroy that lands while that
1619
+ // request is in flight must still refuse to sign. (#1090)
1620
+ if (this.destroyed)
1621
+ throw destroyedClientError();
1281
1622
  // Sign with Ed25519
1282
1623
  const signature = await ed.signAsync(msgBytes, this.privateKey);
1624
+ // destroy() during the sign, or during public-key derivation, must
1625
+ // not reach fetch with the wiped seed's well-known key. (#1090)
1626
+ if (this.destroyed)
1627
+ throw destroyedClientError();
1283
1628
  const publicKey = await this.getPublicKey();
1629
+ if (this.destroyed)
1630
+ throw destroyedClientError();
1284
1631
  // Make HTTP request
1285
1632
  const url = `${this.serverUrl}${path}`;
1286
1633
  const headers = {
@@ -1298,17 +1645,31 @@ export class MemWal {
1298
1645
  if (options.includeDelegateKey !== false) {
1299
1646
  headers["x-seal-session"] = await this.buildSealSession();
1300
1647
  }
1301
- // Bound the request. `fetch` never times out on its own, so this is the
1302
- // only thing standing between a stalled socket and a call that hangs
1303
- // for as long as the connection stays open.
1304
- const deadlineMs = options.timeoutMs ?? this.requestTimeoutMs;
1305
- const deadline = deadlineSignal(deadlineMs, options.signal);
1648
+ // WALM-598: the caller's deadline starts HERE, not at the top of the
1649
+ // call. Everything above — `ensureCompatibleRelayer()` (`/version` ->
1650
+ // `/health`) and `buildSealSession()` (`/config`, dynamic imports, a
1651
+ // Sui RPC round-trip for `SessionKey.create`) — is preflight work that
1652
+ // used to run inside the caller's budget while being unabortable
1653
+ // itself. Each of those now carries its own independent deadline.
1654
+ //
1655
+ // `fetch` never times out on its own, so this deadline is also the only
1656
+ // thing standing between a stalled socket and a call that hangs for as
1657
+ // long as the connection stays open.
1658
+ const explicitTimeout = options.timeoutMs;
1659
+ const deadlineOptOut = typeof explicitTimeout === "number"
1660
+ && (!Number.isFinite(explicitTimeout) || explicitTimeout <= 0);
1661
+ const deadlineMs = deadlineOptOut
1662
+ ? undefined
1663
+ : (explicitTimeout ?? this.requestTimeoutMs);
1664
+ const deadline = deadlineMs === undefined
1665
+ ? undefined
1666
+ : deadlineSignal(deadlineMs, options.signal);
1306
1667
  try {
1307
1668
  const res = await fetch(url, {
1308
1669
  method,
1309
1670
  headers,
1310
1671
  body: method === "GET" ? undefined : bodyStr,
1311
- signal: deadline.signal,
1672
+ signal: deadline?.signal ?? options.signal,
1312
1673
  });
1313
1674
  if (!acceptedStatuses.includes(res.status)) {
1314
1675
  // LOW-26: sanitize server error bodies before surfacing to callers.
@@ -1335,18 +1696,33 @@ export class MemWal {
1335
1696
  err.cause = raw;
1336
1697
  throw err;
1337
1698
  }
1338
- return (await res.json());
1699
+ const rawBody = await res.text();
1700
+ if (rawBody.trim() === "") {
1701
+ throw jsonBodyError(res.status, `MemWal: HTTP ${res.status} response had an empty body; expected JSON`);
1702
+ }
1703
+ try {
1704
+ return JSON.parse(rawBody);
1705
+ }
1706
+ catch (err) {
1707
+ if (err instanceof SyntaxError) {
1708
+ throw jsonBodyError(res.status, `MemWal: HTTP ${res.status} response was not JSON`);
1709
+ }
1710
+ throw err;
1711
+ }
1339
1712
  }
1340
1713
  catch (err) {
1341
1714
  // Translate our own expiry into something a caller can classify.
1342
1715
  // An abort the CALLER asked for is theirs and propagates untouched.
1343
- if (deadline.timedOut() && err.status === undefined) {
1344
- throw requestTimeoutError(method, path, deadlineMs);
1716
+ const status = err && typeof err === "object" && "status" in err
1717
+ ? err.status
1718
+ : undefined;
1719
+ if (deadline?.timedOut() && typeof status !== "number") {
1720
+ throw requestTimeoutError(method, path, deadlineMs ?? 0);
1345
1721
  }
1346
1722
  throw err;
1347
1723
  }
1348
1724
  finally {
1349
- deadline.dispose();
1725
+ deadline?.dispose();
1350
1726
  }
1351
1727
  }
1352
1728
  }