@mysten-incubation/memwal 0.1.8-dev.2 → 0.1.8-dev.21

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 (47) 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 +57 -20
  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.d.ts +22 -4
  14. package/dist/manual.d.ts.map +1 -1
  15. package/dist/manual.js +158 -71
  16. package/dist/manual.js.map +1 -1
  17. package/dist/memwal.d.ts +87 -31
  18. package/dist/memwal.d.ts.map +1 -1
  19. package/dist/memwal.js +544 -206
  20. package/dist/memwal.js.map +1 -1
  21. package/dist/mock.d.ts +27 -11
  22. package/dist/mock.d.ts.map +1 -1
  23. package/dist/mock.js +161 -47
  24. package/dist/mock.js.map +1 -1
  25. package/dist/polling-delay.d.ts +3 -0
  26. package/dist/polling-delay.d.ts.map +1 -0
  27. package/dist/polling-delay.js +13 -0
  28. package/dist/polling-delay.js.map +1 -0
  29. package/dist/recall-args.d.ts +12 -0
  30. package/dist/recall-args.d.ts.map +1 -0
  31. package/dist/recall-args.js +44 -0
  32. package/dist/recall-args.js.map +1 -0
  33. package/dist/sui-client.d.ts +10 -0
  34. package/dist/sui-client.d.ts.map +1 -0
  35. package/dist/sui-client.js +29 -0
  36. package/dist/sui-client.js.map +1 -0
  37. package/dist/tokens.d.ts +19 -4
  38. package/dist/tokens.d.ts.map +1 -1
  39. package/dist/tokens.js +51 -13
  40. package/dist/tokens.js.map +1 -1
  41. package/dist/types.d.ts +106 -6
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/utils.d.ts +72 -0
  44. package/dist/utils.d.ts.map +1 -1
  45. package/dist/utils.js +189 -3
  46. package/dist/utils.js.map +1 -1
  47. 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,43 +47,61 @@ 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 destroyedClientError() {
94
+ return new Error("Walrus Memory client was destroyed; its keys are zeroed. Create a new one.");
95
+ }
79
96
  /** `POST /api/analyze` runs the extractor LLM inline before it accepts, so it
80
97
  * is the one write that legitimately outruns the default. */
81
98
  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;
99
+ /** How far under the client's own abort `recall()` asks the relayer to stop,
100
+ * so the 504 naming the stuck stage arrives before the abort rather than
101
+ * after it. A second, because the two clocks start at different moments: this
102
+ * timer starts before `fetch`, the relayer's when the request lands, and the
103
+ * margin the relayer keeps for its reply cannot also cover DNS, TCP and TLS. */
104
+ const RECALL_DEADLINE_MARGIN_MS = 1_000;
85
105
  /**
86
106
  * Abort signal that fires after `ms`, or when `caller` aborts — whichever is
87
107
  * first. Built by hand rather than with `AbortSignal.any`, which lands too
@@ -124,14 +144,47 @@ function deadlineSignal(ms, caller) {
124
144
  * `status: 504` is load-bearing, not decoration: `isTransientPollingStatus`
125
145
  * treats it as retryable, so one stalled poll inside a wait loop is abandoned
126
146
  * and retried against the remaining budget instead of failing the whole wait.
147
+ *
148
+ * `phase` names the round-trip that actually stalled — `"preflight GET
149
+ * /version"`, `"POST /api/recall"` — so WALM-598's diagnostic question ("which
150
+ * step ate the budget?") is answerable from the error alone. The name stays
151
+ * `MemWalRequestTimeout`: that is the shipped contract callers and
152
+ * `isTransientPollingStatus` already key off (WALM-648).
127
153
  */
