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

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