@mysten-incubation/memwal 0.1.8-dev.0 → 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
@@ -135,6 +161,62 @@ function requestTimeoutError(method, path, ms) {
135
161
  function isTransientPollingStatus(status) {
136
162
  return status === 0 || status === 429 || status >= 500;
137
163
  }
164
+ /**
165
+ * How long a transient polling rejection asked us to wait, in ms.
166
+ *
167
+ * A 429 from the relayer's rate limiter is not an invitation to poll again in
168
+ * a second. The limiter counts our own status reads, so answering a
169
+ * `retry_after_seconds: 60` with the 10s backoff cap re-trips it on every
170
+ * attempt and the loop starves itself: the job then reads as "still uploading"
171
+ * for as long as the caller is willing to wait — including long after it has
172
+ * actually failed, which is the state that costs a user their fact.
173
+ *
174
+ * Clamped to what is left of the caller's own budget, so a 10-minute backoff
175
+ * costs at most the wait the caller already asked for. The loop then spends
176
+ * that remainder on one final read at the boundary rather than on a backoff
177
+ * curve nobody asked for.
178
+ */
179
+ function retryAfterDelayMs(err, deadline) {
180
+ const seconds = err.retryAfterSeconds
181
+ ?? retryAfterSecondsFromBody(err.cause);
182
+ if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0)
183
+ return 0;
184
+ return Math.max(0, Math.min(seconds * 1000, deadline - Date.now()));
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
+ }
204
+ /**
205
+ * The relayer states the backoff in the 429 body as well as in `Retry-After`.
206
+ * A proxy that strips the header must not cost us the hint.
207
+ */
208
+ function retryAfterSecondsFromBody(cause) {
209
+ if (typeof cause !== "string")
210
+ return undefined;
211
+ try {
212
+ const parsed = JSON.parse(cause);
213
+ const seconds = Number(parsed?.retry_after_seconds);
214
+ return Number.isFinite(seconds) ? seconds : undefined;
215
+ }
216
+ catch {
217
+ return undefined;
218
+ }
219
+ }
138
220
  /**
139
221
  * Normalise the legacy `(text, namespace)` and new `(text, options)`
140
222
  * overloads of `analyze()` / `analyzeAndWait()` into a single
@@ -181,6 +263,7 @@ function normalizeSuiNetworkForGrpc(network) {
181
263
  export class MemWal {
182
264
  privateKey;
183
265
  publicKey = null;
266
+ destroyed = false;
184
267
  serverUrl;
185
268
  namespace;
186
269
  accountId;
@@ -238,6 +321,7 @@ export class MemWal {
238
321
  * Prevents key extraction from V8 heap dumps.
239
322
  */
