@mysten-incubation/memwal 0.1.8-dev.1 → 0.1.8-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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, } from "./utils.js";
31
31
  import { assertCompatibleRelayer, compatibilityErrorFromStatus, } from "./compatibility.js";
32
32
  import { applyTokenBudget, estimateTokens } 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
  // ============================================================
@@ -48,12 +50,6 @@ const SEAL_SESSION_SAFETY_MARGIN_MS = 30_000;
48
50
  function sleep(ms) {
49
51
  return new Promise((resolve) => setTimeout(resolve, ms));
50
52
  }
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
53
  /** Window over which the same (namespace, text) resolves to one key.
58
54
  *
59
55
  * `pendingRememberKeys` only dedupes retries that reuse one client instance,
@@ -72,6 +68,30 @@ async function derivedIdempotencyKey(requestIdentity) {
72
68
  * so one stalled read ran past `timeoutMs` entirely. 30s mirrors the relayer's
73
69
  * own outbound client. */
74
70
  const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
71
+ /** The one confirming read a bulk wait makes after its budget is spent. It
72
+ * runs past the caller's deadline by design, so it gets a short bound of its
73
+ * own rather than the 30s default a stalled socket would hold it for. */
74
+ const CONFIRM_READ_TIMEOUT_MS = 5_000;
75
+ /** Matches the relayer's `MAX_BULK_ITEMS`. Reject before a signed request. */
76
+ const MAX_BULK_ITEMS = 20;
77
+ /**
78
+ * `remember(text, { idempotencyKey })` is the natural call when the namespace
79
+ * stays at the client default. A plain object in the namespace slot is those
80
+ * options, not a namespace name. (#1142)
81
+ */
82
+ function splitRememberArgs(namespaceOrOptions, options) {
83
+ // The third argument is the dedicated options bag. When the namespace
84
+ // slot is also an object, keep both and let the bag win on a clash.
85
+ // `rememberAndWait(text, { timeoutMs }, { idempotencyKey })` is typed
86
+ // and used to drop the key, so a retry minted a second blob. (#1142)
87
+ if (typeof namespaceOrOptions === "object" && namespaceOrOptions !== null) {
88
+ return { namespace: undefined, options: { ...namespaceOrOptions, ...options } };
89
+ }
90
+ return { namespace: namespaceOrOptions, options: options ?? {} };
91
+ }
92
+ function destroyedClientError() {
93
+ return new Error("Walrus Memory client was destroyed; its keys are zeroed. Create a new one.");
94
+ }
75
95
  /** `POST /api/restore` bounds itself at 55s server-side and answers with an
76
96
  * error rather than going quiet, so the client must outlast that or it would
77
97
  * abandon a response already on its way. */
@@ -82,6 +102,13 @@ const ANALYZE_REQUEST_TIMEOUT_MS = 60_000;
82
102
  /** `POST /api/recall` has carried its own 15s deadline since before the rest
83
103
  * had any; keeping it named makes that a decision rather than an accident. */
84
104
  const RECALL_REQUEST_TIMEOUT_MS = 15_000;
