wontopos 2.2.30 → 2.2.32

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/README.md CHANGED
@@ -160,6 +160,19 @@ const mem = new Client({ apiKey: "...", baseUrl: "https://wos.your-host.com" });
160
160
  - Homepage: <https://wontopos.com>
161
161
  - API reference: <https://wontopos.com/en/why> (Developers tab)
162
162
 
163
+ ## Reporting a bug
164
+
165
+ Found something wrong, or something that looks unsafe? Tell us — one person reads
166
+ every report.
167
+
168
+ - Bugs: <https://wontopos.com/contact?topic=bug>
169
+ - Security: <https://wontopos.com/contact?topic=security> (also published at
170
+ [`/.well-known/security.txt`](https://wontopos.com/.well-known/security.txt))
171
+
172
+ Include the SDK version (`the version in package.json`) and the language. If it involves a store id or a
173
+ memory, describe the shape rather than pasting the contents — we do not need your
174
+ data to fix it.
175
+
163
176
  ## Changelog
164
177
 
165
178
  The three clients release in lockstep — same version, same surface, same day.
@@ -145,6 +145,142 @@ export interface StatusResult {
145
145
  status?: string;
146
146
  [key: string]: unknown;
147
147
  }
148
+ /**
149
+ * An image attached to a memory, passed to `add`/`store` via `opts.image`.
150
+ *
151
+ * What the service keeps is NOT your original. An image whose long edge is over
152
+ * 1568px is downscaled to 1568 before anything else happens, and that smaller
153
+ * picture is what gets embedded, stored, and handed back by `getImage`. Nothing in
154
+ * the retrieval path ever looks above 1568 — the embedder and the reader both
155
+ * shrink to it — so the extra pixels would be bytes nobody reads. This is a memory
156
+ * service, not a photo host: the picture it holds has the resolution of a memory.
157
+ *
158
+ * Keep your own copy if you need the full-resolution file. Either archive it
159
+ * yourself, or put its URL in `reference` — we store that string and never open it.
160
+ *
161
+ * You are billed for the picture we keep, so downscaling never costs you more.
162
+ */
163
+ export interface ImageInput {
164
+ /** base64 of the image. A `data:image/...;base64,` prefix is accepted and stripped. */
165
+ data: string;
166
+ /** Where YOUR copy of the original lives. Stored as-is; the service never fetches it. */
167
+ reference?: string;
168
+ /**
169
+ * When the image was TAKEN (RFC3339), if you know it — usually from EXIF.
170
+ *
171
+ * Worth passing: an image knows a moment that its caption does not. This fills
172
+ * `metadata.event_date` when that is empty, so "the day we moved" sorts by when it
173
+ * happened rather than by when it was uploaded.
174
+ */
175
+ taken_at?: string;
176
+ }
177
+ /** `getImage` → the picture the service holds, plus what it actually is. */
178
+ export interface ImageBytes {
179
+ /**
180
+ * The image as stored. Write it to a file, or wrap it in a Blob to show it.
181
+ *
182
+ * This is the service's copy, not necessarily your upload: anything over 1568px
183
+ * on its long edge was downscaled on the way in (see `ImageInput`).
184
+ */
185
+ bytes: Uint8Array;
186
+ /** Sniffed from the BYTES, not from whatever the upload was named — e.g. `image/jpeg`. */
187
+ contentType: string;
188
+ }
189
+ /** `forgetImage` → what happened, or (with `preview`) what would happen. */
190
+ export interface ImageDeleteResult {
191
+ /** `"image_deleted"`, or `"preview"` when nothing was touched. */
192
+ status?: string;
193
+ memory_id?: string;
194
+ /**
195
+ * Whether the MEMORY survives losing its image.
196
+ *
197
+ * A captioned image keeps its text and only loses the image. An image stored with no
198
+ * caption IS the memory, so deleting the image deletes the memory — and the service
199
+ * says so here rather than silently taking more than you asked for. Call with
200
+ * `preview: true` first if that distinction matters to you.
201
+ */
202
+ memory_kept?: boolean;
203
+ /** Plain-language note about the above, when there is something to say. */
204
+ note?: string | null;
205
+ /** Only on a preview. */
206
+ would_delete_image?: boolean;
207
+ [key: string]: unknown;
208
+ }
209
+ /** `listImages` → one page of image memories, newest first. */
210
+ export interface ImagePage {
211
+ images: Memory[];
212
+ /** TOTAL images in the store, not the size of this page. */
213
+ count?: number;
214
+ has_more?: boolean;
215
+ /** Hand these two back as `before` / `skipIds` to get the next page. */
216
+ next_before?: string | null;
217
+ next_skip_ids?: string[];
218
+ [key: string]: unknown;
219
+ }
220
+ /** `revisions` → how much of this store has been edited since it was written. */
221
+ export interface RevisionsResult {
222
+ /** Memories a transform has touched (supersede, update, retract, image removed). */
223
+ revised?: number;
224
+ /** Memories nothing has touched since they were written. Always `total - revised`. */
225
+ unrevised?: number;
226
+ /** Every memory in the store. Atoms — the fragments search uses internally — are not counted. */
227
+ total?: number;
228
+ /** What `revised` counts, spelled out by the service. */
229
+ counts?: string;
230
+ /** What it does NOT count — deletions leave nothing to count. */
231
+ excludes?: string;
232
+ /** Which side was paged, echoed back. Only present when you asked for a page. */
233
+ include?: "revised" | "unrevised";
234
+ /** TOTAL memories behind this page, not the size of the page. Only with `include`. */
235
+ matched?: number;
236
+ /** One page, at most 20. **Absent unless you asked for it** — see `revisions()`. */
237
+ memories?: Memory[];
238
+ has_more?: boolean;
239
+ /** Hand these two back as `before` / `skipIds` to get the next page. */
240
+ next_before?: string | null;
241
+ next_skip_ids?: string[];
242
+ /** Which order the page is in — by when each memory was STORED, not when it was edited. */
243
+ ordered_by?: string;
244
+ [key: string]: unknown;
245
+ }
246
+ /** One link in a memory's supersede chain. */
247
+ export interface LineageStep {
248
+ memory_id?: string;
249
+ content?: string;
250
+ speaker?: string | null;
251
+ created_at?: string | null;
252
+ /** When this link was superseded (RFC3339), or null while it is still current. */
253
+ changed_at?: string | null;
254
+ /** What happened here — e.g. how the replacement related to this version. */
255
+ action?: string | null;
256
+ confidence?: number | null;
257
+ superseded_by?: string | null;
258
+ /** True for the one version that is still in force. */
259
+ is_current?: boolean;
260
+ [key: string]: unknown;
261
+ }
262
+ /** `lineage` → the full chain of edits behind one memory, oldest first. */
263
+ export interface LineageResult {
264
+ memory_id?: string;
265
+ chain: LineageStep[];
266
+ count?: number;
267
+ /** True when the chain was longer than the service would walk. */
268
+ truncated?: boolean;
269
+ [key: string]: unknown;
270
+ }
271
+ /** `bySpeaker` → one page of what a given person said. */
272
+ export interface SpeakerPage {
273
+ speaker?: string;
274
+ memories: Memory[];
275
+ /** Sentence-level fragments behind these memories — what a delete would actually remove. */
276
+ chunks?: number;
277
+ points_to_delete?: number;
278
+ returned?: number;
279
+ has_more?: boolean;
280
+ next_before?: string | null;
281
+ next_skip_ids?: string[];
282
+ [key: string]: unknown;
283
+ }
148
284
  /** `update` (supersede) → old and new memory ids. */
149
285
  export interface UpdateResult {
150
286
  old_memory_id?: string;
@@ -296,6 +432,31 @@ export interface SearchOptions {
296
432
  speaker?: string;
297
433
  /** Restrict the search to part of the store — see {@link SearchFilters}. */
298
434
  filters?: SearchFilters;
435
+ /**
436
+ * Re-ask passes, 0–3. After the first retrieval the service asks the engine again up
437
+ * to this many times, each time telling it what was already returned so it skips
438
+ * those and reaches further back. Retrieval stays purely semantic — no LLM at any
439
+ * value. Stops early when a pass finds nothing new; `verify_used` in the response
440
+ * says how many actually ran.
441
+ *
442
+ * Each pass is another engine call and can add up to `limit` more memories, so it
443
+ * costs more — you are billed for what is delivered. Default 0. Worth it on questions
444
+ * that need several distinct memories from far apart in the history; it does little
445
+ * on a single-fact lookup.
446
+ *
447
+ * ⚠️Requires a re-ask-capable model. Older ones REFUSE the call (403) rather than
448
+ * quietly charging you for passes that never happened.
449
+ */
450
+ verify?: number;
451
+ /**
452
+ * How many image memories the answer may carry, 0–5. Default 1; 0 asks for none.
453
+ * Out of range is refused, not clamped — silently cutting 5 to 1 would leave you
454
+ * believing you got five.
455
+ *
456
+ * ⚠️Requires an image-capable model, and is refused (403) on one without it rather
457
+ * than answering with no images.
458
+ */
459
+ max_images?: number;
299
460
  [key: string]: unknown;
300
461
  }
301
462
  /**
@@ -316,6 +477,14 @@ export interface SearchOptions {
316
477
  */
317
478
  export interface WriteOptions {
318
479
  idempotencyKey?: string;
480
+ /**
481
+ * An image to store alongside the text (Tablet 2 and newer).
482
+ *
483
+ * `content` may be empty when you pass one — then the image IS the memory and is
484
+ * searchable on its own. Older models have no image channel and will reject the
485
+ * write rather than store the caption and quietly drop the image.
486
+ */
487
+ image?: ImageInput;
319
488
  }
320
489
  export interface ClientOptions {
321
490
  apiKey: string;
@@ -439,6 +608,18 @@ export declare class Client {
439
608
  recall(query: string, userId?: string, opts?: {
440
609
  form?: string;
441
610
  tz?: number;
611
+ /**
612
+ * Long-term memories to recall, 5–20. Default 10. Out of range is refused, not
613
+ * clamped — asking for 20 and silently getting 10 reads as "that is all there is".
614
+ *
615
+ * ⚠️Needs a limit-aware model. An older one recalls a fixed ten no matter what you
616
+ * send, so the API refuses the call (403) rather than answering with a number you
617
+ * did not ask for.
618
+ */
619
+ limit?: number;
620
+ /** Chunks of surrounding context attached around the best match, 0–20. Default 10;
621
+ * 0 attaches none. Same model floor as `limit`. */
622
+ context_limit?: number;
442
623
  }): Promise<RecallResult>;
443
624
  /** Run a built-in engram ("deep_recall" | "timeline" | "gather"). Returns the merged result.
444
625
  * `form`/`tz` render memory times (memoir/archive) on Scroll 1.2+, same as search/recall. */
@@ -481,6 +662,134 @@ export declare class Client {
481
662
  }): AsyncGenerator<Memory>;
482
663
  /** Collect ALL of a store's memories into an array (original text + metadata, no vectors). */
483
664
  exportMemories(userId?: string): Promise<Memory[]>;
665
+ /**
666
+ * Fetch the bytes of an image memory — the picture the SERVICE holds.
667
+ *
668
+ * Not necessarily your upload: an image whose long edge was over 1568px was
669
+ * downscaled to 1568 on the way in, and that is what was embedded, stored and
670
+ * comes back here. Nothing in the retrieval path looks above 1568, so the extra
671
+ * pixels would be bytes nobody reads. Keep your own copy for the full-resolution
672
+ * file. The type is sniffed from the bytes themselves rather
673
+ * than from whatever the file was called. Rejects with `NotFoundError` when this
674
+ * memory has no image, or when the service was not configured to keep originals —
675
+ * it says "no" instead of handing back something empty, so "a memory with no image"
676
+ * never looks the same as "an image we lost".
677
+ *
678
+ * const { bytes, contentType } = await mem.getImage(undefined, id);
679
+ * await fs.writeFile("image.jpg", bytes);
680
+ */
681
+ getImage(userId: string | undefined, memoryId: string): Promise<ImageBytes>;
682
+ /**
683
+ * Remove the PHOTO from a memory, keeping its text.
684
+ *
685
+ * Except when there is no text: an image stored without a caption *is* the memory, so
686
+ * deleting the image deletes it. That is the one case worth checking before you
687
+ * commit, which is what `preview` is for — it reports `memory_kept` and changes
688
+ * nothing.
689
+ *
690
+ * const p = await mem.forgetImage(undefined, id, { preview: true });
691
+ * if (p.memory_kept === false) { /* this would delete the whole memory *\/ }
692
+ */
693
+ forgetImage(userId: string | undefined, memoryId: string, opts?: {
694
+ preview?: boolean;
695
+ }): Promise<ImageDeleteResult>;
696
+ /**
697
+ * List a store's image memories, newest first, and count them.
698
+ *
699
+ * `count` is the TOTAL in the store, not the size of the page — so you can show
700
+ * "142 images" without walking every page. Paging is by cursor, not offset: hand
701
+ * `next_before` and `next_skip_ids` back as `before` / `skipIds`. The pair exists
702
+ * because several images can share a timestamp, and a timestamp alone would either
703
+ * repeat them or skip them.
704
+ */
705
+ listImages(userId?: string, opts?: {
706
+ limit?: number;
707
+ before?: string;
708
+ skipIds?: string[];
709
+ }): Promise<ImagePage>;
710
+ /** Async-iterate every image memory, paging under the hood. */
711
+ iterImages(userId?: string, opts?: {
712
+ pageSize?: number;
713
+ }): AsyncGenerator<Memory>;
714
+ /**
715
+ * How much of this store has been altered since it was written.
716
+ *
717
+ * This one is aimed at the MODEL, not at you. An assistant leaning on its own memory
718
+ * should be able to ask how far that memory has been edited underneath it — a store
719
+ * nobody has touched reads differently from one where a third of the facts were
720
+ * rewritten. Free, and it never reaches the retrieval path.
721
+ *
722
+ * Counts memories a transform touched (supersede, update, retract, image removed).
723
+ * Deletions are NOT counted: a deleted memory leaves nothing to count. Neither are
724
+ * atoms, the sentence fragments search uses internally — nobody stored one, so they
725
+ * do not belong in a ratio that answers "how much of MY memory changed".
726
+ *
727
+ * ★By default this returns COUNTS ONLY, and the answer is the same size for a store
728
+ * of a hundred memories and a store of a hundred million. That is deliberate: a model
729
+ * asks this mid-conversation, and an answer that grew with the store would be
730
+ * unusable for exactly the customers who most need to ask.
731
+ *
732
+ * To see WHICH memories, ask for one side and page through it — at most 20 per call,
733
+ * and never both sides in one response:
734
+ *
735
+ * ```ts
736
+ * const { revised, unrevised, total } = await mem.revisions(); // numbers only
737
+ *
738
+ * let before: string | undefined, skipIds: string[] | undefined;
739
+ * for (;;) {
740
+ * const p = await mem.revisions(undefined, { include: "revised", before, skipIds });
741
+ * for (const m of p.memories ?? []) console.log(m.content);
742
+ * if (!p.has_more || !p.next_before) break;
743
+ * before = p.next_before;
744
+ * skipIds = p.next_skip_ids;
745
+ * }
746
+ * ```
747
+ *
748
+ * ⚠️Pages are ordered by when each memory was STORED, not by when it was edited.
749
+ * The response says so in `ordered_by`.
750
+ *
751
+ * ★Served from `/api/v1/won/*`, not `/api/v1/memory/*`. Won is the surface for calls
752
+ * a model makes ABOUT its memory rather than calls an application makes WITH it, and
753
+ * the address says so. The old path still answers, for clients published before
754
+ * 2026-08-18, and both share one rate-limit budget.
755
+ */
756
+ revisions(userId?: string, opts?: {
757
+ /**
758
+ * Omit for counts only. Set it to ALSO get one page of the memories behind that
759
+ * number. One side per call — there is no way to ask for both lists at once.
760
+ */
761
+ include?: "revised" | "unrevised";
762
+ /** Memories per page. 20 is both the default and the ceiling; more is rejected. */
763
+ limit?: number;
764
+ /** Cursor: `next_before` from the previous page. */
765
+ before?: string;
766
+ /** Cursor: `next_skip_ids` from the previous page. Hand back what you were given. */
767
+ skipIds?: string[];
768
+ }): Promise<RevisionsResult>;
769
+ /**
770
+ * The full chain of edits behind one memory, oldest first.
771
+ *
772
+ * `is_current` marks the version in force. Use it to answer "what did this used to
773
+ * say, and when did it change" — `revisions()` tells you HOW MUCH a store moved,
774
+ * this tells you what happened to one fact.
775
+ */
776
+ lineage(userId: string | undefined, memoryId: string): Promise<LineageResult>;
777
+ /**
778
+ * What one person said, newest first.
779
+ *
780
+ * `speaker` is the tag written at store time (`metadata.speaker`) — `"me"` for the
781
+ * assistant's own words, otherwise a person's name. Same cursor paging as
782
+ * `listImages`.
783
+ *
784
+ * `chunks` / `points_to_delete` report the sentence-level fragments behind these
785
+ * memories, which is what a delete would actually remove — usually larger than
786
+ * `returned`, and worth showing before anyone confirms one.
787
+ */
788
+ bySpeaker(speaker: string, userId?: string, opts?: {
789
+ limit?: number;
790
+ before?: string;
791
+ skipIds?: string[];
792
+ }): Promise<SpeakerPage>;
484
793
  /** Check connectivity AND that the API key works. Resolves `true`, or rejects — an
485
794
  * `AuthenticationError` (bad key), `PaymentRequiredError` (valid key but no card /
486
795
  * depleted balance), or `APIConnectionError` (unreachable). Makes one metered request. */
@@ -523,6 +832,19 @@ export declare class Client {
523
832
  * this is destructive, so it never falls back to the default store. */
524
833
  deleteAll(userId: string): Promise<StatusResult>;
525
834
  private post;
835
+ /**
836
+ * One request that answers with BYTES rather than JSON.
837
+ *
838
+ * Only `/memory/image` does this, and it is why this cannot go through `request()`:
839
+ * that path reads the body as text and insists the result parses to a JSON object.
840
+ * Feeding it a JPEG would throw "invalid JSON in response" — a confusing error for a
841
+ * call that actually succeeded.
842
+ *
843
+ * Errors still arrive as JSON, so those are handed back to the normal machinery: on
844
+ * a non-2xx we re-read the body as text and reuse `errorFor`, which keeps 404
845
+ * (`NotFoundError`) and 401 behaving the same as everywhere else.
846
+ */
847
+ private requestBytes;
526
848
  /** Validate an idempotency key BEFORE the network. The API answers a malformed
527
849
  * key with a 400, which on a retry path reads as "my write failed" when in fact
528
850
  * it was never attempted — cheaper and clearer to reject it here. */
@@ -532,6 +854,13 @@ export declare class Client {
532
854
  /** Read the body with a hard size cap, so a broken/hostile endpoint can't
533
855
  * make the process buffer gigabytes. */
534
856
  private readCapped;
857
+ /** The same cap, for a body that is not text.
858
+ *
859
+ * `getImage` used to call `arrayBuffer()` here, which buffers whatever arrives. The
860
+ * cap exists for a hostile or broken `baseUrl`, and a photo endpoint is exactly where
861
+ * that shows up — the JSON paths were guarded while the one path that returns
862
+ * megabytes was not. One implementation, two callers, so they cannot drift. */
863
+ private readCappedBytes;
535
864
  private request;
536
865
  }
537
866
  /** Back-compat alias: older code used `WME`. */
package/dist/wontopos.js CHANGED
@@ -37,7 +37,7 @@
37
37
  * runtime's (never disabled by this SDK; Node 18+ floors TLS at 1.2). Prefer
38
38
  * `Client.fromEnv()` over keys in source code.
39
39
  */
40
- const VERSION = "2.2.30";
40
+ const VERSION = "2.2.32";
41
41
  /** Runtime info helps support debug a report ("node 18 on Windows...") —
42
42
  * platform only, never anything identifying. Browsers have no `process` (and
43
43
  * silently drop the UA header anyway). */
@@ -132,6 +132,45 @@ export function _resetStoreIdWarnings() {
132
132
  const NO_BODY_STATUS = new Set([204, 205, 304]);
133
133
  /** Paging backstop: bound the walk so a fresh-cursor-forever server can't loop us. */
134
134
  const MAX_PAGES = 1_000_000;
135
+ /**
136
+ * Put an image into the shape the API expects, and fail loudly on the parts we can
137
+ * check from here.
138
+ *
139
+ * Deliberately NOT checked: the byte ceiling. It is a server setting (`/health`
140
+ * reports it as `memory.images.max_bytes`), so a number baked in here would drift the
141
+ * first time that config changes and would reject an image the service would have
142
+ * taken. What we do check is what cannot change: an empty payload, and a `data:` URL
143
+ * prefix — browsers and file pickers hand you `data:image/jpeg;base64,…`, the API
144
+ * wants the part after the comma, and the difference is invisible until the write
145
+ * fails with "not a readable image".
146
+ */
147
+ function normalizeImage(image) {
148
+ if (!image || typeof image !== "object") {
149
+ throw new Error("image must be an object — { data: '<base64>' }.");
150
+ }
151
+ if (typeof image.data !== "string" || image.data.trim() === "") {
152
+ throw new Error("image.data is required — base64 of the image (a data: URL is fine).");
153
+ }
154
+ // 🔴**다듬고 나서 접두어를 본다.** 예전엔 원본에 바로 `startsWith("data:")` 를
155
+ // 걸어서, 앞에 공백이 하나만 있어도(` data:image/png;base64,…`) 접두어를 못 떼고
156
+ // **`data:image/png;base64,` 문자열까지 통째로 base64 로** 보냈다. 엔진은
157
+ // "이미지를 읽을 수 없다"며 400 을 내고, 부르는 쪽은 왜인지 모른다.
158
+ const raw = image.data.trim();
159
+ const comma = raw.startsWith("data:") ? raw.indexOf(",") : -1;
160
+ // 🔴그리고 **가운데 공백까지** 없앤다. `base64` 명령과 `openssl base64` 는 76자마다
161
+ // 줄을 바꾼다 — 파일을 그렇게 만들어 붙여넣는 건 흔한 길인데, 양끝만 다듬으면
162
+ // 그 줄바꿈이 그대로 payload 에 남는다. base64 알파벳에 공백은 없으므로
163
+ // 전부 빼는 게 안전하다.
164
+ const data = (comma === -1 ? raw : raw.slice(comma + 1)).replace(/\s+/g, "");
165
+ if (data === "")
166
+ throw new Error("image.data is empty after stripping its data: prefix.");
167
+ const out = { data };
168
+ if (image.reference !== undefined)
169
+ out.reference = image.reference;
170
+ if (image.taken_at !== undefined)
171
+ out.taken_at = image.taken_at;
172
+ return out;
173
+ }
135
174
  /** Error codes that only occur while ESTABLISHING a connection — the request
136
175
  * never reached the server, so a retry can't double-process a write. Mid-stream
137
176
  * codes (ECONNRESET, EPIPE, UND_ERR_SOCKET, ETIMEDOUT) are ambiguous: the server
@@ -513,7 +552,10 @@ export class Client {
513
552
  * `opts.idempotencyKey`: see {@link WriteOptions} — pass one to make YOUR retry
514
553
  * of this exact write safe to repeat. */
515
554
  add(content, userId, metadata = {}, opts = {}) {
516
- return this.post("/api/v1/memory/store", { user_id: this.uid(userId), content, metadata }, opts.idempotencyKey);
555
+ const body = { user_id: this.uid(userId), content, metadata };
556
+ if (opts.image !== undefined)
557
+ body.image = normalizeImage(opts.image);
558
+ return this.post("/api/v1/memory/store", body, opts.idempotencyKey);
517
559
  }
518
560
  /** Alias of `add` — store one memory. Same surface as the Python SDK's `store`. */
519
561
  store(content, userId, metadata = {}, opts = {}) {
@@ -566,7 +608,12 @@ export class Client {
566
608
  * `form` ("memoir"/"archive", Scroll 1.2+) renders each long-term memory's time in
567
609
  * that form; `tz` is your UTC-offset hours for that rendering. */
568
610
  recall(query, userId, opts = {}) {
569
- return this.post("/api/v1/memory/recall", withForm({ user_id: this.uid(userId), query }, opts.form, opts.tz));
611
+ const body = { user_id: this.uid(userId), query };
612
+ if (opts.limit !== undefined)
613
+ body.limit = opts.limit;
614
+ if (opts.context_limit !== undefined)
615
+ body.context_limit = opts.context_limit;
616
+ return this.post("/api/v1/memory/recall", withForm(body, opts.form, opts.tz));
570
617
  }
571
618
  /** Run a built-in engram ("deep_recall" | "timeline" | "gather"). Returns the merged result.
572
619
  * `form`/`tz` render memory times (memoir/archive) on Scroll 1.2+, same as search/recall. */
@@ -640,6 +687,177 @@ export class Client {
640
687
  out.push(m);
641
688
  return out;
642
689
  }
690
+ // ----- images (Tablet 2 and newer) -----
691
+ /**
692
+ * Fetch the bytes of an image memory — the picture the SERVICE holds.
693
+ *
694
+ * Not necessarily your upload: an image whose long edge was over 1568px was
695
+ * downscaled to 1568 on the way in, and that is what was embedded, stored and
696
+ * comes back here. Nothing in the retrieval path looks above 1568, so the extra
697
+ * pixels would be bytes nobody reads. Keep your own copy for the full-resolution
698
+ * file. The type is sniffed from the bytes themselves rather
699
+ * than from whatever the file was called. Rejects with `NotFoundError` when this
700
+ * memory has no image, or when the service was not configured to keep originals —
701
+ * it says "no" instead of handing back something empty, so "a memory with no image"
702
+ * never looks the same as "an image we lost".
703
+ *
704
+ * const { bytes, contentType } = await mem.getImage(undefined, id);
705
+ * await fs.writeFile("image.jpg", bytes);
706
+ */
707
+ getImage(userId, memoryId) {
708
+ if (!memoryId || typeof memoryId !== "string") {
709
+ throw new Error("memoryId is required — the id that add/store or listImages returned.");
710
+ }
711
+ return this.requestBytes("/api/v1/memory/image", { user_id: this.uid(userId), memory_id: memoryId });
712
+ }
713
+ /**
714
+ * Remove the PHOTO from a memory, keeping its text.
715
+ *
716
+ * Except when there is no text: an image stored without a caption *is* the memory, so
717
+ * deleting the image deletes it. That is the one case worth checking before you
718
+ * commit, which is what `preview` is for — it reports `memory_kept` and changes
719
+ * nothing.
720
+ *
721
+ * const p = await mem.forgetImage(undefined, id, { preview: true });
722
+ * if (p.memory_kept === false) { /* this would delete the whole memory *\/ }
723
+ */
724
+ forgetImage(userId, memoryId, opts = {}) {
725
+ if (!memoryId || typeof memoryId !== "string") {
726
+ throw new Error("memoryId is required — the id of the memory whose image you want removed.");
727
+ }
728
+ const body = { user_id: this.uid(userId), memory_id: memoryId };
729
+ if (opts.preview)
730
+ body.preview = true;
731
+ return this.request("DELETE", "/api/v1/memory/image", body);
732
+ }
733
+ /**
734
+ * List a store's image memories, newest first, and count them.
735
+ *
736
+ * `count` is the TOTAL in the store, not the size of the page — so you can show
737
+ * "142 images" without walking every page. Paging is by cursor, not offset: hand
738
+ * `next_before` and `next_skip_ids` back as `before` / `skipIds`. The pair exists
739
+ * because several images can share a timestamp, and a timestamp alone would either
740
+ * repeat them or skip them.
741
+ */
742
+ listImages(userId, opts = {}) {
743
+ const body = { user_id: this.uid(userId) };
744
+ if (opts.limit !== undefined)
745
+ body.limit = opts.limit;
746
+ if (opts.before !== undefined)
747
+ body.before = opts.before;
748
+ if (opts.skipIds !== undefined)
749
+ body.skip_ids = opts.skipIds;
750
+ return this.post("/api/v1/memory/images", body);
751
+ }
752
+ /** Async-iterate every image memory, paging under the hood. */
753
+ async *iterImages(userId, opts = {}) {
754
+ let before;
755
+ let skipIds;
756
+ for (let page = 0; page < MAX_PAGES; page++) {
757
+ const p = await this.listImages(userId, { limit: opts.pageSize, before, skipIds });
758
+ for (const m of asRecords(p.images))
759
+ yield m;
760
+ if (!p.has_more || !p.next_before)
761
+ break;
762
+ before = p.next_before;
763
+ skipIds = Array.isArray(p.next_skip_ids) ? p.next_skip_ids : undefined;
764
+ }
765
+ }
766
+ // ----- how much has this memory been edited -----
767
+ /**
768
+ * How much of this store has been altered since it was written.
769
+ *
770
+ * This one is aimed at the MODEL, not at you. An assistant leaning on its own memory
771
+ * should be able to ask how far that memory has been edited underneath it — a store
772
+ * nobody has touched reads differently from one where a third of the facts were
773
+ * rewritten. Free, and it never reaches the retrieval path.
774
+ *
775
+ * Counts memories a transform touched (supersede, update, retract, image removed).
776
+ * Deletions are NOT counted: a deleted memory leaves nothing to count. Neither are
777
+ * atoms, the sentence fragments search uses internally — nobody stored one, so they
778
+ * do not belong in a ratio that answers "how much of MY memory changed".
779
+ *
780
+ * ★By default this returns COUNTS ONLY, and the answer is the same size for a store
781
+ * of a hundred memories and a store of a hundred million. That is deliberate: a model
782
+ * asks this mid-conversation, and an answer that grew with the store would be
783
+ * unusable for exactly the customers who most need to ask.
784
+ *
785
+ * To see WHICH memories, ask for one side and page through it — at most 20 per call,
786
+ * and never both sides in one response:
787
+ *
788
+ * ```ts
789
+ * const { revised, unrevised, total } = await mem.revisions(); // numbers only
790
+ *
791
+ * let before: string | undefined, skipIds: string[] | undefined;
792
+ * for (;;) {
793
+ * const p = await mem.revisions(undefined, { include: "revised", before, skipIds });
794
+ * for (const m of p.memories ?? []) console.log(m.content);
795
+ * if (!p.has_more || !p.next_before) break;
796
+ * before = p.next_before;
797
+ * skipIds = p.next_skip_ids;
798
+ * }
799
+ * ```
800
+ *
801
+ * ⚠️Pages are ordered by when each memory was STORED, not by when it was edited.
802
+ * The response says so in `ordered_by`.
803
+ *
804
+ * ★Served from `/api/v1/won/*`, not `/api/v1/memory/*`. Won is the surface for calls
805
+ * a model makes ABOUT its memory rather than calls an application makes WITH it, and
806
+ * the address says so. The old path still answers, for clients published before
807
+ * 2026-08-18, and both share one rate-limit budget.
808
+ */
809
+ revisions(userId, opts = {}) {
810
+ const body = {};
811
+ if (opts.include !== undefined)
812
+ body.include = opts.include;
813
+ if (opts.limit !== undefined)
814
+ body.limit = opts.limit;
815
+ if (opts.before !== undefined)
816
+ body.before = opts.before;
817
+ if (opts.skipIds !== undefined)
818
+ body.skip_ids = opts.skipIds;
819
+ // `user_id` LAST, after the caller's fields — an `opts` spread that can land on top
820
+ // of it is how a client ends up reading another store. Same order as `search`.
821
+ body.user_id = this.uid(userId);
822
+ return this.post("/api/v1/won/revisions", body);
823
+ }
824
+ /**
825
+ * The full chain of edits behind one memory, oldest first.
826
+ *
827
+ * `is_current` marks the version in force. Use it to answer "what did this used to
828
+ * say, and when did it change" — `revisions()` tells you HOW MUCH a store moved,
829
+ * this tells you what happened to one fact.
830
+ */
831
+ lineage(userId, memoryId) {
832
+ if (!memoryId || typeof memoryId !== "string") {
833
+ throw new Error("memoryId is required — the memory whose history you want.");
834
+ }
835
+ return this.post("/api/v1/memory/lineage", { user_id: this.uid(userId), memory_id: memoryId });
836
+ }
837
+ /**
838
+ * What one person said, newest first.
839
+ *
840
+ * `speaker` is the tag written at store time (`metadata.speaker`) — `"me"` for the
841
+ * assistant's own words, otherwise a person's name. Same cursor paging as
842
+ * `listImages`.
843
+ *
844
+ * `chunks` / `points_to_delete` report the sentence-level fragments behind these
845
+ * memories, which is what a delete would actually remove — usually larger than
846
+ * `returned`, and worth showing before anyone confirms one.
847
+ */
848
+ bySpeaker(speaker, userId, opts = {}) {
849
+ if (!speaker || typeof speaker !== "string" || speaker.trim() === "") {
850
+ throw new Error('speaker is required — "me" for the assistant, or a person\'s name.');
851
+ }
852
+ const body = { user_id: this.uid(userId), speaker: speaker.trim() };
853
+ if (opts.limit !== undefined)
854
+ body.limit = opts.limit;
855
+ if (opts.before !== undefined)
856
+ body.before = opts.before;
857
+ if (opts.skipIds !== undefined)
858
+ body.skip_ids = opts.skipIds;
859
+ return this.post("/api/v1/memory/by-speaker", body);
860
+ }
643
861
  /** Check connectivity AND that the API key works. Resolves `true`, or rejects — an
644
862
  * `AuthenticationError` (bad key), `PaymentRequiredError` (valid key but no card /
645
863
  * depleted balance), or `APIConnectionError` (unreachable). Makes one metered request. */
@@ -747,6 +965,73 @@ export class Client {
747
965
  post(path, body, idempotencyKey) {
748
966
  return this.request("POST", path, body, idempotencyKey);
749
967
  }
968
+ /**
969
+ * One request that answers with BYTES rather than JSON.
970
+ *
971
+ * Only `/memory/image` does this, and it is why this cannot go through `request()`:
972
+ * that path reads the body as text and insists the result parses to a JSON object.
973
+ * Feeding it a JPEG would throw "invalid JSON in response" — a confusing error for a
974
+ * call that actually succeeded.
975
+ *
976
+ * Errors still arrive as JSON, so those are handed back to the normal machinery: on
977
+ * a non-2xx we re-read the body as text and reuse `errorFor`, which keeps 404
978
+ * (`NotFoundError`) and 401 behaving the same as everywhere else.
979
+ */
980
+ async requestBytes(path, body) {
981
+ const ctrl = new AbortController();
982
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
983
+ let res;
984
+ try {
985
+ res = await this.fetchImpl(`${this.base}${path}`, {
986
+ method: "POST",
987
+ headers: this.headers,
988
+ body: JSON.stringify(body),
989
+ signal: ctrl.signal,
990
+ redirect: "manual",
991
+ });
992
+ }
993
+ catch (e) {
994
+ clearTimeout(timer);
995
+ if (e?.name === "AbortError" || ctrl.signal.aborted) {
996
+ throw new APIConnectionError(0, `request timed out after ${this.timeoutMs}ms`);
997
+ }
998
+ throw new APIConnectionError(0, `network error: ${e?.message ?? e}`);
999
+ }
1000
+ try {
1001
+ this._rateLimit = parseRateLimit(res.headers) ?? this._rateLimit;
1002
+ if ((res.status >= 300 && res.status < 400) || res.type === "opaqueredirect") {
1003
+ void res.body?.cancel();
1004
+ throw errorFor(res.status, "the API answered with a redirect; refusing to follow it");
1005
+ }
1006
+ if (!res.ok) {
1007
+ let msg = await this.readCapped(res).catch(() => "");
1008
+ try {
1009
+ const data = JSON.parse(msg);
1010
+ const err = data?.error;
1011
+ if (err && typeof err === "object")
1012
+ msg = err.message ?? err.type ?? msg;
1013
+ else if (typeof err === "string")
1014
+ msg = err;
1015
+ }
1016
+ catch {
1017
+ /* keep raw text */
1018
+ }
1019
+ if (msg.length > MAX_ERR_MSG)
1020
+ msg = msg.slice(0, MAX_ERR_MSG) + "…(truncated)";
1021
+ throw errorFor(res.status, msg || `HTTP ${res.status}`);
1022
+ }
1023
+ const buf = await this.readCappedBytes(res);
1024
+ if (buf.byteLength === 0) {
1025
+ // An empty 200 would otherwise read as "here is your image" and write a
1026
+ // zero-byte file — indistinguishable from an image we lost.
1027
+ throw new WosError(res.status, "empty image body — the service returned no bytes");
1028
+ }
1029
+ return { bytes: buf, contentType: res.headers.get("content-type") ?? "application/octet-stream" };
1030
+ }
1031
+ finally {
1032
+ clearTimeout(timer);
1033
+ }
1034
+ }
750
1035
  /** Validate an idempotency key BEFORE the network. The API answers a malformed
751
1036
  * key with a 400, which on a retry path reads as "my write failed" when in fact
752
1037
  * it was never attempted — cheaper and clearer to reject it here. */
@@ -774,12 +1059,21 @@ export class Client {
774
1059
  /** Read the body with a hard size cap, so a broken/hostile endpoint can't
775
1060
  * make the process buffer gigabytes. */
776
1061
  async readCapped(res) {
1062
+ return new TextDecoder().decode(await this.readCappedBytes(res));
1063
+ }
1064
+ /** The same cap, for a body that is not text.
1065
+ *
1066
+ * `getImage` used to call `arrayBuffer()` here, which buffers whatever arrives. The
1067
+ * cap exists for a hostile or broken `baseUrl`, and a photo endpoint is exactly where
1068
+ * that shows up — the JSON paths were guarded while the one path that returns
1069
+ * megabytes was not. One implementation, two callers, so they cannot drift. */
1070
+ async readCappedBytes(res) {
777
1071
  const cl = res.headers.get("content-length");
778
1072
  if (cl && Number(cl) > MAX_RESPONSE_BYTES) {
779
1073
  throw new WosError(0, `response too large (${cl} bytes) — refusing to buffer it`);
780
1074
  }
781
1075
  if (!res.body)
782
- return res.text();
1076
+ return new Uint8Array(await res.arrayBuffer());
783
1077
  const reader = res.body.getReader();
784
1078
  const parts = [];
785
1079
  let size = 0;
@@ -800,7 +1094,7 @@ export class Client {
800
1094
  buf.set(p, off);
801
1095
  off += p.byteLength;
802
1096
  }
803
- return new TextDecoder().decode(buf);
1097
+ return buf;
804
1098
  }
805
1099
  async request(method, path, body, idempotencyKey) {
806
1100
  const extraHeaders = this.idemHeader(idempotencyKey);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wontopos",
3
- "version": "2.2.30",
3
+ "version": "2.2.32",
4
4
  "description": "Wontopos — long-term memory for AI agents. Pure semantic retrieval, identical recall in every language, ~100× lower LLM bill.",
5
5
  "keywords": [
6
6
  "memory",
@@ -42,5 +42,8 @@
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^5.4.0"
45
+ },
46
+ "bugs": {
47
+ "url": "https://wontopos.com/contact?topic=bug"
45
48
  }
46
49
  }