240
323
  destroy() {
324
+ this.destroyed = true;
241
325
  if (this.privateKey) {
242
326
  this.privateKey.fill(0);
243
327
  }
@@ -258,11 +342,13 @@ export class MemWal {
258
342
  /**
259
343
  * Submit a remember request and return as soon as the server accepts the job.
260
344
  */
261
- async rememberAsync(text, namespace, options = {}) {
262
- 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;
263
349
  const requestIdentity = `${resolvedNamespace}\0${text}`;
264
- const generatedKey = options.idempotencyKey === undefined;
265
- const idempotencyKey = options.idempotencyKey
350
+ const generatedKey = split.options.idempotencyKey === undefined;
351
+ const idempotencyKey = split.options.idempotencyKey
266
352
  ?? this.pendingRememberKeys.get(requestIdentity)
267
353
  ?? (await derivedIdempotencyKey(requestIdentity));
268
354
  if (generatedKey)
@@ -282,7 +368,18 @@ export class MemWal {
282
368
  * resolves at the terminal state and hides progress.
283
369
  */
284
370
  async getRememberStatus(jobId) {
285
- 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 });
286
383
  if (!("status" in status)) {
287
384
  return {
288
385
  job_id: jobId,
@@ -296,11 +393,22 @@ export class MemWal {
296
393
  * Poll an accepted remember job until it reaches a terminal state.
297
394
  */
298
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
+ }
299
402
  const { pollIntervalMs = 1500, timeoutMs = 60_000 } = opts;
300
403
  const deadline = Date.now() + timeoutMs;
301
404
  let attempt = 0;
405
+ let retryAfterMs = 0;
406
+ let sawRateLimit = false;
302
407
  while (Date.now() < deadline) {
303
- await sleep(pollingDelayMs(pollIntervalMs, attempt++));
408
+ // A retry-after the server just gave us wins over our own curve;
409
+ // the backoff resumes from where it was on the next normal poll.
410
+ await sleep(retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++));
411
+ retryAfterMs = 0;
304
412
  let status;
305
413
  try {
306
414
  status = await this.signedRequest("GET", `/api/remember/${jobId}`, {}, [200, 404],
@@ -314,11 +422,14 @@ export class MemWal {
314
422
  // and the client deadline keeps ONE stalled poll from
315
423
  // swallowing the entire budget, so the loop still gets to
316
424
  // retry. An expired poll surfaces as a transient 504.
317
- { timeoutMs: this.pollDeadlineMs(deadline) });
425
+ { timeoutMs: this.pollDeadlineMs(deadline), includeDelegateKey: false });
318
426
  }
319
427
  catch (err) {
320
428
  const httpStatus = err.status ?? 0;
321
429
  if (isTransientPollingStatus(httpStatus)) {
430
+ if (httpStatus === 429)
431
+ sawRateLimit = true;
432
+ retryAfterMs = retryAfterDelayMs(err, deadline);
322
433
  continue;
323
434
  }
324
435
  throw err;
@@ -342,22 +453,26 @@ export class MemWal {
342
453
  throw Object.assign(new Error(`remember job failed: ${redactInternalUrls(status.error ?? "unknown error")}`), { status: 500, jobId });
343
454
  }
344
455
  }
345
- 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 });
346
458
  }
347
459
  /**
348
460
  * Remember something and wait for the background job to complete.
349
461
  */
350
- async rememberAndWait(text, namespace, opts = {}) {
351
- const resolvedNamespace = namespace ?? this.namespace;
462
+ async rememberAndWait(text, namespaceOrOptions, opts) {
463
+ const split = splitRememberArgs(namespaceOrOptions, opts);
464
+ const resolvedNamespace = split.namespace ?? this.namespace;
352
465
  const requestIdentity = `${resolvedNamespace}\0${text}`;
353
- const generatedKey = opts.idempotencyKey === undefined;
354
- const idempotencyKey = opts.idempotencyKey
466
+ const generatedKey = split.options.idempotencyKey === undefined;
467
+ const idempotencyKey = split.options.idempotencyKey
355
468
  ?? this.pendingRememberKeys.get(requestIdentity)
356
469
  ?? (await derivedIdempotencyKey(requestIdentity));
357
470
  if (generatedKey)
358
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)
359
474
  const accepted = await this.rememberAsync(text, resolvedNamespace, { idempotencyKey });
360
- const completed = await this.waitForRememberJob(accepted.job_id, opts);
475
+ const completed = await this.waitForRememberJob(accepted.job_id, split.options);
361
476
  // Clear only after terminal success. A polling timeout/transport failure
362
477
  // keeps the key so retrying the high-level operation reuses the same job.
363
478
  if (generatedKey)
@@ -370,11 +485,11 @@ export class MemWal {
370
485
  * The relayer continues embedding, encrypting, uploading, and indexing in the background.
371
486
  * Use rememberAndWait() when the caller needs the final blob_id before continuing.
372
487
  *
373
- * @param text - The text to remember
374
- * @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)
375
490
  */
376
- async remember(text, namespace, options = {}) {
377
- return this.rememberAsync(text, namespace, options);
491
+ async remember(text, namespaceOrOptions, options) {
492
+ return this.rememberAsync(text, namespaceOrOptions, options);
378
493
  }
379
494
  /**
380
495
  * Remember multiple memories in one batched request (ENG-1408).
@@ -401,6 +516,13 @@ export class MemWal {
401
516
  if (!Array.isArray(items) || items.length === 0) {
402
517
  throw new Error("rememberBulkAsync: items must be a non-empty array");
403
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
+ });
404
526
  const normalised = items.map((item) => ({
405
527
  text: item.text,
406
528
  namespace: item.namespace ?? this.namespace,
@@ -412,7 +534,9 @@ export class MemWal {
412
534
  return accepted;
413
535
  }
414
536
  async getRememberBulkStatus(jobIds, opts = {}) {
415
- 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 });
416
540
  }
417
541
  async waitForRememberJobs(jobIds, namespaces = [], opts = {}) {
418
542
  const { pollIntervalMs = 1500, timeoutMs = 120_000 } = opts;
@@ -426,8 +550,59 @@ export class MemWal {
426
550
  }));
427
551
  const pending = new Set(jobIds);
428
552
  let attempt = 0;
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
+ };
429
601
  while (pending.size > 0 && Date.now() < deadline) {
430
- await sleep(pollingDelayMs(pollIntervalMs, attempt++));
602
+ // A retry-after the server just gave us wins over our own curve;
603
+ // the backoff resumes from where it was on the next normal poll.
604
+ await sleep(retryAfterMs > 0 ? retryAfterMs : pollingDelayMs(pollIntervalMs, attempt++));
605
+ retryAfterMs = 0;
431
606
  const pendingIds = jobIds.filter((jobId) => pending.has(jobId));
432
607
  if (pendingIds.length === 0) {
433
608
  break;
@@ -442,10 +617,15 @@ export class MemWal {
442
617
  catch (err) {
443
618
  const httpStatus = err.status ?? 0;
444
619
  if (isTransientPollingStatus(httpStatus)) {
620
+ lastRefusal = httpStatus;
621
+ if (httpStatus === 429)
622
+ sawRateLimit = true;
623
+ retryAfterMs = retryAfterDelayMs(err, deadline);
445
624
  continue;
446
625
  }
447
626
  throw err;
448
627
  }
628
+ answered = true;
449
629
  const statusById = new Map();
450
630
  for (const item of batchStatus.results) {
451
631
  const bucket = statusById.get(item.job_id);
@@ -461,29 +641,46 @@ export class MemWal {
461
641
  if (!status) {
462
642
  continue;
463
643
  }
464
- const idx = jobIds.indexOf(jobId);
465
- if (status.status === "done") {
466
- results[idx] = {
467
- id: jobId,
468
- blob_id: status.blob_id ?? "",
469
- status: "done",
470
- namespace: namespaces[idx] ?? this.namespace,
471
- };
472
- pending.delete(jobId);
473
- }
474
- else if (status.status === "failed" || status.status === "not_found") {
475
- results[idx] = {
476
- id: jobId,
477
- blob_id: "",
478
- status: "failed",
479
- namespace: namespaces[idx] ?? this.namespace,
480
- error: status.status === "not_found"
481
- ? "job not found"
482
- : redactInternalUrls(status.error ?? "unknown error"),
483
- };
484
- 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);
485
659
  }
486
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
+ }
487
684
  }
488
685
  const succeeded = results.filter((r) => r.status === "done").length;
489
686
  return {
@@ -578,7 +775,12 @@ export class MemWal {
578
775
  options = { limit: limitOrOptions, namespace };
579
776
  }
580
777
  else {
581
- 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
+ }
582
784
  }
583
785
  }
584
786
  const limit = options.topK ?? options.limit ?? 10;
@@ -597,6 +799,9 @@ export class MemWal {
597
799
  // request byte-identical and the relayer applies its own
598
800
  // "relevance" default.
599
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,
600
805
  }, { timeoutMs: RECALL_REQUEST_TIMEOUT_MS });
601
806
  let processed = result;
602
807
  if (typeof options.maxDistance === "number") {
@@ -698,6 +903,7 @@ export class MemWal {
698
903
  * @returns EmbedResult with vector
699
904
  */
700
905
  async embed(text) {
906
+ assertNonBlankText(text, "text cannot be empty");
701
907
  return this.signedRequest("POST", "/api/embed", { text }, { includeDelegateKey: false });
702
908
  }
703
909
  /**
@@ -716,6 +922,7 @@ export class MemWal {
716
922
  * ```
717
923
  */
718
924
  async analyze(text, namespaceOrOptions) {
925
+ assertNonBlankText(text);
719
926
  const options = normalizeAnalyzeOptions(namespaceOrOptions);
720
927
  const body = {
721
928
  text,
@@ -881,7 +1088,7 @@ export class MemWal {
881
1088
  if (!res.ok) {
882
1089
  throw new Error(`Health check failed: ${res.status}`);
883
1090
  }
884
- return res.json();
1091
+ return res.body;
885
1092
  }
886
1093
  /**
887
1094
  * Fetch and validate the relayer compatibility contract.
@@ -894,17 +1101,32 @@ export class MemWal {
894
1101
  */
895
1102
  async getPublicKeyHex() {
896
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();
897
1109
  return bytesToHex(pk);
898
1110
  }
899
1111
  // ============================================================
900
1112
  // Internal: Signed HTTP Requests
901
1113
  // ============================================================
902
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();
903
1120
  if (!this.publicKey) {
904
1121
  const ed = await getEd();
905
- 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;
906
1128
  }
907
- return this.publicKey;
1129
+ return this.publicKey.slice();
908
1130
  }
909
1131
  async ensureCompatibleRelayer() {
910
1132
  if (this.relayerVersionMetadata)
@@ -920,7 +1142,7 @@ export class MemWal {
920
1142
  const versionRes = await this.fetchWithDeadline(`${this.serverUrl}/version`, { method: "GET" });
921
1143
  let body;
922
1144
  if (versionRes.ok) {
923
- body = (await versionRes.json());
1145
+ body = versionRes.body;
924
1146
  }
925
1147
  else if (versionRes.status === 404 || versionRes.status === 405) {
926
1148
  const healthRes = await this.fetchWithDeadline(`${this.serverUrl}/health`, { method: "GET" });
@@ -928,7 +1150,7 @@ export class MemWal {
928
1150
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ` +
929
1151
  `${versionRes.status}, and GET /health returned ${healthRes.status}`);
930
1152
  }
931
- body = (await healthRes.json());
1153
+ body = healthRes.body;
932
1154
  }
933
1155
  else {
934
1156
  throw new Error(`Walrus Memory compatibility check failed: GET /version returned ${versionRes.status}`);
@@ -965,7 +1187,7 @@ export class MemWal {
965
1187
  if (!res.ok) {
966
1188
  throw new Error(`GET /config returned ${res.status}`);
967
1189
  }
968
- const body = (await res.json());
1190
+ const body = res.body;
969
1191
  if (typeof body.packageId !== "string" || !body.packageId ||
970
1192
  typeof body.network !== "string" || !body.network) {
971
1193
  throw new Error("GET /config response missing packageId / network");
@@ -1161,7 +1383,7 @@ export class MemWal {
1161
1383
  * Pass [200, 202] for endpoints that return 202 Accepted.
1162
1384
  */
1163
1385
  /**
1164
- * `fetch` with this client's deadline applied.
1386
+ * `fetch` plus the JSON body read, with this client's deadline applied across both.
1165
1387
  *
1166
1388
  * For the handshake endpoints that skip request signing — `/health`,
1167
1389
  * `/version`, `/config`. They are the worst place to leave unbounded: the
@@ -1177,7 +1399,12 @@ export class MemWal {
1177
1399
  const ms = timeoutMs ?? this.requestTimeoutMs;
1178
1400
  const deadline = deadlineSignal(ms);
1179
1401
  try {
1180
- 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
+ };
1181
1408
  }
1182
1409
  catch (err) {
1183
1410
  if (deadline.timedOut()) {
@@ -1196,6 +1423,9 @@ export class MemWal {
1196
1423
  const options = Array.isArray(acceptedStatusesOrOptions)
1197
1424
  ? requestOptions
1198
1425
  : acceptedStatusesOrOptions;
1426
+ // Before the version probe. A destroyed client must not open GET /version. (#1090)
1427
+ if (this.destroyed)
1428
+ throw destroyedClientError();
1199
1429
  await this.ensureCompatibleRelayer();
1200
1430
  const ed = await getEd();
1201
1431
  const timestamp = Math.floor(Date.now() / 1000).toString();
@@ -1210,9 +1440,19 @@ export class MemWal {
1210
1440
  // LOW-23: Build message to sign — now includes nonce AND account id
1211
1441
  const message = `${timestamp}.${method}.${path}.${bodySha256}.${nonce}.${this.accountId}`;
1212
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();
1213
1447
  // Sign with Ed25519
1214
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();
1215
1453
  const publicKey = await this.getPublicKey();
1454
+ if (this.destroyed)
1455
+ throw destroyedClientError();
1216
1456
  // Make HTTP request
1217
1457
  const url = `${this.serverUrl}${path}`;
1218
1458
  const headers = {
@@ -1235,51 +1475,51 @@ export class MemWal {
1235
1475
  // for as long as the connection stays open.
1236
1476
  const deadlineMs = options.timeoutMs ?? this.requestTimeoutMs;
1237
1477
  const deadline = deadlineSignal(deadlineMs, options.signal);
1238
- let res;
1239
1478
  try {
1240
- res = await fetch(url, {
1479
+ const res = await fetch(url, {
1241
1480
  method,
1242
1481
  headers,
1243
1482
  body: method === "GET" ? undefined : bodyStr,
1244
1483
  signal: deadline.signal,
1245
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());
1246
1511
  }
1247
1512
  catch (err) {
1248
1513
  // Translate our own expiry into something a caller can classify.
1249
1514
  // An abort the CALLER asked for is theirs and propagates untouched.
1250
- if (deadline.timedOut())
1515
+ if (deadline.timedOut() && err.status === undefined) {
1251
1516
  throw requestTimeoutError(method, path, deadlineMs);
1517
+ }
1252
1518
  throw err;
1253
1519
  }
1254
1520
  finally {
1255
1521
  deadline.dispose();
1256
1522
  }
1257
- if (!acceptedStatuses.includes(res.status)) {
1258
- // LOW-26: sanitize server error bodies before surfacing to callers.
1259
- const raw = await res.text();
1260
- const compatibilityError = compatibilityErrorFromStatus(res.status, raw);
1261
- if (compatibilityError)
1262
- throw compatibilityError;
1263
- // A stale/future-dated signature is rejected with 401 + a machine-
1264
- // readable reason header. Surface it as an actionable clock-drift
1265
- // error rather than an opaque 401 so the caller can fix node time.
1266
- const clockDriftError = clockDriftErrorFromResponse(res);
1267
- if (clockDriftError)
1268
- throw clockDriftError;
1269
- const { message, serverCode } = sanitizeServerError(res.status, raw, res.headers.get("x-auth-error"));
1270
- const err = new Error(message);
1271
- err.status = res.status;
1272
- if (serverCode)
1273
- err.serverCode = serverCode;
1274
- const retryAfter = Number(res.headers.get("retry-after"));
1275
- if (Number.isFinite(retryAfter) && retryAfter > 0) {
1276
- err.retryAfterSeconds = retryAfter;
1277
- }
1278
- // Preserve raw body on `cause` for in-process debugging only.
1279
- err.cause = raw;
1280
- throw err;
1281
- }
1282
- return res.json();
1283
1523
  }
1284
1524
  }
1285
1525
  //# sourceMappingURL=memwal.js.map