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

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,10 @@
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";
33
34
  // ============================================================
34
35
  // Ed25519 Signing (lazy-loaded)
35
36
  // ============================================================
@@ -48,12 +49,6 @@ const SEAL_SESSION_SAFETY_MARGIN_MS = 30_000;
48
49
  function sleep(ms) {
49
50
  return new Promise((resolve) => setTimeout(resolve, ms));
50
51
  }
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
52
  /** Window over which the same (namespace, text) resolves to one key.
58
53
  *
59
54
  * `pendingRememberKeys` only dedupes retries that reuse one client instance,
@@ -72,6 +67,30 @@ async function derivedIdempotencyKey(requestIdentity) {
72
67
  * so one stalled read ran past `timeoutMs` entirely. 30s mirrors the relayer's
73
68
  * own outbound client. */
74
69
  const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
70
+ /** The one confirming read a bulk wait makes after its budget is spent. It
71
+ * runs past the caller's deadline by design, so it gets a short bound of its
72
+ * own rather than the 30s default a stalled socket would hold it for. */
73
+ const CONFIRM_READ_TIMEOUT_MS = 5_000;
74
+ /** Matches the relayer's `MAX_BULK_ITEMS`. Reject before a signed request. */
75
+ const MAX_BULK_ITEMS = 20;
76
+ /**
77
+ * `remember(text, { idempotencyKey })` is the natural call when the namespace
78
+ * stays at the client default. A plain object in the namespace slot is those
79
+ * options, not a namespace name. (#1142)
80
+ */
81
+ function splitRememberArgs(namespaceOrOptions, options) {
82
+ // The third argument is the dedicated options bag. When the namespace
83
+ // slot is also an object, keep both and let the bag win on a clash.
84
+ // `rememberAndWait(text, { timeoutMs }, { idempotencyKey })` is typed
85
+ // and used to drop the key, so a retry minted a second blob. (#1142)
86
+ if (typeof namespaceOrOptions === "object" && namespaceOrOptions !== null) {
87
+ return { namespace: undefined, options: { ...namespaceOrOptions, ...options } };
88
+ }
89
+ return { namespace: namespaceOrOptions, options: options ?? {} };
90
+ }
91
+ function destroyedClientError() {
92
+ return new Error("Walrus Memory client was destroyed; its keys are zeroed. Create a new one.");
93
+ }
75
94
  /** `POST /api/restore` bounds itself at 55s server-side and answers with an
76
95
  * error rather than going quiet, so the client must outlast that or it would
77
96
  * abandon a response already on its way. */
@@ -82,6 +101,13 @@ const ANALYZE_REQUEST_TIMEOUT_MS = 60_000;
82
101
  /** `POST /api/recall` has carried its own 15s deadline since before the rest
83
102
  * had any; keeping it named makes that a decision rather than an accident. */
84
103
  const RECALL_REQUEST_TIMEOUT_MS = 15_000;