105
+ /** What `recall()` tells the relayer it will wait, so the 504 naming the stuck
106
+ * stage arrives before the abort above rather than after it. A second under
107
+ * that abort because the two clocks start at different moments: this timer
108
+ * starts before `fetch`, the relayer's when the request lands, and the margin
109
+ * the relayer keeps for its reply cannot also cover DNS, TCP and TLS. Derived
110
+ * from the timeout so the two can never drift apart. */
111
+ const RECALL_DEADLINE_MS = RECALL_REQUEST_TIMEOUT_MS - 1_000;
85
112
  /**
86
113
  * Abort signal that fires after `ms`, or when `caller` aborts — whichever is
87
114
  * first. Built by hand rather than with `AbortSignal.any`, which lands too
@@ -157,6 +184,24 @@ function retryAfterDelayMs(err, deadline) {
157
184
  return 0;
158
185
  return Math.max(0, Math.min(seconds * 1000, deadline - Date.now()));
159
186
  }
187
+ /**
188
+ * Thrown when a bulk wait could not read a single status, the confirming read
189
+ * included. The status endpoint counts against the same delegate-key budget
190
+ * as writes, so a batch sent near the limit can have every poll refused. The
191
+ * old result then read as "still uploading" even when nothing had landed
192
+ * (GH #967). A refusal says nothing about the jobs, so do not report it as
193
+ * progress.
194
+ */
195
+ function bulkRateLimitedError(err, jobIds) {
196
+ const retryAfterSeconds = err.retryAfterSeconds
197
+ ?? retryAfterSecondsFromBody(err.cause);
198
+ const wait = retryAfterSeconds ? ` after ~${Math.ceil(retryAfterSeconds)}s` : "";
199
+ const e = new Error(`Walrus Memory rate-limited every status read for this batch, so none of its ${jobIds.length} writes ` +
200
+ `could be confirmed. Do not treat them as stored: check them with getRememberBulkStatus(jobIds)${wait}. ` +
201
+ `Status reads count against the same delegate-key budget as writes.`);
202
+ e.name = "MemWalRateLimited";
203
+ return Object.assign(e, { status: 429, jobIds, retryAfterSeconds });
204
+ }
160
205
  /**
161
206
  * The relayer states the backoff in the 429 body as well as in `Retry-After`.
162
207
  * A proxy that strips the header must not cost us the hint.
@@ -219,6 +264,7 @@ function normalizeSuiNetworkForGrpc(network) {
219
264
  export class MemWal {
220
265
  privateKey;
221
266
  publicKey = null;
267
+ destroyed = false;
222
268
  serverUrl;
223
269
  namespace;
224
270
  accountId;
@@ -276,6 +322,7 @@ export class MemWal {
276
322
  * Prevents key extraction from V8 heap dumps.
277
323
  */