128
- function requestTimeoutError(method, path, ms) {
129
- const err = new Error(`Walrus Memory request timed out after ${ms}ms (${method} ${path}). The relayer ` +
154
+ function requestTimeoutError(method, path, ms, phase) {
155
+ const stage = phase ?? `${method} ${path}`;
156
+ const err = new Error(`Walrus Memory request timed out after ${ms}ms during ${stage}. The relayer ` +
130
157
  `accepted the connection but did not answer in time.`);
131
158
  err.name = "MemWalRequestTimeout";
132
159
  err.status = 504;
160
+ err.phase = stage;
161
+ err.timeoutMs = ms;
133
162
  return err;
134
163
  }
164
+ /**
165
+ * The 504 a remember wait raises when its budget runs out.
166
+ *
167
+ * Under upload congestion the relayer keeps a job `running` for tens of
168
+ * minutes, far past a 60s wait, and says so in the job's `error`. Carrying the
169
+ * last status the relayer reported is what lets a caller tell "still retrying,
170
+ * wait on the same job" from "we never got an answer" (GH #966). The wait
171
+ * only times out on a job that is still pending/running/uploaded (a `failed`
172
+ * job throws), so the advice is always to keep waiting on the job id.
173
+ */
174
+ function rememberJobTimeoutError(jobId, timeoutMs, lastSeen, lastRefusal, sawRateLimit) {
175
+ const serverError = lastSeen?.error ? redactInternalUrls(lastSeen.error) : undefined;
176
+ // "no status read got through (last poll: HTTP 429)" already names the rate limit.
177
+ const rateLimited = sawRateLimit && (lastSeen || lastRefusal !== 429) ? "; wait hit a rate limit (429)" : "";
178
+ const detail = lastSeen
179
+ ? `last status: ${lastSeen.status}${serverError ? ` (${serverError})` : ""}. ` +
180
+ `The job is still in progress: call waitForRememberJob("${jobId}") to keep waiting on it. ` +
181
+ `Sending the text again under a new idempotency key stores it twice; a key you passed ` +
182
+ `as idempotencyKey is not remembered by the client, so pass it again on any retry.`
183
+ : `no status read got through (last poll: HTTP ${lastRefusal ?? 0}), so the job's state is unknown.`;
184
+ const err = new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})${rateLimited}; ${detail}`);
185
+ err.name = "MemWalRememberJobTimeout";
186
+ return Object.assign(err, { status: 504, jobId, lastStatus: lastSeen?.status, serverError });
187
+ }
135
188
  function isTransientPollingStatus(status) {
136
189
  return status === 0 || status === 429 || status >= 500;
137
190
  }
@@ -157,6 +210,24 @@ function retryAfterDelayMs(err, deadline) {
157
210
  return 0;
158
211
  return Math.max(0, Math.min(seconds * 1000, deadline - Date.now()));
159
212
  }
213
+ /**
214
+ * Thrown when a bulk wait could not read a single status, the confirming read
215
+ * included. The status endpoint counts against the same delegate-key budget
216
+ * as writes, so a batch sent near the limit can have every poll refused. The
217
+ * old result then read as "still uploading" even when nothing had landed
218
+ * (GH #967). A refusal says nothing about the jobs, so do not report it as
219
+ * progress.
220
+ */
221
+ function bulkRateLimitedError(err, jobIds) {
222
+ const retryAfterSeconds = err.retryAfterSeconds
223
+ ?? retryAfterSecondsFromBody(err.cause);
224
+ const wait = retryAfterSeconds ? ` after ~${Math.ceil(retryAfterSeconds)}s` : "";
225
+ const e = new Error(`Walrus Memory rate-limited every status read for this batch, so none of its ${jobIds.length} writes ` +
226
+ `could be confirmed. Do not treat them as stored: check them with getRememberBulkStatus(jobIds)${wait}. ` +
227
+ `Status reads count against the same delegate-key budget as writes.`);
228
+ e.name = "MemWalRateLimited";
229
+ return Object.assign(e, { status: 429, jobIds, retryAfterSeconds });
230
+ }
160
231
  /**
161
232
  * The relayer states the backoff in the 429 body as well as in `Retry-After`.
162
233
  * A proxy that strips the header must not cost us the hint.
@@ -225,6 +296,13 @@ export class MemWal {
225
296
  accountId;
226
297
  /** Deadline applied to any request that does not name its own. */
227
298
  requestTimeoutMs;
299
+ /**
300
+ * Recall's abort budget, and the independent per-round-trip budget for the
301
+ * unauthenticated preflights that precede it. Separate so a slow
302
+ * `/version`, `/health` or `/config` is never charged against recall.
303
+ */
304
+ recallTimeoutMs;
305
+ preflightTimeoutMs;
228
306
  // ENG-1697 state — all internal, never surfaced to user code.
229
307
  // The public API (`MemWal.create({ key, accountId })`) is unchanged.
230
308
  sessionCache = null;
@@ -250,11 +328,23 @@ export class MemWal {
250
328
  typeof config.key === "string"
251
329
  ? hexToBytes(normalizePrivateKey(config.key))
252
330
  : config.key;
331
+ if (!(this.privateKey instanceof Uint8Array) || this.privateKey.length !== 32) {
332
+ const got = this.privateKey instanceof Uint8Array
333
+ ? String(this.privateKey.length)
334
+ : typeof this.privateKey;
335
+ throw new Error(`Ed25519 seed must be exactly 32 bytes, got ${got}`);
336
+ }
337
+ if (typeof config.accountId !== "string" || config.accountId.trim().length === 0) {
338
+ throw new TypeError(`MemWal.create: "accountId" is required (Walrus Memory object ID, e.g. 0x...); got ${config.accountId}`);
339
+ }
253
340
  this.accountId = config.accountId;
254
341
  // LOW-22: default to HTTPS for production usage; normalizeServerUrl
255
342
  // warns (does not throw) if a user passes plain http:// for a
256
343
  // non-localhost host.
257
344
  this.serverUrl = normalizeServerUrl(config.serverUrl ?? "https://relayer.memory.walrus.xyz");
345
+ if (config.namespace !== undefined && !config.namespace) {
346
+ throw new Error("namespace cannot be empty");
347
+ }
258
348
  this.namespace = config.namespace ?? "default";
259
349
  // A non-positive or non-finite override would disable the backstop
260
350
  // entirely, which is the bug this exists to prevent.
@@ -262,6 +352,8 @@ export class MemWal {
262
352
  Number.isFinite(config.requestTimeoutMs) && config.requestTimeoutMs > 0
263
353
  ? config.requestTimeoutMs
264
354
  : DEFAULT_REQUEST_TIMEOUT_MS;
355
+ this.recallTimeoutMs = config.recallTimeoutMs ?? DEFAULT_RECALL_TIMEOUT_MS;
356
+ this.preflightTimeoutMs = config.preflightTimeoutMs ?? DEFAULT_PREFLIGHT_TIMEOUT_MS;
265
357
  }
266
358
  /**
267
359
  * Create a new Walrus Memory client instance.
@@ -298,11 +390,13 @@ export class MemWal {
298
390
  /**
299
391
  * Submit a remember request and return as soon as the server accepts the job.
300
392
  */
301
- async rememberAsync(text, namespace, options = {}) {
302
- const resolvedNamespace = namespace ?? this.namespace;
393
+ async rememberAsync(text, namespaceOrOptions, options) {
394
+ assertNonBlankText(text);
395
+ const split = splitRememberArgs(namespaceOrOptions, options);
396
+ const resolvedNamespace = split.namespace ?? this.namespace;
303
397
  const requestIdentity = `${resolvedNamespace}\0${text}`;
304
- const generatedKey = options.idempotencyKey === undefined;
305
- const idempotencyKey = options.idempotencyKey
398
+ const generatedKey = split.options.idempotencyKey === undefined;
399
+ const idempotencyKey = split.options.idempotencyKey
306
400
  ?? this.pendingRememberKeys.get(requestIdentity)
307
401
  ?? (await derivedIdempotencyKey(requestIdentity));
308
402
  if (generatedKey)
@@ -322,7 +416,17 @@ export class MemWal {
322
416
  * resolves at the terminal state and hides progress.
323
417
  */
324
418
  async getRememberStatus(jobId) {
325
- const status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404]);
419
+ const path = rememberStatusPath(jobId);
420
+ if (path === undefined) {
421
+ return {
422
+ job_id: jobId,
423
+ status: "not_found",
424
+ error: `Job ${jobId} not found`,
425
+ };
426
+ }
427
+ const status = await this.signedRequest("GET", path, {}, [200, 404],
428
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
429
+ { includeDelegateKey: false });
326
430
  if (!("status" in status)) {
327
431
  return {
328
432
  job_id: jobId,
@@ -336,18 +440,34 @@ export class MemWal {
336
440
  * Poll an accepted remember job until it reaches a terminal state.
337
441
  */
338
442
  async waitForRememberJob(jobId, opts = {}) {
443
+ const path = rememberStatusPath(jobId);
444
+ if (path === undefined) {
445
+ throw Object.assign(new Error(`remember job not found: ${jobId}`), {
446
+ status: 404,
447
+ jobId,
448
+ });
449
+ }
339
450
  const { pollIntervalMs = 1500, timeoutMs = 60_000 } = opts;
340
451
  const deadline = Date.now() + timeoutMs;
341
452
  let attempt = 0;
342
453
  let retryAfterMs = 0;
343
- while (Date.now() < deadline) {
454
+ let sawRateLimit = false;
455
+ let lastSeen;
456
+ let lastRefusal;
457
+ while (true) {
344
458
  // A retry-after the server just gave us wins over our own curve;
345
459
  // the backoff resumes from where it was on the next normal poll.
346
- await sleep(retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++));
460
+ // Clamped to remaining budget so we never sleep past deadline (#1081).
461
+ const remainingBeforeSleep = Math.max(0, deadline - Date.now());
462
+ const requestedDelay = retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++);
347
463
  retryAfterMs = 0;
464
+ const delay = Math.min(requestedDelay, remainingBeforeSleep);
465
+ if (delay > 0) {
466
+ await sleep(delay);
467
+ }
348
468
  let status;
349
469
  try {
350
- status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404],
470
+ status = await this.signedRequest("GET", path, {}, [200, 404],
351
471
  // Bound each poll by the client deadline, and never past
352
472
  // what is left of the budget. Without this the loop only
353
473
  // checks the deadline between polls, so one stalled read
@@ -358,11 +478,17 @@ export class MemWal {
358
478
  // and the client deadline keeps ONE stalled poll from
359
479
  // swallowing the entire budget, so the loop still gets to
360
480
  // retry. An expired poll surfaces as a transient 504.
361
- { timeoutMs: this.pollDeadlineMs(deadline) });
481
+ { timeoutMs: this.pollDeadlineMs(deadline), includeDelegateKey: false });
362
482
  }
363
483
  catch (err) {
364
484
  const httpStatus = err.status ?? 0;
365
485
  if (isTransientPollingStatus(httpStatus)) {
486
+ lastRefusal = httpStatus;
487
+ if (httpStatus === 429)
488
+ sawRateLimit = true;
489
+ if (Date.now() >= deadline) {
490
+ break;
491
+ }
366
492
  retryAfterMs = retryAfterDelayMs(err, deadline);
367
493
  continue;
368
494
  }
@@ -374,6 +500,7 @@ export class MemWal {
374
500
  jobId,
375
501
  });
376
502
  }
503
+ lastSeen = status;
377
504
  if (status.status === "done") {
378
505
  return {
379
506
  id: status.job_id,
@@ -386,23 +513,29 @@ export class MemWal {
386
513
  if (status.status === "failed") {
387
514
  throw Object.assign(new Error(`remember job failed: ${redactInternalUrls(status.error ?? "unknown error")}`), { status: 500, jobId });
388
515
  }
516
+ if (Date.now() >= deadline) {
517
+ break;
518
+ }
389
519
  }
390
- throw Object.assign(new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})`), { status: 504, jobId });
520
+ throw rememberJobTimeoutError(jobId, timeoutMs, lastSeen, lastRefusal, sawRateLimit);
391
521
  }