104
+ /** What `recall()` tells the relayer it will wait, so the 504 naming the stuck
105
+ * stage arrives before the abort above rather than after it. A second under
106
+ * that abort because the two clocks start at different moments: this timer
107
+ * starts before `fetch`, the relayer's when the request lands, and the margin
108
+ * the relayer keeps for its reply cannot also cover DNS, TCP and TLS. Derived
109
+ * from the timeout so the two can never drift apart. */
110
+ const RECALL_DEADLINE_MS = RECALL_REQUEST_TIMEOUT_MS - 1_000;
85
111
  /**
86
112
  * Abort signal that fires after `ms`, or when `caller` aborts — whichever is
87
113
  * first. Built by hand rather than with `AbortSignal.any`, which lands too
@@ -157,6 +183,24 @@ function retryAfterDelayMs(err, deadline) {
157
183
  return 0;
158
184
  return Math.max(0, Math.min(seconds * 1000, deadline - Date.now()));
159
185
  }
186
+ /**
187
+ * Thrown when a bulk wait could not read a single status, the confirming read
188
+ * included. The status endpoint counts against the same delegate-key budget
189
+ * as writes, so a batch sent near the limit can have every poll refused. The
190
+ * old result then read as "still uploading" even when nothing had landed
191
+ * (GH #967). A refusal says nothing about the jobs, so do not report it as
192
+ * progress.
193
+ */
194
+ function bulkRateLimitedError(err, jobIds) {
195
+ const retryAfterSeconds = err.retryAfterSeconds
196
+ ?? retryAfterSecondsFromBody(err.cause);
197
+ const wait = retryAfterSeconds ? ` after ~${Math.ceil(retryAfterSeconds)}s` : "";
198
+ const e = new Error(`Walrus Memory rate-limited every status read for this batch, so none of its ${jobIds.length} writes ` +
199
+ `could be confirmed. Do not treat them as stored: check them with getRememberBulkStatus(jobIds)${wait}. ` +
200
+ `Status reads count against the same delegate-key budget as writes.`);
201
+ e.name = "MemWalRateLimited";
202
+ return Object.assign(e, { status: 429, jobIds, retryAfterSeconds });
203
+ }
160
204
  /**
161
205
  * The relayer states the backoff in the 429 body as well as in `Retry-After`.
162
206
  * A proxy that strips the header must not cost us the hint.
@@ -219,6 +263,7 @@ function normalizeSuiNetworkForGrpc(network) {
219
263
  export class MemWal {
220
264
  privateKey;
221
265
  publicKey = null;
266
+ destroyed = false;
222
267
  serverUrl;
223
268
  namespace;
224
269
  accountId;
@@ -276,6 +321,7 @@ export class MemWal {
276
321
  * Prevents key extraction from V8 heap dumps.
277
322
  */