278
324
  destroy() {
325
+ this.destroyed = true;
279
326
  if (this.privateKey) {
280
327
  this.privateKey.fill(0);
281
328
  }
@@ -296,11 +343,13 @@ export class MemWal {
296
343
  /**
297
344
  * Submit a remember request and return as soon as the server accepts the job.
298
345
  */
299
- async rememberAsync(text, namespace, options = {}) {
300
- const resolvedNamespace = namespace ?? this.namespace;
346
+ async rememberAsync(text, namespaceOrOptions, options) {
347
+ assertNonBlankText(text);
348
+ const split = splitRememberArgs(namespaceOrOptions, options);
349
+ const resolvedNamespace = split.namespace ?? this.namespace;
301
350
  const requestIdentity = `${resolvedNamespace}\0${text}`;
302
- const generatedKey = options.idempotencyKey === undefined;
303
- const idempotencyKey = options.idempotencyKey
351
+ const generatedKey = split.options.idempotencyKey === undefined;
352
+ const idempotencyKey = split.options.idempotencyKey
304
353
  ?? this.pendingRememberKeys.get(requestIdentity)
305
354
  ?? (await derivedIdempotencyKey(requestIdentity));
306
355
  if (generatedKey)
@@ -320,7 +369,18 @@ export class MemWal {
320
369
  * resolves at the terminal state and hides progress.
321
370
  */
322
371
  async getRememberStatus(jobId) {
323
- const status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404]);
372
+ // `GET /api/remember/` is not a route. The relayer answers 404 with an
373
+ // empty body, and parsing that threw SyntaxError. (#1087)
374
+ if (typeof jobId !== "string" || jobId.length === 0) {
375
+ return {
376
+ job_id: jobId,
377
+ status: "not_found",
378
+ error: `Job ${jobId} not found`,
379
+ };
380
+ }
381
+ const status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404],
382
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
383
+ { includeDelegateKey: false });
324
384
  if (!("status" in status)) {
325
385
  return {
326
386
  job_id: jobId,
@@ -334,10 +394,17 @@ export class MemWal {
334
394
  * Poll an accepted remember job until it reaches a terminal state.
335
395
  */
336
396
  async waitForRememberJob(jobId, opts = {}) {
397
+ if (typeof jobId !== "string" || jobId.length === 0) {
398
+ throw Object.assign(new Error(`remember job not found: ${jobId}`), {
399
+ status: 404,
400
+ jobId,
401
+ });
402
+ }
337
403
  const { pollIntervalMs = 1500, timeoutMs = 60_000 } = opts;
338
404
  const deadline = Date.now() + timeoutMs;
339
405
  let attempt = 0;
340
406
  let retryAfterMs = 0;
407
+ let sawRateLimit = false;
341
408
  while (Date.now() < deadline) {
342
409
  // A retry-after the server just gave us wins over our own curve;
343
410
  // the backoff resumes from where it was on the next normal poll.
@@ -356,11 +423,13 @@ export class MemWal {
356
423
  // and the client deadline keeps ONE stalled poll from
357
424
  // swallowing the entire budget, so the loop still gets to
358
425
  // retry. An expired poll surfaces as a transient 504.
359
- { timeoutMs: this.pollDeadlineMs(deadline) });
426
+ { timeoutMs: this.pollDeadlineMs(deadline), includeDelegateKey: false });
360
427
  }
361
428
  catch (err) {
362
429
  const httpStatus = err.status ?? 0;
363
430
  if (isTransientPollingStatus(httpStatus)) {
431
+ if (httpStatus === 429)
432
+ sawRateLimit = true;
364
433
  retryAfterMs = retryAfterDelayMs(err, deadline);
365
434
  continue;
366
435
  }
@@ -385,22 +454,26 @@ export class MemWal {
385
454
  throw Object.assign(new Error(`remember job failed: ${redactInternalUrls(status.error ?? "unknown error")}`), { status: 500, jobId });
386
455
  }
387
456
  }
388
- throw Object.assign(new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})`), { status: 504, jobId });
457
+ throw Object.assign(new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})` +
458
+ (sawRateLimit ? "; wait hit a rate limit (429)" : "")), { status: 504, jobId });
389
459
  }
390
460
  /**
391
461
  * Remember something and wait for the background job to complete.
392
462
  */
393
- async rememberAndWait(text, namespace, opts = {}) {
394
- const resolvedNamespace = namespace ?? this.namespace;
463
+ async rememberAndWait(text, namespaceOrOptions, opts) {
464
+ const split = splitRememberArgs(namespaceOrOptions, opts);
465
+ const resolvedNamespace = split.namespace ?? this.namespace;
395
466
  const requestIdentity = `${resolvedNamespace}\0${text}`;
396
- const generatedKey = opts.idempotencyKey === undefined;
397
- const idempotencyKey = opts.idempotencyKey
467
+ const generatedKey = split.options.idempotencyKey === undefined;
468
+ const idempotencyKey = split.options.idempotencyKey
398
469
  ?? this.pendingRememberKeys.get(requestIdentity)
399
470
  ?? (await derivedIdempotencyKey(requestIdentity));
400
471
  if (generatedKey)
401
472
  this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
473
+ // Pass the resolved string. rememberAsync would otherwise read the
474
+ // options object in this slot as a namespace. (#1142)
402
475
  const accepted = await this.rememberAsync(text, resolvedNamespace, { idempotencyKey });
403
- const completed = await this.waitForRememberJob(accepted.job_id, opts);
476
+ const completed = await this.waitForRememberJob(accepted.job_id, split.options);
404
477
  // Clear only after terminal success. A polling timeout/transport failure
405
478
  // keeps the key so retrying the high-level operation reuses the same job.
406
479
  if (generatedKey)
@@ -413,11 +486,11 @@ export class MemWal {
413
486
  * The relayer continues embedding, encrypting, uploading, and indexing in the background.
414
487
  * Use rememberAndWait() when the caller needs the final blob_id before continuing.
415
488
  *
416
- * @param text - The text to remember
417
- * @param namespace - Optional namespace override
489
+ * A plain object in the namespace position is options, so
490
+ * `remember(text, { idempotencyKey })` keeps the client namespace. (#1142)
418
491
  */
419
- async remember(text, namespace, options = {}) {
420
- return this.rememberAsync(text, namespace, options);
492
+ async remember(text, namespaceOrOptions, options) {
493
+ return this.rememberAsync(text, namespaceOrOptions, options);
421
494
  }
422
495
  /**
423
496
  * Remember multiple memories in one batched request (ENG-1408).
@@ -444,6 +517,13 @@ export class MemWal {
444
517
  if (!Array.isArray(items) || items.length === 0) {
445
518
  throw new Error("rememberBulkAsync: items must be a non-empty array");
446
519
  }
520
+ // The relayer rejects this after the request is signed. Say so first. (#1104)
521
+ if (items.length > MAX_BULK_ITEMS) {
522
+ throw new Error(`rememberBulkAsync: items exceeds maximum of ${MAX_BULK_ITEMS} per bulk request`);
523
+ }
524
+ items.forEach((item, i) => {
525
+ assertNonBlankText(item?.text, `items[${i}].text cannot be empty`);
526
+ });
447
527
  const normalised = items.map((item) => ({
448
528
  text: item.text,
449
529
  namespace: item.namespace ?? this.namespace,
@@ -455,7 +535,9 @@ export class MemWal {
455
535
  return accepted;
456
536
  }
457
537
  async getRememberBulkStatus(jobIds, opts = {}) {
458
- return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200], { timeoutMs: opts.timeoutMs });
538
+ return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200],
539
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
540
+ { timeoutMs: opts.timeoutMs, includeDelegateKey: false });
459
541
  }
460
542
  async waitForRememberJobs(jobIds, namespaces = [], opts = {}) {
461
543
  const { pollIntervalMs = 1500, timeoutMs = 120_000 } = opts;
@@ -470,6 +552,53 @@ export class MemWal {
470
552
  const pending = new Set(jobIds);
471
553
  let attempt = 0;
472
554
  let retryAfterMs = 0;
555
+ let sawRateLimit = false;
556
+ const lastSeen = new Map();
557
+ let lastRefusal;
558
+ // Whether any status read got through. An item missing from an answer
559
+ // was not refused, so it must not be reported as if it had been.
560
+ let answered = false;
561
+ const settle = (jobId, status) => {
562
+ lastSeen.set(jobId, status);
563
+ // The same id can occupy more than one slot. `indexOf` updated only
564
+ // the first, and `pending` is a Set, so the copies stayed `timeout`.
565
+ // (#1121, #1084)
566
+ const terminal = status.status === "done" ||
567
+ status.status === "failed" ||
568
+ status.status === "not_found";
569
+ for (let idx = 0; idx < jobIds.length; idx++) {
570
+ if (jobIds[idx] !== jobId)
571
+ continue;
572
+ if (namespaces[idx] === undefined && status.namespace) {
573
+ results[idx].namespace = status.namespace;
574
+ }
575
+ if (!terminal)
576
+ continue;
577
+ // Caller namespace, then the job's own, then the client default. (#1136)
578
+ const namespace = namespaces[idx] ?? status.namespace ?? this.namespace;
579
+ if (status.status === "done") {
580
+ results[idx] = {
581
+ id: jobId,
582
+ blob_id: status.blob_id ?? "",
583
+ status: "done",
584
+ namespace,
585
+ };
586
+ }
587
+ else {
588
+ results[idx] = {
589
+ id: jobId,
590
+ blob_id: "",
591
+ status: "failed",
592
+ namespace,
593
+ error: status.status === "not_found"
594
+ ? "job not found"
595
+ : redactInternalUrls(status.error ?? "unknown error"),
596
+ };
597
+ }
598
+ }
599
+ if (terminal)
600
+ pending.delete(jobId);
601
+ };
473
602
  while (pending.size > 0 && Date.now() < deadline) {
474
603
  // A retry-after the server just gave us wins over our own curve;
475
604
  // the backoff resumes from where it was on the next normal poll.
@@ -489,11 +618,15 @@ export class MemWal {
489
618
  catch (err) {
490
619
  const httpStatus = err.status ?? 0;
491
620
  if (isTransientPollingStatus(httpStatus)) {
621
+ lastRefusal = httpStatus;
622
+ if (httpStatus === 429)
623
+ sawRateLimit = true;
492
624
  retryAfterMs = retryAfterDelayMs(err, deadline);
493
625
  continue;
494
626
  }
495
627
  throw err;
496
628
  }
629
+ answered = true;
497
630
  const statusById = new Map();
498
631
  for (const item of batchStatus.results) {
499
632
  const bucket = statusById.get(item.job_id);
@@ -509,29 +642,46 @@ export class MemWal {
509
642
  if (!status) {
510
643
  continue;
511
644
  }
512
- const idx = jobIds.indexOf(jobId);
513
- if (status.status === "done") {
514
- results[idx] = {
515
- id: jobId,
516
- blob_id: status.blob_id ?? "",
517
- status: "done",
518
- namespace: namespaces[idx] ?? this.namespace,
519
- };
520
- pending.delete(jobId);
521
- }
522
- else if (status.status === "failed" || status.status === "not_found") {
523
- results[idx] = {
524
- id: jobId,
525
- blob_id: "",
526
- status: "failed",
527
- namespace: namespaces[idx] ?? this.namespace,
528
- error: status.status === "not_found"
529
- ? "job not found"
530
- : redactInternalUrls(status.error ?? "unknown error"),
531
- };
532
- pending.delete(jobId);
645
+ settle(jobId, status);
646
+ }
647
+ }
648
+ // Nothing settled and nothing was even seen: the polls may all have been
649
+ // refused rather than the jobs being slow. Confirm with one direct read,
650
+ // as the MCP bridge does, before reporting anything.
651
+ if (timeoutMs > 0 && pending.size === jobIds.length && lastSeen.size === 0) {
652
+ try {
653
+ const probed = await this.getRememberBulkStatus(jobIds, {
654
+ timeoutMs: Math.min(this.requestTimeoutMs, CONFIRM_READ_TIMEOUT_MS),
655
+ });
656
+ answered = true;
657
+ for (const item of probed.results) {
658
+ if (pending.has(item.job_id))
659
+ settle(item.job_id, item);
533
660
  }
534
661
  }
662
+ catch (err) {
663
+ if (err.status === 429)
664
+ throw bulkRateLimitedError(err, jobIds);
665
+ // Any other probe failure is not evidence about the jobs.
666
+ }
667
+ }
668
+ for (let idx = 0; idx < jobIds.length; idx++) {
669
+ const jobId = jobIds[idx];
670
+ if (!pending.has(jobId))
671
+ continue;
672
+ const seen = lastSeen.get(jobId);
673
+ results[idx].error = seen
674
+ ? `still ${seen.status} after ${timeoutMs}ms` + (seen.error ? `: ${redactInternalUrls(seen.error)}` : "")
675
+ : answered
676
+ ? "not in the relayer's status answer; this item may not be stored"
677
+ : lastRefusal !== undefined
678
+ ? `no status read got through (last poll: HTTP ${lastRefusal}); this item may not be stored`
679
+ : `polling timed out after ${timeoutMs}ms`;
680
+ // Only the "no status read got through" message already names the 429.
681
+ const namesRateLimit = !seen && !answered && lastRefusal === 429;
682
+ if (sawRateLimit && !namesRateLimit) {
683
+ results[idx].error += "; wait hit a rate limit (429)";
684
+ }
535
685
  }
536
686
  const succeeded = results.filter((r) => r.status === "done").length;
537
687
  return {
@@ -555,42 +705,6 @@ export class MemWal {
555
705
  const accepted = await this.rememberBulkAsync(items);
556
706
  return this.waitForRememberJobs(accepted.job_ids, namespaces, opts);
557
707
  }
558
- /**
559
- * Recall memories similar to a query — server handles:
560
- * verify → embed query → search → Walrus download → decrypt → return plaintext.
561
- *
562
- * **Preferred call style**: pass a single `RecallParams` object
563
- * so call sites read self-describingly:
564
- * ```ts
565
- * memwal.recall({ query: "food allergies", limit: 5, namespace: "profile" })
566
- * ```
567
- *
568
- * The legacy positional forms remain supported for backwards compatibility:
569
- * - `recall(query)`
570
- * - `recall(query, limit)`
571
- * - `recall(query, limit, namespace)`
572
- * - `recall(query, { limit, namespace, maxDistance, topK })`
573
- *
574
- * `topK` and `limit` are aliases; if both are set, `topK` wins.
575
- *
576
- * @returns RecallResult with decrypted text results
577
- *
578
- * @example
579
- * ```typescript
580
- * // Object style — recommended
581
- * const result = await memwal.recall({
582
- * query: "food allergies",
583
- * limit: 5,
584
- * namespace: "profile",
585
- * });
586
- * for (const memory of result.results) {
587
- * console.log(memory.text, memory.distance);
588
- * }
589
- *
590
- * // Positional style — still works
591
- * const result2 = await memwal.recall("food allergies", 5, "profile");
592
- * ```
593
- */
594
708
  /**
595
709
  * Estimate the token cost of a string using the SDK's default
596
710
  * character-based approximation (~chars/4, code-point aware). Useful to weigh
@@ -610,25 +724,7 @@ export class MemWal {
610
724
  return estimateTokens(text);
611
725
  }
612
726
  async recall(queryOrParams, limitOrOptions = 10, namespace) {
613
- let query;
614
- let options;
615
- if (typeof queryOrParams === "object") {
616
- const { query: q, ...rest } = queryOrParams;
617
- query = q;
618
- options = rest;
619
- }
620
- else {
621
- query = queryOrParams;
622
- if (limitOrOptions == null) {
623
- options = { limit: 10, namespace };
624
- }
625
- else if (typeof limitOrOptions === "number") {
626
- options = { limit: limitOrOptions, namespace };
627
- }
628
- else {
629
- options = limitOrOptions;
630
- }
631
- }
727
+ const { query, options } = resolveRecallCall(queryOrParams, limitOrOptions, namespace);
632
728
  const limit = options.topK ?? options.limit ?? 10;
633
729
  const resolvedNamespace = options.namespace ?? this.namespace;
634
730
  {
@@ -645,6 +741,9 @@ export class MemWal {
645
741
  // request byte-identical and the relayer applies its own
646
742
  // "relevance" default.
647
743
  sort: options.sort,
744
+ // How long this call waits, so the relayer can stop just
745
+ // short of it and name the step it was stuck in.
746
+ deadline_ms: RECALL_DEADLINE_MS,
648
747
  }, { timeoutMs: RECALL_REQUEST_TIMEOUT_MS });
649
748
  let processed = result;
650
749
  if (typeof options.maxDistance === "number") {
@@ -746,6 +845,7 @@ export class MemWal {
746
845
  * @returns EmbedResult with vector
747
846
  */
748
847
  async embed(text) {
848
+ assertNonBlankText(text, "text cannot be empty");
749
849
  return this.signedRequest("POST", "/api/embed", { text }, { includeDelegateKey: false });
750
850
  }
751
851
  /**
@@ -764,6 +864,7 @@ export class MemWal {
764
864
  * ```
765
865
  */
766
866
  async analyze(text, namespaceOrOptions) {
867
+ assertNonBlankText(text);
767
868
  const options = normalizeAnalyzeOptions(namespaceOrOptions);
768
869
  const body = {
769
870
  text,
@@ -929,7 +1030,7 @@ export class MemWal {
929
1030
  if (!res.ok) {
930
1031
  throw new Error(`Health check failed: ${res.status}`);
931
1032
  }
932
- return res.json();
1033
+ return res.body;
933
1034
  }
934
1035
  /**
935
1036
  * Fetch and validate the relayer compatibility contract.
@@ -942,17 +1043,32 @@ export class MemWal {
942
1043
  */
943
1044
  async getPublicKeyHex() {
944
1045
  const pk = await this.getPublicKey();
1046
+ // `await` yields even when the key was already cached. destroy()
1047
+ // zero-fills that cache in place, so encode only after a fresh check
1048
+ // or this resolves to 64 zero hex chars. (#1090)
1049
+ if (this.destroyed)
1050
+ throw destroyedClientError();
945
1051
  return bytesToHex(pk);
946
1052
  }
947
1053
  // ============================================================
948
1054
  // Internal: Signed HTTP Requests
949
1055
  // ============================================================
950
1056
  async getPublicKey() {
1057
+ // destroy() zero-fills the cache in place, and an uncached key would
1058
+ // otherwise derive the well-known key of the all-zero seed. Re-check
1059
+ // after every await, and never cache a key derived once wiped. (#1090)
1060
+ if (this.destroyed)
1061
+ throw destroyedClientError();
951
1062
  if (!this.publicKey) {
952
1063
  const ed = await getEd();
953
- this.publicKey = await ed.getPublicKeyAsync(this.privateKey);
1064
+ if (this.destroyed)
1065
+ throw destroyedClientError();
1066
+ const derived = await ed.getPublicKeyAsync(this.privateKey);
1067
+ if (this.destroyed)
1068
+ throw destroyedClientError();
1069
+ this.publicKey = derived;
954
1070
  }
955
- return this.publicKey;
1071
+ return this.publicKey.slice();
956
1072
  }
957
1073
  async ensureCompatibleRelayer() {
958
1074
  if (this.relayerVersionMetadata)
@@ -968,7 +1084,7 @@ export class MemWal {
968
1084
  const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" });
969
1085
  let body;
970
1086
  if (versionRes.ok) {
971
- body = (await versionRes.json());
1087
+ body = versionRes.body;
972
1088
  }
973
1089
  else if (versionRes.status === 404 || versionRes.status === 405) {
974
1090
  const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" });
@@ -976,7 +1092,7 @@ export class MemWal {
976
1092
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ` +
977
1093
  `${versionRes.status}, and GET /health returned ${healthRes.status}`);
978
1094
  }
979
- body = (await healthRes.json());
1095
+ body = healthRes.body;
980
1096
  }
981
1097
  else {
982
1098
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ${versionRes.status}`);
@@ -1013,7 +1129,7 @@ export class MemWal {
1013
1129
  if (!res.ok) {
1014
1130
  throw new Error(`GET /config returned ${res.status}`);
1015
1131
  }
1016
- const body = (await res.json());
1132
+ const body = res.body;
1017
1133
  if (typeof body.packageId !== "string" || !body.packageId ||
1018
1134
  typeof body.network !== "string" || !body.network) {
1019
1135
  throw new Error("GET /config response missing packageId / network");
@@ -1209,7 +1325,7 @@ export class MemWal {
1209
1325
  * Pass [200, 202] for endpoints that return 202 Accepted.
1210
1326
  */
1211
1327
  /**
1212
- * `fetch` with this client's deadline applied.
1328
+ * `fetch` plus the JSON body read, with this client's deadline applied across both.
1213
1329
  *
1214
1330
  * For the handshake endpoints that skip request signing — `/health`,
1215
1331
  * `/version`, `/config`. They are the worst place to leave unbounded: the
@@ -1225,7 +1341,12 @@ export class MemWal {
1225
1341
  const ms = timeoutMs ?? this.requestTimeoutMs;
1226
1342
  const deadline = deadlineSignal(ms);
1227
1343
  try {
1228
- return await fetch(url, { ...init, signal: deadline.signal });
1344
+ const res = await fetch(url, { ...init, signal: deadline.signal });
1345
+ return {
1346
+ ok: res.ok,
1347
+ status: res.status,
1348
+ body: res.ok ? (await res.json()) : undefined,
1349
+ };
1229
1350
  }
1230
1351
  catch (err) {
1231
1352
  if (deadline.timedOut()) {
@@ -1244,6 +1365,9 @@ export class MemWal {
1244
1365
  const options = Array.isArray(acceptedStatusesOrOptions)
1245
1366
  ? requestOptions
1246
1367
  : acceptedStatusesOrOptions;
1368
+ // Before the version probe. A destroyed client must not open GET /version. (#1090)
1369
+ if (this.destroyed)
1370
+ throw destroyedClientError();
1247
1371
  await this.ensureCompatibleRelayer();
1248
1372
  const ed = await getEd();
1249
1373
  const timestamp = Math.floor(Date.now() / 1000).toString();
@@ -1258,9 +1382,19 @@ export class MemWal {
1258
1382
  // LOW-23: Build message to sign — now includes nonce AND account id
1259
1383
  const message = `${timestamp}.${method}.${path}.${bodySha256}.${nonce}.${this.accountId}`;
1260
1384
  const msgBytes = new TextEncoder().encode(message);
1385
+ // Again after the version await. A destroy that lands while that
1386
+ // request is in flight must still refuse to sign. (#1090)
1387
+ if (this.destroyed)
1388
+ throw destroyedClientError();
1261
1389
  // Sign with Ed25519
1262
1390
  const signature = await ed.signAsync(msgBytes, this.privateKey);
1391
+ // destroy() during the sign, or during public-key derivation, must
1392
+ // not reach fetch with the wiped seed's well-known key. (#1090)
1393
+ if (this.destroyed)
1394
+ throw destroyedClientError();
1263
1395
  const publicKey = await this.getPublicKey();
1396
+ if (this.destroyed)
1397
+ throw destroyedClientError();
1264
1398
  // Make HTTP request
1265
1399
  const url = `${this.serverUrl}${path}`;
1266
1400
  const headers = {
@@ -1283,51 +1417,51 @@ export class MemWal {
1283
1417
  // for as long as the connection stays open.
1284
1418
  const deadlineMs = options.timeoutMs ?? this.requestTimeoutMs;
1285
1419
  const deadline = deadlineSignal(deadlineMs, options.signal);
1286
- let res;
1287
1420
  try {
1288
- res = await fetch(url, {
1421
+ const res = await fetch(url, {
1289
1422
  method,
1290
1423
  headers,
1291
1424
  body: method === "GET" ? undefined : bodyStr,
1292
1425
  signal: deadline.signal,
1293
1426
  });
1427
+ if (!acceptedStatuses.includes(res.status)) {
1428
+ // LOW-26: sanitize server error bodies before surfacing to callers.
1429
+ const raw = await res.text();
1430
+ const compatibilityError = compatibilityErrorFromStatus(res.status, raw);
1431
+ if (compatibilityError)
1432
+ throw compatibilityError;
1433
+ // A stale/future-dated signature is rejected with 401 + a machine-
1434
+ // readable reason header. Surface it as an actionable clock-drift
1435
+ // error rather than an opaque 401 so the caller can fix node time.
1436
+ const clockDriftError = clockDriftErrorFromResponse(res);
1437
+ if (clockDriftError)
1438
+ throw clockDriftError;
1439
+ const { message, serverCode } = sanitizeServerError(res.status, raw, res.headers.get("x-auth-error"));
1440
+ const err = new Error(message);
1441
+ err.status = res.status;
1442
+ if (serverCode)
1443
+ err.serverCode = serverCode;
1444
+ const retryAfter = Number(res.headers.get("retry-after"));
1445
+ if (Number.isFinite(retryAfter) && retryAfter > 0) {
1446
+ err.retryAfterSeconds = retryAfter;
1447
+ }
1448
+ // Preserve raw body on `cause` for in-process debugging only.
1449
+ err.cause = raw;
1450
+ throw err;
1451
+ }
1452
+ return (await res.json());
1294
1453
  }
1295
1454
  catch (err) {
1296
1455
  // Translate our own expiry into something a caller can classify.
1297
1456
  // An abort the CALLER asked for is theirs and propagates untouched.
1298
- if (deadline.timedOut())
1457
+ if (deadline.timedOut() && err.status === undefined) {
1299
1458
  throw requestTimeoutError(method, path, deadlineMs);
1459
+ }
1300
1460
  throw err;
1301
1461
  }
1302
1462
  finally {
1303
1463
  deadline.dispose();
1304
1464
  }
1305
- if (!acceptedStatuses.includes(res.status)) {
1306
- // LOW-26: sanitize server error bodies before surfacing to callers.
1307
- const raw = await res.text();
1308
- const compatibilityError = compatibilityErrorFromStatus(res.status, raw);
1309
- if (compatibilityError)
1310
- throw compatibilityError;
1311
- // A stale/future-dated signature is rejected with 401 + a machine-
1312
- // readable reason header. Surface it as an actionable clock-drift
1313
- // error rather than an opaque 401 so the caller can fix node time.
1314
- const clockDriftError = clockDriftErrorFromResponse(res);
1315
- if (clockDriftError)
1316
- throw clockDriftError;
1317
- const { message, serverCode } = sanitizeServerError(res.status, raw, res.headers.get("x-auth-error"));
1318
- const err = new Error(message);
1319
- err.status = res.status;
1320
- if (serverCode)
1321
- err.serverCode = serverCode;
1322
- const retryAfter = Number(res.headers.get("retry-after"));
1323
- if (Number.isFinite(retryAfter) && retryAfter > 0) {
1324
- err.retryAfterSeconds = retryAfter;
1325
- }
1326
- // Preserve raw body on `cause` for in-process debugging only.
1327
- err.cause = raw;
1328
- throw err;
1329
- }
1330
- return res.json();
1331
1465
  }
1332
1466
  }
1333
1467
  //# sourceMappingURL=memwal.js.map