392
522
  /**
393
523
  * Remember something and wait for the background job to complete.
394
524
  */
395
- async rememberAndWait(text, namespace, opts = {}) {
396
- const resolvedNamespace = namespace ?? this.namespace;
525
+ async rememberAndWait(text, namespaceOrOptions, opts) {
526
+ const split = splitRememberArgs(namespaceOrOptions, opts);
527
+ const resolvedNamespace = split.namespace ?? this.namespace;
397
528
  const requestIdentity = `${resolvedNamespace}\0${text}`;
398
- const generatedKey = opts.idempotencyKey === undefined;
399
- const idempotencyKey = opts.idempotencyKey
529
+ const generatedKey = split.options.idempotencyKey === undefined;
530
+ const idempotencyKey = split.options.idempotencyKey
400
531
  ?? this.pendingRememberKeys.get(requestIdentity)
401
532
  ?? (await derivedIdempotencyKey(requestIdentity));
402
533
  if (generatedKey)
403
534
  this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
535
+ // Pass the resolved string. rememberAsync would otherwise read the
536
+ // options object in this slot as a namespace. (#1142)
404
537
  const accepted = await this.rememberAsync(text, resolvedNamespace, { idempotencyKey });
405
- const completed = await this.waitForRememberJob(accepted.job_id, opts);
538
+ const completed = await this.waitForRememberJob(accepted.job_id, split.options);
406
539
  // Clear only after terminal success. A polling timeout/transport failure
407
540
  // keeps the key so retrying the high-level operation reuses the same job.
408
541
  if (generatedKey)
@@ -415,11 +548,11 @@ export class MemWal {
415
548
  * The relayer continues embedding, encrypting, uploading, and indexing in the background.
416
549
  * Use rememberAndWait() when the caller needs the final blob_id before continuing.
417
550
  *
418
- * @param text - The text to remember
419
- * @param namespace - Optional namespace override
551
+ * A plain object in the namespace position is options, so
552
+ * `remember(text, { idempotencyKey })` keeps the client namespace. (#1142)
420
553
  */
421
- async remember(text, namespace, options = {}) {
422
- return this.rememberAsync(text, namespace, options);
554
+ async remember(text, namespaceOrOptions, options) {
555
+ return this.rememberAsync(text, namespaceOrOptions, options);
423
556
  }
424
557
  /**
425
558
  * Remember multiple memories in one batched request (ENG-1408).
@@ -442,22 +575,40 @@ export class MemWal {
442
575
  * console.log(accepted.job_ids)
443
576
  * ```
444
577
  */
445
- async rememberBulkAsync(items) {
578
+ async rememberBulkAsync(items, options = {}) {
446
579
  if (!Array.isArray(items) || items.length === 0) {
447
580
  throw new Error("rememberBulkAsync: items must be a non-empty array");
448
581
  }
582
+ // The relayer rejects this after the request is signed. Say so first. (#1104)
583
+ if (items.length > MAX_BULK_ITEMS) {
584
+ throw new Error(`rememberBulkAsync: items exceeds maximum of ${MAX_BULK_ITEMS} per bulk request`);
585
+ }
586
+ items.forEach((item, i) => {
587
+ assertNonBlankText(item?.text, `items[${i}].text cannot be empty`);
588
+ });
449
589
  const normalised = items.map((item) => ({
450
590
  text: item.text,
451
591
  namespace: item.namespace ?? this.namespace,
452
592
  }));
453
- const accepted = await this.signedRequest("POST", "/api/remember/bulk", { items: normalised }, [200, 202]);
593
+ const requestIdentity = `bulk\0${normalised.map((item) => `${item.namespace}\0${item.text}`).join("\0\0")}`;
594
+ const generatedKey = options.idempotencyKey === undefined;
595
+ const idempotencyKey = options.idempotencyKey
596
+ ?? this.pendingRememberKeys.get(requestIdentity)
597
+ ?? (await derivedBulkIdempotencyKey(requestIdentity));
598
+ if (generatedKey)
599
+ this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
600
+ const accepted = await this.signedRequest("POST", "/api/remember/bulk", { items: normalised, idempotency_key: idempotencyKey }, [200, 202]);
601
+ if (generatedKey)
602
+ this.pendingRememberKeys.delete(requestIdentity);
454
603
  if (!accepted.job_ids || accepted.job_ids.length !== normalised.length) {
455
604
  throw new Error(`rememberBulkAsync: server returned ${accepted.job_ids?.length ?? 0} job_ids for ${normalised.length} items`);
456
605
  }
457
606
  return accepted;
458
607
  }
459
608
  async getRememberBulkStatus(jobIds, opts = {}) {
460
- return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200], { timeoutMs: opts.timeoutMs });
609
+ return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200],
610
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
611
+ { timeoutMs: opts.timeoutMs, includeDelegateKey: false });
461
612
  }
462
613
  async waitForRememberJobs(jobIds, namespaces = [], opts = {}) {
463
614
  const { pollIntervalMs = 1500, timeoutMs = 120_000 } = opts;
@@ -472,11 +623,64 @@ export class MemWal {
472
623
  const pending = new Set(jobIds);
473
624
  let attempt = 0;
474
625
  let retryAfterMs = 0;
475
- while (pending.size > 0 && Date.now() < deadline) {
626
+ let sawRateLimit = false;
627
+ const lastSeen = new Map();
628
+ let lastRefusal;
629
+ // Whether any status read got through. An item missing from an answer
630
+ // was not refused, so it must not be reported as if it had been.
631
+ let answered = false;
632
+ const settle = (jobId, status) => {
633
+ lastSeen.set(jobId, status);
634
+ // The same id can occupy more than one slot. `indexOf` updated only
635
+ // the first, and `pending` is a Set, so the copies stayed `timeout`.
636
+ // (#1121, #1084)
637
+ const terminal = status.status === "done" ||
638
+ status.status === "failed" ||
639
+ status.status === "not_found";
640
+ for (let idx = 0; idx < jobIds.length; idx++) {
641
+ if (jobIds[idx] !== jobId)
642
+ continue;
643
+ if (namespaces[idx] === undefined && status.namespace) {
644
+ results[idx].namespace = status.namespace;
645
+ }
646
+ if (!terminal)
647
+ continue;
648
+ // Caller namespace, then the job's own, then the client default. (#1136)
649
+ const namespace = namespaces[idx] ?? status.namespace ?? this.namespace;
650
+ if (status.status === "done") {
651
+ results[idx] = {
652
+ id: jobId,
653
+ blob_id: status.blob_id ?? "",
654
+ status: "done",
655
+ namespace,
656
+ };
657
+ }
658
+ else {
659
+ results[idx] = {
660
+ id: jobId,
661
+ blob_id: "",
662
+ status: "failed",
663
+ namespace,
664
+ error: status.status === "not_found"
665
+ ? "job not found"
666
+ : redactInternalUrls(status.error ?? "unknown error"),
667
+ };
668
+ }
669
+ }
670
+ if (terminal)
671
+ pending.delete(jobId);
672
+ };
673
+ while (pending.size > 0) {
476
674
  // A retry-after the server just gave us wins over our own curve;
477
675
  // the backoff resumes from where it was on the next normal poll.
478
- await sleep(retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++));
676
+ // Clamped to remaining budget so we never sleep past deadline (#1081).
677
+ const remainingBeforeSleep = Math.max(0, deadline - Date.now());
678
+ const requestedDelay = retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++);
479
679
  retryAfterMs = 0;
680
+ const delay = Math.min(requestedDelay, remainingBeforeSleep);
681
+ if (delay > 0) {
682
+ await sleep(delay);
683
+ }
480
684
  const pendingIds = jobIds.filter((jobId) => pending.has(jobId));
481
685
  if (pendingIds.length === 0) {
482
686
  break;
@@ -491,11 +695,18 @@ export class MemWal {
491
695
  catch (err) {
492
696
  const httpStatus = err.status ?? 0;
493
697
  if (isTransientPollingStatus(httpStatus)) {
698
+ lastRefusal = httpStatus;
699
+ if (httpStatus === 429)
700
+ sawRateLimit = true;
701
+ if (Date.now() >= deadline) {
702
+ break;
703
+ }
494
704
  retryAfterMs = retryAfterDelayMs(err, deadline);
495
705
  continue;
496
706
  }
497
707
  throw err;
498
708
  }
709
+ answered = true;
499
710
  const statusById = new Map();
500
711
  for (const item of batchStatus.results) {
501
712
  const bucket = statusById.get(item.job_id);
@@ -511,29 +722,49 @@ export class MemWal {
511
722
  if (!status) {
512
723
  continue;
513
724
  }
514
- const idx = jobIds.indexOf(jobId);
515
- if (status.status === "done") {
516
- results[idx] = {
517
- id: jobId,
518
- blob_id: status.blob_id ?? "",
519
- status: "done",
520
- namespace: namespaces[idx] ?? this.namespace,
521
- };
522
- pending.delete(jobId);
523
- }
524
- else if (status.status === "failed" || status.status === "not_found") {
525
- results[idx] = {
526
- id: jobId,
527
- blob_id: "",
528
- status: "failed",
529
- namespace: namespaces[idx] ?? this.namespace,
530
- error: status.status === "not_found"
531
- ? "job not found"
532
- : redactInternalUrls(status.error ?? "unknown error"),
533
- };
534
- pending.delete(jobId);
725
+ settle(jobId, status);
726
+ }
727
+ if (pending.size === 0 || Date.now() >= deadline) {
728
+ break;
729
+ }
730
+ }
731
+ // Nothing settled and nothing was even seen: the polls may all have been
732
+ // refused rather than the jobs being slow. Confirm with one direct read,
733
+ // as the MCP bridge does, before reporting anything.
734
+ if (timeoutMs > 0 && pending.size === jobIds.length && lastSeen.size === 0) {
735
+ try {
736
+ const probed = await this.getRememberBulkStatus(jobIds, {
737
+ timeoutMs: Math.min(this.requestTimeoutMs, CONFIRM_READ_TIMEOUT_MS),
738
+ });
739
+ answered = true;
740
+ for (const item of probed.results) {
741
+ if (pending.has(item.job_id))
742
+ settle(item.job_id, item);
535
743
  }
536
744
  }
745
+ catch (err) {
746
+ if (err.status === 429)
747
+ throw bulkRateLimitedError(err, jobIds);
748
+ // Any other probe failure is not evidence about the jobs.
749
+ }
750
+ }
751
+ for (let idx = 0; idx < jobIds.length; idx++) {
752
+ const jobId = jobIds[idx];
753
+ if (!pending.has(jobId))
754
+ continue;
755
+ const seen = lastSeen.get(jobId);
756
+ results[idx].error = seen
757
+ ? `still ${seen.status} after ${timeoutMs}ms` + (seen.error ? `: ${redactInternalUrls(seen.error)}` : "")
758
+ : answered
759
+ ? "not in the relayer's status answer; this item may not be stored"
760
+ : lastRefusal !== undefined
761
+ ? `no status read got through (last poll: HTTP ${lastRefusal}); this item may not be stored`
762
+ : `polling timed out after ${timeoutMs}ms`;
763
+ // Only the "no status read got through" message already names the 429.
764
+ const namesRateLimit = !seen && !answered && lastRefusal === 429;
765
+ if (sawRateLimit && !namesRateLimit) {
766
+ results[idx].error += "; wait hit a rate limit (429)";
767
+ }
537
768
  }
538
769
  const succeeded = results.filter((r) => r.status === "done").length;
539
770
  return {
@@ -546,53 +777,40 @@ export class MemWal {
546
777
  /**
547
778
  * Remember multiple memories and return as soon as the server accepts the jobs.
548
779
  */
549
- async rememberBulk(items) {
550
- return this.rememberBulkAsync(items);
780
+ async rememberBulk(items, options = {}) {
781
+ return this.rememberBulkAsync(items, options);
551
782
  }
552
783
  /**
553
784
  * Remember multiple memories and wait until every job reaches a terminal state.
554
785
  */
555
786
  async rememberBulkAndWait(items, opts = {}) {
556
- const namespaces = items.map((item) => item.namespace ?? this.namespace);
557
- const accepted = await this.rememberBulkAsync(items);
558
- return this.waitForRememberJobs(accepted.job_ids, namespaces, opts);
787
+ if (!Array.isArray(items) || items.length === 0) {
788
+ throw new Error("rememberBulkAsync: items must be a non-empty array");
789
+ }
790
+ if (items.length > MAX_BULK_ITEMS) {
791
+ throw new Error(`rememberBulkAsync: items exceeds maximum of ${MAX_BULK_ITEMS} per bulk request`);
792
+ }
793
+ items.forEach((item, i) => {
794
+ assertNonBlankText(item?.text, `items[${i}].text cannot be empty`);
795
+ });
796
+ const normalised = items.map((item) => ({
797
+ text: item.text,
798
+ namespace: item.namespace ?? this.namespace,
799
+ }));
800
+ const requestIdentity = `bulk\0${normalised.map((item) => `${item.namespace}\0${item.text}`).join("\0\0")}`;
801
+ const generatedKey = opts.idempotencyKey === undefined;
802
+ const idempotencyKey = opts.idempotencyKey
803
+ ?? this.pendingRememberKeys.get(requestIdentity)
804
+ ?? (await derivedBulkIdempotencyKey(requestIdentity));
805
+ if (generatedKey)
806
+ this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
807
+ const namespaces = normalised.map((item) => item.namespace);
808
+ const accepted = await this.rememberBulkAsync(items, { ...opts, idempotencyKey });
809
+ const completed = await this.waitForRememberJobs(accepted.job_ids, namespaces, opts);
810
+ if (generatedKey)
811
+ this.pendingRememberKeys.delete(requestIdentity);
812
+ return completed;
559
813
  }
560
- /**
561
- * Recall memories similar to a query — server handles:
562
- * verify → embed query → search → Walrus download → decrypt → return plaintext.
563
- *
564
- * **Preferred call style**: pass a single `RecallParams` object
565
- * so call sites read self-describingly:
566
- * ```ts
567
- * memwal.recall({ query: "food allergies", limit: 5, namespace: "profile" })
568
- * ```
569
- *
570
- * The legacy positional forms remain supported for backwards compatibility:
571
- * - `recall(query)`
572
- * - `recall(query, limit)`
573
- * - `recall(query, limit, namespace)`
574
- * - `recall(query, { limit, namespace, maxDistance, topK })`
575
- *
576
- * `topK` and `limit` are aliases; if both are set, `topK` wins.
577
- *
578
- * @returns RecallResult with decrypted text results
579
- *
580
- * @example
581
- * ```typescript
582
- * // Object style — recommended
583
- * const result = await memwal.recall({
584
- * query: "food allergies",
585
- * limit: 5,
586
- * namespace: "profile",
587
- * });
588
- * for (const memory of result.results) {
589
- * console.log(memory.text, memory.distance);
590
- * }
591
- *
592
- * // Positional style — still works
593
- * const result2 = await memwal.recall("food allergies", 5, "profile");
594
- * ```
595
- */
596
814
  /**
597
815
  * Estimate the token cost of a string using the SDK's default
598
816
  * character-based approximation (~chars/4, code-point aware). Useful to weigh
@@ -612,61 +830,60 @@ export class MemWal {
612
830
  return estimateTokens(text);
613
831
  }
614
832
  async recall(queryOrParams, limitOrOptions = 10, namespace) {
615
- let query;
616
- let options;
617
- if (typeof queryOrParams === "object") {
618
- const { query: q, ...rest } = queryOrParams;
619
- query = q;
620
- options = rest;
833
+ const { query, options } = resolveRecallCall(queryOrParams, limitOrOptions, namespace);
834
+ validateMaxTokens(options.maxTokens);
835
+ const rawLimit = options.topK !== undefined ? options.topK : options.limit;
836
+ const limit = rawLimit !== undefined ? rawLimit : 10;
837
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
838
+ throw new TypeError(`limit must be a positive integer, got ${limit}`);
621
839
  }
622
- else {
623
- query = queryOrParams;
624
- if (limitOrOptions == null) {
625
- options = { limit: 10, namespace };
626
- }
627
- else if (typeof limitOrOptions === "number") {
628
- options = { limit: limitOrOptions, namespace };
629
- }
630
- else {
631
- options = limitOrOptions;
632
- }
633
- }
634
- const limit = options.topK ?? options.limit ?? 10;
635
840
  const resolvedNamespace = options.namespace ?? this.namespace;
636
841
  {
842
+ // WALM-598: this budget is handed to `signedRequest`, which starts
843
+ // the clock on the `/api/recall` fetch itself — after
844
+ // `ensureCompatibleRelayer` (`/version`, falling back to `/health`)
845
+ // and `buildSealSession` (`/config` + Sui RPC) have already
846
+ // resolved. Those preflights carry their own independent
847
+ // deadlines, so a relayer whose `/health` p50 had crept to ~9s can
848
+ // no longer eat most of recall's window and make a perfectly
849
+ // healthy recall surface an `AbortError` (GH #438).
850
+ const budget = options.timeoutMs ?? this.recallTimeoutMs;
851
+ const optedOut = typeof budget !== "number" || !Number.isFinite(budget) || budget <= 0;
852
+ const timeoutMs = optedOut ? 0 : budget;
853
+ const wireDeadline = optedOut
854
+ ? undefined
855
+ : (timeoutMs > RECALL_DEADLINE_MARGIN_MS
856
+ ? timeoutMs - RECALL_DEADLINE_MARGIN_MS
857
+ : timeoutMs);
637
858
  const result = await this.signedRequest("POST", "/api/recall", {
638
859
  query,
639
860
  limit,
640
861
  namespace: resolvedNamespace,
641
- // `undefined` when no weights were supplied, which
642
- // JSON.stringify drops — so a default-weighted recall stays
643
- // byte-identical on the wire and the relayer keeps
644
- // short-circuiting to the plain pgvector cosine order.
645
862
  scoring_weights: scoringWeightsToWire(options.scoringWeights),
646
- // Same `undefined`-is-dropped trick: an unset sort leaves the
647
- // request byte-identical and the relayer applies its own
648
- // "relevance" default.
649
863
  sort: options.sort,
650
- }, { timeoutMs: RECALL_REQUEST_TIMEOUT_MS });
864
+ ...(wireDeadline === undefined ? {} : { deadline_ms: wireDeadline }),
865
+ }, { timeoutMs });
651
866
  let processed = result;
652
867
  if (typeof options.maxDistance === "number") {
653
868
  const filtered = result.results.filter((memory) => memory.distance < options.maxDistance);
869
+ // Keep the relayer's matching total so callers can distinguish
870
+ // "no memories exist" from "matches exist but were outside maxDistance" (#1066).
654
871
  processed = {
655
872
  ...processed,
656
873
  results: filtered,
657
- total: filtered.length,
658
874
  };
659
875
  }
660
- // Client-side token budgeting: trim the (already distance-sorted)
661
- // payload to fit maxTokens per the chosen strategy, and attach the
662
- // token estimate + truncated flag. Omitting maxTokens leaves the
663
- // result byte-identical to the pre-budget behavior (no meta).
664
- if (typeof options.maxTokens === "number") {
876
+ // Client-side token budgeting: trim the payload to fit maxTokens per
877
+ // the chosen strategy, and attach the token estimate + truncated flag.
878
+ // Under high-relevance-only, lowest-distance hits are retained and
879
+ // returned in the caller's requested order (WALM-756).
880
+ // Omitting maxTokens leaves the result byte-identical to the pre-budget
881
+ // behavior (no meta). Total preserves the matching hit count (#1068).
882
+ if (options.maxTokens !== undefined) {
665
883
  const { results: budgeted, meta } = applyTokenBudget(processed.results, options.maxTokens, options.truncationStrategy, options.countTokens);
666
884
  processed = {
667
885
  ...processed,
668
886
  results: budgeted,
669
- total: budgeted.length,
670
887
  meta,
671
888
  };
672
889
  }
@@ -734,9 +951,13 @@ export class MemWal {
734
951
  * ```
735
952
  */
736
953
  async recallManual(opts) {
954
+ const limit = opts.limit !== undefined ? opts.limit : 10;
955
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
956
+ throw new TypeError(`limit must be a positive integer, got ${limit}`);
957
+ }
737
958
  return this.signedRequest("POST", "/api/recall/manual", {
738
959
  vector: opts.vector,
739
- limit: opts.limit ?? 10,
960
+ limit,
740
961
  namespace: opts.namespace ?? this.namespace,
741
962
  scoring_weights: scoringWeightsToWire(opts.scoringWeights),
742
963
  }, { includeDelegateKey: false });
@@ -748,6 +969,7 @@ export class MemWal {
748
969
  * @returns EmbedResult with vector
749
970
  */
750
971
  async embed(text) {
972
+ assertNonBlankText(text, "text cannot be empty");
751
973
  return this.signedRequest("POST", "/api/embed", { text }, { includeDelegateKey: false });
752
974
  }
753
975
  /**
@@ -766,6 +988,7 @@ export class MemWal {
766
988
  * ```
767
989
  */
768
990
  async analyze(text, namespaceOrOptions) {
991
+ assertNonBlankText(text);
769
992
  const options = normalizeAnalyzeOptions(namespaceOrOptions);
770
993
  const body = {
771
994
  text,
@@ -839,6 +1062,9 @@ export class MemWal {
839
1062
  * ```
840
1063
  */
841
1064
  async restore(namespace, limit = 10) {
1065
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) {
1066
+ throw new TypeError(`limit must be a positive integer, got ${limit}`);
1067
+ }
842
1068
  const result = await this.signedRequest("POST", "/api/restore", { namespace, limit }, [200], { timeoutMs: RESTORE_REQUEST_TIMEOUT_MS });
843
1069
  // Relayers older than WALM-319 omit `truncated` entirely — treat
844
1070
  // "not present" as "not known to be truncated" rather than drop
@@ -889,6 +1115,58 @@ export class MemWal {
889
1115
  includeDelegateKey: false,
890
1116
  });
891
1117
  }
1118
+ /**
1119
+ * List the memories this account holds, without a semantic query.
1120
+ *
1121
+ * Recall is similarity-ranked and limit-bounded, so it cannot confirm a
1122
+ * write or count a namespace. This walks the full inventory instead.
1123
+ * Returns metadata only — no blob fetch, no decryption; use `recall()`
1124
+ * for content.
1125
+ *
1126
+ * `namespace` is filtered client-side: the relayer lists every namespace,
1127
+ * so a filtered page can be short or empty while `has_more` is true.
1128
+ * Paginate with `has_more`, NOT page length.
1129
+ *
1130
+ * ```ts
1131
+ * let cursor: string | undefined;
1132
+ * let more = true;
1133
+ * let count = 0;
1134
+ * while (more) {
1135
+ * const page = await memwal.listMemories({ cursor, namespace: "work" });
1136
+ * count += page.memories.length;
1137
+ * cursor = page.next_cursor ?? undefined;
1138
+ * more = page.has_more;
1139
+ * }
1140
+ * ```
1141
+ */
1142
+ async listMemories(options = {}) {
1143
+ const owner = await this.resolveOwner();
1144
+ const params = new URLSearchParams();
1145
+ if (options.cursor !== undefined)
1146
+ params.set("updated_after", options.cursor);
1147
+ if (options.limit !== undefined)
1148
+ params.set("limit", String(options.limit));
1149
+ const query = params.toString();
1150
+ // Query string must be part of the signed path (see listNamespaces).
1151
+ const path = `/v1/owners/${owner}/memories${query ? `?${query}` : ""}`;
1152
+ const raw = await this.signedRequest("GET", path, {}, [200], {
1153
+ includeDelegateKey: false,
1154
+ });
1155
+ // Relayers older than WALM-363 omit the tombstone fields.
1156
+ const page = {
1157
+ ...raw,
1158
+ deleted: raw.deleted ?? [],
1159
+ must_resync: raw.must_resync ?? false,
1160
+ };
1161
+ if (options.namespace === undefined)
1162
+ return page;
1163
+ const namespace = options.namespace;
1164
+ return {
1165
+ ...page,
1166
+ memories: page.memories.filter((m) => m.namespace_id === namespace),
1167
+ deleted: page.deleted.filter((d) => d.namespace_id === namespace),
1168
+ };
1169
+ }
892
1170
  /**
893
1171
  * Resolve this account's owner address, memoised for the client's life.
894
1172
  *
@@ -927,11 +1205,11 @@ export class MemWal {
927
1205
  * Check server health. The endpoint is public and does not require request signing.
928
1206
  */
929
1207
  async health() {
930
- const res = await this.fetchWithDeadline(`${this.serverUrl}/health`);
1208
+ const res = await this.fetchWithDeadline(`${this.serverUrl}/health`, {}, this.preflightTimeoutMs, "GET /health");
931
1209
  if (!res.ok) {
932
1210
  throw new Error(`Health check failed: ${res.status}`);
933
1211
  }
934
- return res.json();
1212
+ return res.body;
935
1213
  }
936
1214
  /**
937
1215
  * Fetch and validate the relayer compatibility contract.
@@ -944,17 +1222,32 @@ export class MemWal {
944
1222
  */
945
1223
  async getPublicKeyHex() {
946
1224
  const pk = await this.getPublicKey();
1225
+ // `await` yields even when the key was already cached. destroy()
1226
+ // zero-fills that cache in place, so encode only after a fresh check
1227
+ // or this resolves to 64 zero hex chars. (#1090)
1228
+ if (this.destroyed)
1229
+ throw destroyedClientError();
947
1230
  return bytesToHex(pk);
948
1231
  }
949
1232
  // ============================================================
950
1233
  // Internal: Signed HTTP Requests
951
1234
  // ============================================================
952
1235
  async getPublicKey() {
1236
+ // destroy() zero-fills the cache in place, and an uncached key would
1237
+ // otherwise derive the well-known key of the all-zero seed. Re-check
1238
+ // after every await, and never cache a key derived once wiped. (#1090)
1239
+ if (this.destroyed)
1240
+ throw destroyedClientError();
953
1241
  if (!this.publicKey) {
954
1242
  const ed = await getEd();
955
- this.publicKey = await ed.getPublicKeyAsync(this.privateKey);
1243
+ if (this.destroyed)
1244
+ throw destroyedClientError();
1245
+ const derived = await ed.getPublicKeyAsync(this.privateKey);
1246
+ if (this.destroyed)
1247
+ throw destroyedClientError();
1248
+ this.publicKey = derived;
956
1249
  }
957
- return this.publicKey;
1250
+ return this.publicKey.slice();
958
1251
  }
959
1252
  async ensureCompatibleRelayer() {
960
1253
  if (this.relayerVersionMetadata)
@@ -967,18 +1260,22 @@ export class MemWal {
967
1260
  return this.compatibilityPromise;
968
1261
  }
969
1262
  async fetchCompatibilityMetadata() {
970
- const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" });
1263
+ // WALM-598: both round-trips get their own bounded budget. They run
1264
+ // inside whatever signed request triggered the compatibility probe, so
1265
+ // leaving them untimed let a stalled relayer silently drain that
1266
+ // caller's deadline (and, with no signal at all, hang indefinitely).
1267
+ const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" }, this.preflightTimeoutMs, "preflight GET /version");
971
1268
  let body;
972
1269
  if (versionRes.ok) {
973
- body = (await versionRes.json());
1270
+ body = versionRes.body;
974
1271
  }
975
1272
  else if (versionRes.status === 404 || versionRes.status === 405) {
976
- const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" });
1273
+ const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" }, this.preflightTimeoutMs, "preflight GET /health");
977
1274
  if (!healthRes.ok) {
978
1275
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ` +
979
1276
  `${versionRes.status}, and GET /health returned ${healthRes.status}`);
980
1277
  }
981
- body = (await healthRes.json());
1278
+ body = healthRes.body;
982
1279
  }
983
1280
  else {
984
1281
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ${versionRes.status}`);
@@ -1011,11 +1308,13 @@ export class MemWal {
1011
1308
  async fetchServerConfig() {
1012
1309
  if (this.serverConfig)
1013
1310
  return this.serverConfig;
1014
- const res = await this.fetchWithDeadline(`${this.serverUrl}/config`, { method: "GET" });
1311
+ // WALM-598: bounded like the other preflights — this one is awaited
1312
+ // inside `buildSealSession`, itself awaited inside a caller's budget.
1313
+ const res = await this.fetchWithDeadline(`${this.serverUrl}/config`, { method: "GET" }, this.preflightTimeoutMs, "preflight GET /config");
1015
1314
  if (!res.ok) {
1016
1315
  throw new Error(`GET /config returned ${res.status}`);
1017
1316
  }
1018
- const body = (await res.json());
1317
+ const body = res.body;
1019
1318
  if (typeof body.packageId !== "string" || !body.packageId ||
1020
1319
  typeof body.network !== "string" || !body.network) {
1021
1320
  throw new Error("GET /config response missing packageId / network");
@@ -1211,7 +1510,7 @@ export class MemWal {
1211
1510
  * Pass [200, 202] for endpoints that return 202 Accepted.
1212
1511
  */
1213
1512
  /**
1214
- * `fetch` with this client's deadline applied.
1513
+ * `fetch` plus the JSON body read, with this client's deadline applied across both.
1215
1514
  *
1216
1515
  * For the handshake endpoints that skip request signing — `/health`,
1217
1516
  * `/version`, `/config`. They are the worst place to leave unbounded: the
@@ -1219,19 +1518,31 @@ export class MemWal {
1219
1518
  * one stalled socket there hangs every method on the client, not just one.
1220
1519
  */
1221
1520
  /** Deadline for one status poll: the client deadline, clamped so it can
1222
- * never outlive the wait budget it belongs to. */
1521
+ * never outlive the wait budget it belongs to, but given a usable minimum
1522
+ * at or past the deadline so a boundary check does not fail with an
1523
+ * artificial 1ms AbortError (#1081). */
1223
1524
  pollDeadlineMs(deadline) {
1224
- return Math.max(1, Math.min(this.requestTimeoutMs, deadline - Date.now()));
1525
+ const remaining = deadline - Date.now();
1526
+ const minPollTimeout = Math.min(this.requestTimeoutMs, 1_000);
1527
+ if (remaining <= 0) {
1528
+ return minPollTimeout;
1529
+ }
1530
+ return Math.min(this.requestTimeoutMs, Math.max(remaining, minPollTimeout));
1225
1531
  }
1226
- async fetchWithDeadline(url, init = {}, timeoutMs) {
1532
+ async fetchWithDeadline(url, init = {}, timeoutMs, phase) {
1227
1533
  const ms = timeoutMs ?? this.requestTimeoutMs;
1228
1534
  const deadline = deadlineSignal(ms);
1229
1535
  try {
1230
- return await fetch(url, { ...init, signal: deadline.signal });
1536
+ const res = await fetch(url, { ...init, signal: deadline.signal });
1537
+ return {
1538
+ ok: res.ok,
1539
+ status: res.status,
1540
+ body: res.ok ? (await res.json()) : undefined,
1541
+ };
1231
1542
  }
1232
1543
  catch (err) {
1233
1544
  if (deadline.timedOut()) {
1234
- throw requestTimeoutError(init.method ?? "GET", url, ms);
1545
+ throw requestTimeoutError(init.method ?? "GET", url, ms, phase);
1235
1546
  }
1236
1547
  throw err;
1237
1548
  }
@@ -1246,6 +1557,9 @@ export class MemWal {
1246
1557
  const options = Array.isArray(acceptedStatusesOrOptions)
1247
1558
  ? requestOptions
1248
1559
  : acceptedStatusesOrOptions;
1560
+ // Before the version probe. A destroyed client must not open GET /version. (#1090)
1561
+ if (this.destroyed)
1562
+ throw destroyedClientError();
1249
1563
  await this.ensureCompatibleRelayer();
1250
1564
  const ed = await getEd();
1251
1565
  const timestamp = Math.floor(Date.now() / 1000).toString();
@@ -1260,12 +1574,19 @@ export class MemWal {
1260
1574
  // LOW-23: Build message to sign — now includes nonce AND account id
1261
1575
  const message = `${timestamp}.${method}.${path}.${bodySha256}.${nonce}.${this.accountId}`;
1262
1576
  const msgBytes = new TextEncoder().encode(message);
1263
- if (this.destroyed) {
1264
- throw new Error("Walrus Memory client was destroyed; its keys are zeroed. Create a new one.");
1265
- }
1577
+ // Again after the version await. A destroy that lands while that
1578
+ // request is in flight must still refuse to sign. (#1090)
1579
+ if (this.destroyed)
1580
+ throw destroyedClientError();
1266
1581
  // Sign with Ed25519
1267
1582
  const signature = await ed.signAsync(msgBytes, this.privateKey);
1583
+ // destroy() during the sign, or during public-key derivation, must
1584
+ // not reach fetch with the wiped seed's well-known key. (#1090)
1585
+ if (this.destroyed)
1586
+ throw destroyedClientError();
1268
1587
  const publicKey = await this.getPublicKey();
1588
+ if (this.destroyed)
1589
+ throw destroyedClientError();
1269
1590
  // Make HTTP request
1270
1591
  const url = `${this.serverUrl}${path}`;
1271
1592
  const headers = {
@@ -1283,56 +1604,73 @@ export class MemWal {
1283
1604
  if (options.includeDelegateKey !== false) {
1284
1605
  headers["x-seal-session"] = await this.buildSealSession();
1285
1606
  }
1286
- // Bound the request. `fetch` never times out on its own, so this is the
1287
- // only thing standing between a stalled socket and a call that hangs
1288
- // for as long as the connection stays open.
1289
- const deadlineMs = options.timeoutMs ?? this.requestTimeoutMs;
1290
- const deadline = deadlineSignal(deadlineMs, options.signal);
1291
- let res;
1607
+ // WALM-598: the caller's deadline starts HERE, not at the top of the
1608
+ // call. Everything above — `ensureCompatibleRelayer()` (`/version` ->
1609
+ // `/health`) and `buildSealSession()` (`/config`, dynamic imports, a
1610
+ // Sui RPC round-trip for `SessionKey.create`) — is preflight work that
1611
+ // used to run inside the caller's budget while being unabortable
1612
+ // itself. Each of those now carries its own independent deadline.
1613
+ //
1614
+ // `fetch` never times out on its own, so this deadline is also the only
1615
+ // thing standing between a stalled socket and a call that hangs for as
1616
+ // long as the connection stays open.
1617
+ const explicitTimeout = options.timeoutMs;
1618
+ const deadlineOptOut = typeof explicitTimeout === "number"
1619
+ && (!Number.isFinite(explicitTimeout) || explicitTimeout <= 0);
1620
+ const deadlineMs = deadlineOptOut
1621
+ ? undefined
1622
+ : (explicitTimeout ?? this.requestTimeoutMs);
1623
+ const deadline = deadlineMs === undefined
1624
+ ? undefined
1625
+ : deadlineSignal(deadlineMs, options.signal);
1292
1626
  try {
1293
- res = await fetch(url, {
1627
+ const res = await fetch(url, {
1294
1628
  method,
1295
1629
  headers,
1296
1630
  body: method === "GET" ? undefined : bodyStr,
1297
- signal: deadline.signal,
1631
+ signal: deadline?.signal ?? options.signal,
1298
1632
  });
1633
+ if (!acceptedStatuses.includes(res.status)) {
1634
+ // LOW-26: sanitize server error bodies before surfacing to callers.
1635
+ const raw = await res.text();
1636
+ const compatibilityError = compatibilityErrorFromStatus(res.status, raw);
1637
+ if (compatibilityError)
1638
+ throw compatibilityError;
1639
+ // A stale/future-dated signature is rejected with 401 + a machine-
1640
+ // readable reason header. Surface it as an actionable clock-drift
1641
+ // error rather than an opaque 401 so the caller can fix node time.
1642
+ const clockDriftError = clockDriftErrorFromResponse(res);
1643
+ if (clockDriftError)
1644
+ throw clockDriftError;
1645
+ const { message, serverCode } = sanitizeServerError(res.status, raw, res.headers.get("x-auth-error"));
1646
+ const err = new Error(message);
1647
+ err.status = res.status;
1648
+ if (serverCode)
1649
+ err.serverCode = serverCode;
1650
+ const retryAfter = Number(res.headers.get("retry-after"));
1651
+ if (Number.isFinite(retryAfter) && retryAfter > 0) {
1652
+ err.retryAfterSeconds = retryAfter;
1653
+ }
1654
+ // Preserve raw body on `cause` for in-process debugging only.
1655
+ err.cause = raw;
1656
+ throw err;
1657
+ }
1658
+ return (await res.json());
1299
1659
  }
1300
1660
  catch (err) {
1301
1661
  // Translate our own expiry into something a caller can classify.
1302
1662
  // An abort the CALLER asked for is theirs and propagates untouched.
1303
- if (deadline.timedOut())
1304
- throw requestTimeoutError(method, path, deadlineMs);
1663
+ const status = err && typeof err === "object" && "status" in err
1664
+ ? err.status
1665
+ : undefined;
1666
+ if (deadline?.timedOut() && typeof status !== "number") {
1667
+ throw requestTimeoutError(method, path, deadlineMs ?? 0);
1668
+ }
1305
1669
  throw err;
1306
1670
  }
1307
1671
  finally {
1308
- deadline.dispose();
1309
- }
1310
- if (!acceptedStatuses.includes(res.status)) {
1311
- // LOW-26: sanitize server error bodies before surfacing to callers.
1312
- const raw = await res.text();
1313
- const compatibilityError = compatibilityErrorFromStatus(res.status, raw);
1314
- if (compatibilityError)
1315
- throw compatibilityError;
1316
- // A stale/future-dated signature is rejected with 401 + a machine-
1317
- // readable reason header. Surface it as an actionable clock-drift
1318
- // error rather than an opaque 401 so the caller can fix node time.
1319
- const clockDriftError = clockDriftErrorFromResponse(res);
1320
- if (clockDriftError)
1321
- throw clockDriftError;
1322
- const { message, serverCode } = sanitizeServerError(res.status, raw, res.headers.get("x-auth-error"));
1323
- const err = new Error(message);
1324
- err.status = res.status;
1325
- if (serverCode)
1326
- err.serverCode = serverCode;
1327
- const retryAfter = Number(res.headers.get("retry-after"));
1328
- if (Number.isFinite(retryAfter) && retryAfter > 0) {
1329
- err.retryAfterSeconds = retryAfter;
1330
- }
1331
- // Preserve raw body on `cause` for in-process debugging only.
1332
- err.cause = raw;
1333
- throw err;
1672
+ deadline?.dispose();
1334
1673
  }
1335
- return res.json();
1336
1674
  }
1337
1675
  }
1338
1676
  //# sourceMappingURL=memwal.js.map