278
323
  destroy() {
324
+ this.destroyed = true;
279
325
  if (this.privateKey) {
280
326
  this.privateKey.fill(0);
281
327
  }
@@ -296,11 +342,13 @@ export class MemWal {
296
342
  /**
297
343
  * Submit a remember request and return as soon as the server accepts the job.
298
344
  */
299
- async rememberAsync(text, namespace, options = {}) {
300
- const resolvedNamespace = namespace ?? this.namespace;
345
+ async rememberAsync(text, namespaceOrOptions, options) {
346
+ assertNonBlankText(text);
347
+ const split = splitRememberArgs(namespaceOrOptions, options);
348
+ const resolvedNamespace = split.namespace ?? this.namespace;
301
349
  const requestIdentity = `${resolvedNamespace}\0${text}`;
302
- const generatedKey = options.idempotencyKey === undefined;
303
- const idempotencyKey = options.idempotencyKey
350
+ const generatedKey = split.options.idempotencyKey === undefined;
351
+ const idempotencyKey = split.options.idempotencyKey
304
352
  ?? this.pendingRememberKeys.get(requestIdentity)
305
353
  ?? (await derivedIdempotencyKey(requestIdentity));
306
354
  if (generatedKey)
@@ -320,7 +368,18 @@ export class MemWal {
320
368
  * resolves at the terminal state and hides progress.
321
369
  */
322
370
  async getRememberStatus(jobId) {
323
- const status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404]);
371
+ // `GET /api/remember/` is not a route. The relayer answers 404 with an
372
+ // empty body, and parsing that threw SyntaxError. (#1087)
373
+ if (typeof jobId !== "string" || jobId.length === 0) {
374
+ return {
375
+ job_id: jobId,
376
+ status: "not_found",
377
+ error: `Job ${jobId} not found`,
378
+ };
379
+ }
380
+ const status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404],
381
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
382
+ { includeDelegateKey: false });
324
383
  if (!("status" in status)) {
325
384
  return {
326
385
  job_id: jobId,
@@ -334,10 +393,17 @@ export class MemWal {
334
393
  * Poll an accepted remember job until it reaches a terminal state.
335
394
  */
336
395
  async waitForRememberJob(jobId, opts = {}) {
396
+ if (typeof jobId !== "string" || jobId.length === 0) {
397
+ throw Object.assign(new Error(`remember job not found: ${jobId}`), {
398
+ status: 404,
399
+ jobId,
400
+ });
401
+ }
337
402
  const { pollIntervalMs = 1500, timeoutMs = 60_000 } = opts;
338
403
  const deadline = Date.now() + timeoutMs;
339
404
  let attempt = 0;
340
405
  let retryAfterMs = 0;
406
+ let sawRateLimit = false;
341
407
  while (Date.now() < deadline) {
342
408
  // A retry-after the server just gave us wins over our own curve;
343
409
  // the backoff resumes from where it was on the next normal poll.
@@ -356,11 +422,13 @@ export class MemWal {
356
422
  // and the client deadline keeps ONE stalled poll from
357
423
  // swallowing the entire budget, so the loop still gets to
358
424
  // retry. An expired poll surfaces as a transient 504.
359
- { timeoutMs: this.pollDeadlineMs(deadline) });
425
+ { timeoutMs: this.pollDeadlineMs(deadline), includeDelegateKey: false });
360
426
  }
361
427
  catch (err) {
362
428
  const httpStatus = err.status ?? 0;
363
429
  if (isTransientPollingStatus(httpStatus)) {
430
+ if (httpStatus === 429)
431
+ sawRateLimit = true;
364
432
  retryAfterMs = retryAfterDelayMs(err, deadline);
365
433
  continue;
366
434
  }
@@ -385,22 +453,26 @@ export class MemWal {
385
453
  throw Object.assign(new Error(`remember job failed: ${redactInternalUrls(status.error ?? "unknown error")}`), { status: 500, jobId });
386
454
  }
387
455
  }
388
- throw Object.assign(new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})`), { status: 504, jobId });
456
+ throw Object.assign(new Error(`remember job timed out after ${timeoutMs}ms (job_id=${jobId})` +
457
+ (sawRateLimit ? "; wait hit a rate limit (429)" : "")), { status: 504, jobId });
389
458
  }
390
459
  /**
391
460
  * Remember something and wait for the background job to complete.
392
461
  */
393
- async rememberAndWait(text, namespace, opts = {}) {
394
- const resolvedNamespace = namespace ?? this.namespace;
462
+ async rememberAndWait(text, namespaceOrOptions, opts) {
463
+ const split = splitRememberArgs(namespaceOrOptions, opts);
464
+ const resolvedNamespace = split.namespace ?? this.namespace;
395
465
  const requestIdentity = `${resolvedNamespace}\0${text}`;
396
- const generatedKey = opts.idempotencyKey === undefined;
397
- const idempotencyKey = opts.idempotencyKey
466
+ const generatedKey = split.options.idempotencyKey === undefined;
467
+ const idempotencyKey = split.options.idempotencyKey
398
468
  ?? this.pendingRememberKeys.get(requestIdentity)
399
469
  ?? (await derivedIdempotencyKey(requestIdentity));
400
470
  if (generatedKey)
401
471
  this.pendingRememberKeys.set(requestIdentity, idempotencyKey);
472
+ // Pass the resolved string. rememberAsync would otherwise read the
473
+ // options object in this slot as a namespace. (#1142)
402
474
  const accepted = await this.rememberAsync(text, resolvedNamespace, { idempotencyKey });
403
- const completed = await this.waitForRememberJob(accepted.job_id, opts);
475
+ const completed = await this.waitForRememberJob(accepted.job_id, split.options);
404
476
  // Clear only after terminal success. A polling timeout/transport failure
405
477
  // keeps the key so retrying the high-level operation reuses the same job.
406
478
  if (generatedKey)
@@ -413,11 +485,11 @@ export class MemWal {
413
485
  * The relayer continues embedding, encrypting, uploading, and indexing in the background.
414
486
  * Use rememberAndWait() when the caller needs the final blob_id before continuing.
415
487
  *
416
- * @param text - The text to remember
417
- * @param namespace - Optional namespace override
488
+ * A plain object in the namespace position is options, so
489
+ * `remember(text, { idempotencyKey })` keeps the client namespace. (#1142)
418
490
  */
419
- async remember(text, namespace, options = {}) {
420
- return this.rememberAsync(text, namespace, options);
491
+ async remember(text, namespaceOrOptions, options) {
492
+ return this.rememberAsync(text, namespaceOrOptions, options);
421
493
  }
422
494
  /**
423
495
  * Remember multiple memories in one batched request (ENG-1408).
@@ -444,6 +516,13 @@ export class MemWal {
444
516
  if (!Array.isArray(items) || items.length === 0) {
445
517
  throw new Error("rememberBulkAsync: items must be a non-empty array");
446
518
  }
519
+ // The relayer rejects this after the request is signed. Say so first. (#1104)
520
+ if (items.length > MAX_BULK_ITEMS) {
521
+ throw new Error(`rememberBulkAsync: items exceeds maximum of ${MAX_BULK_ITEMS} per bulk request`);
522
+ }
523
+ items.forEach((item, i) => {
524
+ assertNonBlankText(item?.text, `items[${i}].text cannot be empty`);
525
+ });
447
526
  const normalised = items.map((item) => ({
448
527
  text: item.text,
449
528
  namespace: item.namespace ?? this.namespace,
@@ -455,7 +534,9 @@ export class MemWal {
455
534
  return accepted;
456
535
  }
457
536
  async getRememberBulkStatus(jobIds, opts = {}) {
458
- return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200], { timeoutMs: opts.timeoutMs });
537
+ return this.signedRequest("POST", "/api/remember/bulk/status", { job_ids: jobIds }, [200],
538
+ // Status is metadata. No SEAL decrypt, so no session. (#1135)
539
+ { timeoutMs: opts.timeoutMs, includeDelegateKey: false });
459
540
  }
460
541
  async waitForRememberJobs(jobIds, namespaces = [], opts = {}) {
461
542
  const { pollIntervalMs = 1500, timeoutMs = 120_000 } = opts;
@@ -470,6 +551,53 @@ export class MemWal {
470
551
  const pending = new Set(jobIds);
471
552
  let attempt = 0;
472
553
  let retryAfterMs = 0;
554
+ let sawRateLimit = false;
555
+ const lastSeen = new Map();
556
+ let lastRefusal;
557
+ // Whether any status read got through. An item missing from an answer
558
+ // was not refused, so it must not be reported as if it had been.
559
+ let answered = false;
560
+ const settle = (jobId, status) => {
561
+ lastSeen.set(jobId, status);
562
+ // The same id can occupy more than one slot. `indexOf` updated only
563
+ // the first, and `pending` is a Set, so the copies stayed `timeout`.
564
+ // (#1121, #1084)
565
+ const terminal = status.status === "done" ||
566
+ status.status === "failed" ||
567
+ status.status === "not_found";
568
+ for (let idx = 0; idx < jobIds.length; idx++) {
569
+ if (jobIds[idx] !== jobId)
570
+ continue;
571
+ if (namespaces[idx] === undefined && status.namespace) {
572
+ results[idx].namespace = status.namespace;
573
+ }
574
+ if (!terminal)
575
+ continue;
576
+ // Caller namespace, then the job's own, then the client default. (#1136)
577
+ const namespace = namespaces[idx] ?? status.namespace ?? this.namespace;
578
+ if (status.status === "done") {
579
+ results[idx] = {
580
+ id: jobId,
581
+ blob_id: status.blob_id ?? "",
582
+ status: "done",
583
+ namespace,
584
+ };
585
+ }
586
+ else {
587
+ results[idx] = {
588
+ id: jobId,
589
+ blob_id: "",
590
+ status: "failed",
591
+ namespace,
592
+ error: status.status === "not_found"
593
+ ? "job not found"
594
+ : redactInternalUrls(status.error ?? "unknown error"),
595
+ };
596
+ }
597
+ }
598
+ if (terminal)
599
+ pending.delete(jobId);
600
+ };
473
601
  while (pending.size > 0 && Date.now() < deadline) {
474
602
  // A retry-after the server just gave us wins over our own curve;
475
603
  // the backoff resumes from where it was on the next normal poll.
@@ -489,11 +617,15 @@ export class MemWal {
489
617
  catch (err) {
490
618
  const httpStatus = err.status ?? 0;
491
619
  if (isTransientPollingStatus(httpStatus)) {
620
+ lastRefusal = httpStatus;
621
+ if (httpStatus === 429)
622
+ sawRateLimit = true;
492
623
  retryAfterMs = retryAfterDelayMs(err, deadline);
493
624
  continue;
494
625
  }
495
626
  throw err;
496
627
  }
628
+ answered = true;
497
629
  const statusById = new Map();
498
630
  for (const item of batchStatus.results) {
499
631
  const bucket = statusById.get(item.job_id);
@@ -509,29 +641,46 @@ export class MemWal {
509
641
  if (!status) {
510
642
  continue;
511
643
  }
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);
644
+ settle(jobId, status);
645
+ }
646
+ }
647
+ // Nothing settled and nothing was even seen: the polls may all have been
648
+ // refused rather than the jobs being slow. Confirm with one direct read,
649
+ // as the MCP bridge does, before reporting anything.
650
+ if (timeoutMs > 0 && pending.size === jobIds.length && lastSeen.size === 0) {
651
+ try {
652
+ const probed = await this.getRememberBulkStatus(jobIds, {
653
+ timeoutMs: Math.min(this.requestTimeoutMs, CONFIRM_READ_TIMEOUT_MS),
654
+ });
655
+ answered = true;
656
+ for (const item of probed.results) {
657
+ if (pending.has(item.job_id))
658
+ settle(item.job_id, item);
533
659
  }
534
660
  }
661
+ catch (err) {
662
+ if (err.status === 429)
663
+ throw bulkRateLimitedError(err, jobIds);
664
+ // Any other probe failure is not evidence about the jobs.
665
+ }
666
+ }
667
+ for (let idx = 0; idx < jobIds.length; idx++) {
668
+ const jobId = jobIds[idx];
669
+ if (!pending.has(jobId))
670
+ continue;
671
+ const seen = lastSeen.get(jobId);
672
+ results[idx].error = seen
673
+ ? `still ${seen.status} after ${timeoutMs}ms` + (seen.error ? `: ${redactInternalUrls(seen.error)}` : "")
674
+ : answered
675
+ ? "not in the relayer's status answer; this item may not be stored"
676
+ : lastRefusal !== undefined
677
+ ? `no status read got through (last poll: HTTP ${lastRefusal}); this item may not be stored`
678
+ : `polling timed out after ${timeoutMs}ms`;
679
+ // Only the "no status read got through" message already names the 429.
680
+ const namesRateLimit = !seen && !answered && lastRefusal === 429;
681
+ if (sawRateLimit && !namesRateLimit) {
682
+ results[idx].error += "; wait hit a rate limit (429)";
683
+ }
535
684
  }
536
685
  const succeeded = results.filter((r) => r.status === "done").length;
537
686
  return {
@@ -626,7 +775,12 @@ export class MemWal {
626
775
  options = { limit: limitOrOptions, namespace };
627
776
  }
628
777
  else {
629
- options = limitOrOptions;
778
+ // Positional namespace fills an options object that omitted it.
779
+ // An explicit options.namespace still wins. (#1038)
780
+ options = { ...limitOrOptions };
781
+ if (options.namespace === undefined && namespace !== undefined) {
782
+ options.namespace = namespace;
783
+ }
630
784
  }
631
785
  }
632
786
  const limit = options.topK ?? options.limit ?? 10;
@@ -645,6 +799,9 @@ export class MemWal {
645
799
  // request byte-identical and the relayer applies its own
646
800
  // "relevance" default.
647
801
  sort: options.sort,
802
+ // How long this call waits, so the relayer can stop just
803
+ // short of it and name the step it was stuck in.
804
+ deadline_ms: RECALL_DEADLINE_MS,
648
805
  }, { timeoutMs: RECALL_REQUEST_TIMEOUT_MS });
649
806
  let processed = result;
650
807
  if (typeof options.maxDistance === "number") {
@@ -746,6 +903,7 @@ export class MemWal {
746
903
  * @returns EmbedResult with vector
747
904
  */
748
905
  async embed(text) {
906
+ assertNonBlankText(text, "text cannot be empty");
749
907
  return this.signedRequest("POST", "/api/embed", { text }, { includeDelegateKey: false });
750
908
  }
751
909
  /**
@@ -764,6 +922,7 @@ export class MemWal {
764
922
  * ```
765
923
  */
766
924
  async analyze(text, namespaceOrOptions) {
925
+ assertNonBlankText(text);
767
926
  const options = normalizeAnalyzeOptions(namespaceOrOptions);
768
927
  const body = {
769
928
  text,
@@ -929,7 +1088,7 @@ export class MemWal {
929
1088
  if (!res.ok) {
930
1089
  throw new Error(`Health check failed: ${res.status}`);
931
1090
  }
932
- return res.json();
1091
+ return res.body;
933
1092
  }
934
1093
  /**
935
1094
  * Fetch and validate the relayer compatibility contract.
@@ -942,17 +1101,32 @@ export class MemWal {
942
1101
  */
943
1102
  async getPublicKeyHex() {
944
1103
  const pk = await this.getPublicKey();
1104
+ // `await` yields even when the key was already cached. destroy()
1105
+ // zero-fills that cache in place, so encode only after a fresh check
1106
+ // or this resolves to 64 zero hex chars. (#1090)
1107
+ if (this.destroyed)
1108
+ throw destroyedClientError();
945
1109
  return bytesToHex(pk);
946
1110
  }
947
1111
  // ============================================================
948
1112
  // Internal: Signed HTTP Requests
949
1113
  // ============================================================
950
1114
  async getPublicKey() {
1115
+ // destroy() zero-fills the cache in place, and an uncached key would
1116
+ // otherwise derive the well-known key of the all-zero seed. Re-check
1117
+ // after every await, and never cache a key derived once wiped. (#1090)
1118
+ if (this.destroyed)
1119
+ throw destroyedClientError();
951
1120
  if (!this.publicKey) {
952
1121
  const ed = await getEd();
953
- this.publicKey = await ed.getPublicKeyAsync(this.privateKey);
1122
+ if (this.destroyed)
1123
+ throw destroyedClientError();
1124
+ const derived = await ed.getPublicKeyAsync(this.privateKey);
1125
+ if (this.destroyed)
1126
+ throw destroyedClientError();
1127
+ this.publicKey = derived;
954
1128
  }
955
- return this.publicKey;
1129
+ return this.publicKey.slice();
956
1130
  }
957
1131
  async ensureCompatibleRelayer() {
958
1132
  if (this.relayerVersionMetadata)
@@ -968,7 +1142,7 @@ export class MemWal {
968
1142
  const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" });
969
1143
  let body;
970
1144
  if (versionRes.ok) {
971
- body = (await versionRes.json());
1145
+ body = versionRes.body;
972
1146
  }
973
1147
  else if (versionRes.status === 404 || versionRes.status === 405) {
974
1148
  const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" });
@@ -976,7 +1150,7 @@ export class MemWal {
976
1150
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ` +
977
1151
  `${versionRes.status}, and GET /health returned ${healthRes.status}`);
978
1152
  }
979
- body = (await healthRes.json());
1153
+ body = healthRes.body;
980
1154
  }
981
1155
  else {
982
1156
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ${versionRes.status}`);
@@ -1013,7 +1187,7 @@ export class MemWal {
1013
1187
  if (!res.ok) {
1014
1188
  throw new Error(`GET /config returned ${res.status}`);
1015
1189
  }
1016
- const body = (await res.json());
1190
+ const body = res.body;
1017
1191
  if (typeof body.packageId !== "string" || !body.packageId ||
1018
1192
  typeof body.network !== "string" || !body.network) {
1019
1193
  throw new Error("GET /config response missing packageId / network");
@@ -1209,7 +1383,7 @@ export class MemWal {
1209
1383
  * Pass [200, 202] for endpoints that return 202 Accepted.
1210
1384
  */
1211
1385
  /**
1212
- * `fetch` with this client's deadline applied.
1386
+ * `fetch` plus the JSON body read, with this client's deadline applied across both.
1213
1387
  *
1214
1388
  * For the handshake endpoints that skip request signing — `/health`,
1215
1389
  * `/version`, `/config`. They are the worst place to leave unbounded: the
@@ -1225,7 +1399,12 @@ export class MemWal {
1225
1399
  const ms = timeoutMs ?? this.requestTimeoutMs;
1226
1400
  const deadline = deadlineSignal(ms);
1227
1401
  try {
1228
- return await fetch(url, { ...init, signal: deadline.signal });
1402
+ const res = await fetch(url, { ...init, signal: deadline.signal });
1403
+ return {
1404
+ ok: res.ok,
1405
+ status: res.status,
1406
+ body: res.ok ? (await res.json()) : undefined,
1407
+ };
1229
1408
  }
1230
1409
  catch (err) {
1231
1410
  if (deadline.timedOut()) {
@@ -1244,6 +1423,9 @@ export class MemWal {
1244
1423
  const options = Array.isArray(acceptedStatusesOrOptions)
1245
1424
  ? requestOptions
1246
1425
  : acceptedStatusesOrOptions;
1426
+ // Before the version probe. A destroyed client must not open GET /version. (#1090)
1427
+ if (this.destroyed)
1428
+ throw destroyedClientError();
1247
1429
  await this.ensureCompatibleRelayer();
1248
1430
  const ed = await getEd();
1249
1431
  const timestamp = Math.floor(Date.now() / 1000).toString();
@@ -1258,9 +1440,19 @@ export class MemWal {
1258
1440
  // LOW-23: Build message to sign — now includes nonce AND account id
1259
1441
  const message = `${timestamp}.${method}.${path}.${bodySha256}.${nonce}.${this.accountId}`;
1260
1442
  const msgBytes = new TextEncoder().encode(message);
1443
+ // Again after the version await. A destroy that lands while that
1444
+ // request is in flight must still refuse to sign. (#1090)
1445
+ if (this.destroyed)
1446
+ throw destroyedClientError();
1261
1447
  // Sign with Ed25519
1262
1448
  const signature = await ed.signAsync(msgBytes, this.privateKey);
1449
+ // destroy() during the sign, or during public-key derivation, must
1450
+ // not reach fetch with the wiped seed's well-known key. (#1090)
1451
+ if (this.destroyed)
1452
+ throw destroyedClientError();
1263
1453
  const publicKey = await this.getPublicKey();
1454
+ if (this.destroyed)
1455
+ throw destroyedClientError();
1264
1456
  // Make HTTP request
1265
1457
  const url = `${this.serverUrl}${path}`;
1266
1458
  const headers = {
@@ -1283,51 +1475,51 @@ export class MemWal {
1283
1475
  // for as long as the connection stays open.
1284
1476
  const deadlineMs = options.timeoutMs ?? this.requestTimeoutMs;
1285
1477
  const deadline = deadlineSignal(deadlineMs, options.signal);
1286
- let res;
1287
1478
  try {
1288
- res = await fetch(url, {
1479
+ const res = await fetch(url, {
1289
1480
  method,
1290
1481
  headers,
1291
1482
  body: method === "GET" ? undefined : bodyStr,
1292
1483
  signal: deadline.signal,
1293
1484
  });
1485
+ if (!acceptedStatuses.includes(res.status)) {
1486
+ // LOW-26: sanitize server error bodies before surfacing to callers.
1487
+ const raw = await res.text();
1488
+ const compatibilityError = compatibilityErrorFromStatus(res.status, raw);
1489
+ if (compatibilityError)
1490
+ throw compatibilityError;
1491
+ // A stale/future-dated signature is rejected with 401 + a machine-
1492
+ // readable reason header. Surface it as an actionable clock-drift
1493
+ // error rather than an opaque 401 so the caller can fix node time.
1494
+ const clockDriftError = clockDriftErrorFromResponse(res);
1495
+ if (clockDriftError)
1496
+ throw clockDriftError;
1497
+ const { message, serverCode } = sanitizeServerError(res.status, raw, res.headers.get("x-auth-error"));
1498
+ const err = new Error(message);
1499
+ err.status = res.status;
1500
+ if (serverCode)
1501
+ err.serverCode = serverCode;
1502
+ const retryAfter = Number(res.headers.get("retry-after"));
1503
+ if (Number.isFinite(retryAfter) && retryAfter > 0) {
1504
+ err.retryAfterSeconds = retryAfter;
1505
+ }
1506
+ // Preserve raw body on `cause` for in-process debugging only.
1507
+ err.cause = raw;
1508
+ throw err;
1509
+ }
1510
+ return (await res.json());
1294
1511
  }
1295
1512
  catch (err) {
1296
1513
  // Translate our own expiry into something a caller can classify.
1297
1514
  // An abort the CALLER asked for is theirs and propagates untouched.
1298
- if (deadline.timedOut())
1515
+ if (deadline.timedOut() && err.status === undefined) {
1299
1516
  throw requestTimeoutError(method, path, deadlineMs);
1517
+ }
1300
1518
  throw err;
1301
1519
  }
1302
1520
  finally {
1303
1521
  deadline.dispose();
1304
1522
  }
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
1523
  }
1332
1524
  }
1333
1525
  //# sourceMappingURL=memwal.js.map