geniffy 0.1.1 → 0.2.0

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
@@ -50,21 +50,57 @@ A space exists from the first time you write to it; there is nothing to create.
50
50
  const mem = client.space(`user_${user.id}`); // per request
51
51
  await client.memories.add("..."); // no space: your own memory, the one the Geniffy app shows
52
52
  await client.spaces(); // which spaces hold anything, most recently written first
53
+ await client.space("user_8841").export(); // everything held for that user, as their own copy
53
54
  await client.forgetSpace("user_8841"); // everything held for that user, gone, when they ask
54
55
  ```
55
56
 
57
+ To let a user's own app or device reach their memory, and nothing else, give it a key limited to them:
58
+
59
+ ```ts
60
+ const key = await client.space(`user_${user.id}`).keys.create({ name: "Asha's phone" }); // key.key is shown once
61
+ await client.space(`user_${user.id}`).keys.revoke(key.id);
62
+ ```
63
+
64
+ Group your users' profiles your way with sections: `client.sections.create({ name: "billing", keywords: ["invoice"] })`
65
+ for every user, or on `client.space(id)` for one.
66
+
56
67
  ## Add
57
68
 
58
69
  ```ts
59
70
  await mem.memories.add({ text: "Pilots run for 6 weeks.", title: "GTM plan" });
60
71
  await mem.memories.add({ url: "https://example.com" }); // a web page, read once
61
72
  await mem.memories.add({ messages: chatHistory }); // a conversation, as your framework holds it
62
- await mem.memories.addFile(fileOrBlob, { filename: "Pricing.pdf" }); // PDF or Word (.docx)
73
+ await mem.memories.add({ text: "We moved the launch to March.", saidAt: "2026-09-12" }); // dated by when it was said
74
+ await mem.memories.addFile(fileOrBlob, { filename: "Pricing.pdf" }); // PDF, .docx, .pptx, .xlsx or text
63
75
  await mem.memories.addMany([{ text: "..." }, { url: "https://..." }]);
64
76
  ```
65
77
 
66
78
  A file or page that can't be read rejects with `UnreadableError`; `error.source` is the row it left, with the reason.
67
79
 
80
+ Syncing your own records? Give each its id. Sent again under the same `externalId`, the source is updated
81
+ rather than added twice: only what changed is learned, and what was removed is taken back.
82
+
83
+ ```ts
84
+ await mem.memories.add({ text: ticket.body, title: ticket.subject, externalId: `ticket-${ticket.id}` });
85
+ await mem.sources.get({ externalId: `ticket-${ticket.id}` });
86
+ await mem.sources.delete({ externalId: `ticket-${ticket.id}` }); // when the ticket is deleted in your app
87
+ ```
88
+
89
+ Label what you add with your own name/value pairs, then keep any read to them. Every name must match, and a
90
+ list of values is any one of them.
91
+
92
+ ```ts
93
+ await mem.memories.add({ text: email.body, title: email.subject, labels: { channel: "email", account: "lumen" } });
94
+ await mem.context("When does the renewal come up?", { labels: { account: "lumen" } });
95
+ await mem.search("pricing", { labels: { channel: ["email", "chat"] } });
96
+ await mem.memories.list({ labels: { account: "lumen" } });
97
+ await mem.sources.deleteLabelled({ channel: "email" }); // the user disconnected it: all it brought goes
98
+ await mem.sources.deleteLabelled({ channel: "email" }, { keep: seen }); // the end of a full sync: all but what is still there
99
+ ```
100
+
101
+ To keep a whole data source in step, such as a user's Gmail, Drive or Notion, see
102
+ [Sync a data source](https://docs.geniffy.com/add-memories/sync-a-data-source).
103
+
68
104
  ## Read and correct
69
105
 
70
106
  ```ts
package/dist/index.d.ts CHANGED
@@ -10,13 +10,15 @@
10
10
  * Retries: reads and deletes are retried on network errors, 408, 429 and 5xx; adding is retried only on
11
11
  * 429, so a retry never saves a note twice.
12
12
  */
13
- export declare const VERSION = "0.1.1";
13
+ export declare const VERSION = "0.2.0";
14
14
  export declare const DEFAULT_BASE_URL = "https://api.geniffy.com";
15
15
  export type Kind = "all" | "people" | "plan" | "pref" | "detail";
16
16
  export interface SourceRef {
17
17
  id: string | null;
18
18
  kind: string;
19
19
  title: string;
20
+ /** the labels on that source */
21
+ labels?: Labels;
20
22
  }
21
23
  export interface Memory {
22
24
  id: number;
@@ -56,7 +58,16 @@ export interface Source {
56
58
  size_bytes?: number | null;
57
59
  added_by?: string | null;
58
60
  added_at?: string | null;
61
+ /** your own id for it, when you gave one */
62
+ external_id?: string | null;
63
+ /** your own name/value pairs on it */
64
+ labels?: Labels;
59
65
  }
66
+ /** A source's labels: your own name/value pairs, such as { channel: "email" }. */
67
+ export type Labels = Record<string, string>;
68
+ /** A filter by labels: every name must match, and a list of values is any one of them
69
+ * ({ channel: ["email", "chat"] }). */
70
+ export type LabelFilter = Record<string, string | string[]>;
60
71
  export interface SourcePage {
61
72
  sources: Source[];
62
73
  total: number;
@@ -89,7 +100,10 @@ export interface ClientOptions {
89
100
  * You usually want `client.space(id)` instead: one client for the process, one bound client per
90
101
  * request, so a space can never be forgotten on a call.
91
102
  */
92
- space?: string;
103
+ space?: string | number;
104
+ /** For a package built on this SDK: its own name and version ("geniffy-ai-sdk/0.1.0"), sent after the SDK's,
105
+ * so the Requests page shows which integration made each call. */
106
+ integration?: string;
93
107
  }
94
108
  export declare class GeniffyError extends Error {
95
109
  readonly status?: number;
@@ -127,12 +141,16 @@ export declare class InternalServerError extends GeniffyError {
127
141
  type Body = {
128
142
  json?: unknown;
129
143
  form?: FormData;
130
- query?: Record<string, string | number | undefined>;
144
+ query?: Record<string, string | number | string[] | undefined>;
131
145
  };
132
146
  export declare class Geniffy {
133
147
  #private;
134
148
  readonly memories: Memories;
135
149
  readonly sources: Sources;
150
+ /** Keys limited to one of your users, on a client bound to them: client.space(id).keys */
151
+ readonly keys: Keys;
152
+ /** The sections profiles are grouped into: every user's on the plain client, one user's on client.space(id) */
153
+ readonly sections: Sections;
136
154
  readonly maxRetries: number;
137
155
  readonly timeout: number;
138
156
  /** The one of your users this client is bound to, or "" for your own memory. */
@@ -147,18 +165,24 @@ export declare class Geniffy {
147
165
  * await mem.memories.add("Prefers WhatsApp.");
148
166
  * const answer = await mem.ask("How should we reach them?");
149
167
  *
150
- * `space` is your own name for that user and nothing is read into it: an id, an email, whatever
151
- * you already call them. Up to 128 letters, digits, dots, dashes or underscores.
168
+ * `space` is your own name for that user and nothing is read into it: the id you already give them,
169
+ * up to 128 letters, digits, dots, dashes or underscores, so an id rather than an email. A blank one
170
+ * (or undefined, or null) throws rather than reading your own memory.
152
171
  */
153
- space(space: string): Geniffy;
172
+ space(space: string | number): Geniffy;
154
173
  /** @internal */
155
174
  request<T>(method: "GET" | "POST" | "DELETE" | "PATCH", path: string, body?: Body): Promise<T>;
156
- /** An answer from your memory only. `answer` is null when nothing you added supports one. */
157
- ask(question: string): Promise<Answer>;
158
- /** The memories that best match `q`, best first. */
175
+ /** An answer from your memory only. `answer` is null when nothing you added supports one. With labels, only
176
+ * from what the sources carrying them said. */
177
+ ask(question: string, opts?: {
178
+ labels?: LabelFilter;
179
+ }): Promise<Answer>;
180
+ /** The memories that best match `q`, best first. `labels: { channel: "email" }` keeps to the sources
181
+ * carrying them: every name must match, and a list of values is any one of them. */
159
182
  search(q: string, opts?: {
160
183
  limit?: number;
161
184
  kind?: Kind;
185
+ labels?: LabelFilter;
162
186
  }): Promise<Memory[]>;
163
187
  /**
164
188
  * The memories that bear on a question, already written out for YOUR prompt.
@@ -175,21 +199,27 @@ export declare class Geniffy {
175
199
  limit?: number;
176
200
  kind?: Kind;
177
201
  withSources?: boolean;
202
+ labels?: LabelFilter;
178
203
  }): Promise<string>;
179
204
  /** The same, with the memories behind it and whether anything was found. */
180
205
  contextFull(question: string, opts?: {
181
206
  limit?: number;
182
207
  kind?: Kind;
183
208
  withSources?: boolean;
209
+ labels?: LabelFilter;
184
210
  }): Promise<ContextResult>;
185
211
  /** What stays true about someone, and what is going on with them now. */
186
212
  profile(subject?: string): Promise<Profile>;
187
213
  /** What to read before dealing with someone. */
188
214
  brief(subject?: string, opts?: {
189
215
  limit?: number;
216
+ labels?: LabelFilter;
190
217
  }): Promise<Brief>;
191
218
  /** What the memory holds and what connects to what. Every line has a memory behind it. */
192
219
  graph(): Promise<Graph>;
220
+ /** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
221
+ * came from, and every source. On client.space(id), for a user who asks what you hold about them. */
222
+ export(): Promise<Export>;
193
223
  /** Whose key this is, and which space this client is reading. */
194
224
  me(): Promise<{
195
225
  name: string | null;
@@ -202,7 +232,7 @@ export declare class Geniffy {
202
232
  * Everything one of your users ever said, gone: facts, sources, all of it. This is the call to
203
233
  * make when they ask to be forgotten. It cannot be undone.
204
234
  */
205
- forgetSpace(space: string): Promise<void>;
235
+ forgetSpace(space: string | number): Promise<void>;
206
236
  }
207
237
  export interface BatchResult {
208
238
  results: Array<{
@@ -238,6 +268,16 @@ export interface Brief {
238
268
  memories: Memory[];
239
269
  total: number;
240
270
  }
271
+ /** A user's own copy of what is held. */
272
+ export interface Export {
273
+ exported_at: string;
274
+ /** where the memory is kept */
275
+ stored_in: string;
276
+ memories: (Memory & {
277
+ quote?: string | null;
278
+ })[];
279
+ sources: Source[];
280
+ }
241
281
  export interface Graph {
242
282
  nodes: Array<{
243
283
  id: string;
@@ -271,29 +311,51 @@ export interface ChatMessage {
271
311
  /** Who, when the role does not say: a tool name, a participant. */
272
312
  name?: string;
273
313
  }
274
- export type AddInput = string | {
314
+ /** When a note or conversation from the past was said: a Date, or an ISO 8601 string (2026-03-04,
315
+ * 2026-03-04T09:30:00Z). What it teaches is dated by it. Left out, now. */
316
+ export interface SaidAt {
317
+ saidAt?: Date | string;
318
+ }
319
+ /** Your own id for what you add: a ticket's, a document's, a conversation's. Sent again under the same id,
320
+ * the source is updated rather than added twice: only what changed is learned, and what was removed is
321
+ * taken back. Find or delete it by the same id with `sources.get({ externalId })` and `sources.delete`. */
322
+ export interface ExternalId {
323
+ externalId?: string;
324
+ }
325
+ /** Up to 20 of your own name/value pairs ({ channel: "email", project: "apollo" }) to filter search, context,
326
+ * ask, list and brief by. Sent again under the same externalId they replace the old ones, with nothing learned
327
+ * again; left out, they are kept; {} clears them. */
328
+ export interface WithLabels {
329
+ labels?: Labels;
330
+ }
331
+ export type AddInput = string | ({
275
332
  text: string;
276
333
  title?: string;
277
- } | {
334
+ } & SaidAt & ExternalId & WithLabels) | ({
278
335
  url: string;
279
336
  title?: string;
280
- }
337
+ } & ExternalId & WithLabels)
281
338
  /** A conversation as your framework already holds it. System and developer messages are skipped, and
282
339
  * who said what is kept, so the user's words become facts about the user and not about your assistant. */
283
- | {
340
+ | ({
284
341
  messages: ChatMessage[];
285
342
  title?: string;
343
+ } & SaidAt & ExternalId & WithLabels);
344
+ /** A source named by Geniffy's id, or by the external id you added it under. */
345
+ export type SourceLookup = string | {
346
+ externalId: string;
286
347
  };
287
348
  export declare class Memories {
288
349
  private readonly client;
289
350
  constructor(client: Geniffy);
290
351
  /** Add a note (a string or { text }), or a web page ({ url }) that Geniffy reads once. */
291
352
  add(input: AddInput): Promise<Source>;
292
- /** Add a PDF or Word (.docx) file. */
353
+ /** Add a file: PDF, Word (.docx), PowerPoint (.pptx), Excel (.xlsx), or text (.txt, .md, .csv, .html). Under an
354
+ * externalId, a new version updates the source that id names. */
293
355
  addFile(file: Blob | ArrayBuffer | Uint8Array, opts?: {
294
356
  filename?: string;
295
357
  title?: string;
296
- }): Promise<Source>;
358
+ } & ExternalId & WithLabels): Promise<Source>;
297
359
  /**
298
360
  * Up to a hundred at once. One bad item does not take the rest down: every item comes back in
299
361
  * the order you sent it, with either its source or why it was refused.
@@ -306,32 +368,105 @@ export declare class Memories {
306
368
  corrected: boolean;
307
369
  source: Source;
308
370
  }>;
309
- /** One page of memories, newest first. */
371
+ /** One page of memories, newest first; with labels, only what the sources carrying them said. */
310
372
  list(opts?: {
311
373
  kind?: Kind;
312
374
  limit?: number;
313
375
  cursor?: number;
376
+ labels?: LabelFilter;
314
377
  }): Promise<MemoryPage>;
315
378
  /** Every memory, newest first, a page at a time: for await (const m of g.memories.iterate()) */
316
379
  iterate(opts?: {
317
380
  kind?: Kind;
318
381
  pageSize?: number;
382
+ labels?: LabelFilter;
319
383
  }): AsyncGenerator<Memory>;
320
384
  /** A memory, the sentence it came from, and the values it held before. */
321
385
  get(id: number): Promise<MemoryDetail>;
322
386
  /** Forget a memory for good. */
323
387
  delete(id: number): Promise<void>;
324
388
  }
389
+ /** A key limited to one of your users: it reads and writes their memory and nothing else. */
390
+ export interface Key {
391
+ id: number;
392
+ name: string;
393
+ /** the user it is limited to */
394
+ space: string;
395
+ /** the key itself: only when it is made, never again */
396
+ key?: string | null;
397
+ starts_with?: string | null;
398
+ created_at?: string | null;
399
+ last_used_at?: string | null;
400
+ /** when it stops working by itself; null: when it is revoked */
401
+ expires_at?: string | null;
402
+ }
403
+ /** Keys limited to one of your users, on a client bound to that user: `client.space(id).keys`. Such a key is
404
+ * safe to hand to that user's own app or device, since it reaches their memory and nothing else. */
405
+ export declare class Keys {
406
+ private readonly client;
407
+ constructor(client: Geniffy);
408
+ /** A new key limited to this client's user. `key` is shown once. rpm: requests a minute (up to 600, the default).
409
+ * expiresAt: when it stops working by itself (a Date, or an ISO date it works through); left out, never. */
410
+ create(opts?: {
411
+ name?: string;
412
+ rpm?: number;
413
+ expiresAt?: Date | string;
414
+ }): Promise<Key>;
415
+ /** The keys limited to this client's user that still work. */
416
+ list(): Promise<Key[]>;
417
+ /** One of this user's keys stops at once. */
418
+ revoke(id: number): Promise<void>;
419
+ }
420
+ /** A section a profile is grouped into. */
421
+ export interface Section {
422
+ id?: number | null;
423
+ name: string;
424
+ description?: string;
425
+ keywords?: string[];
426
+ topics?: string[];
427
+ /** "every user", "this user" or "built in" */
428
+ applies_to?: string;
429
+ }
430
+ /** The sections profiles are grouped into. On the plain client, for every one of your users; on a client bound
431
+ * to one user (`client.space(id).sections`), for that user only. A memory goes in a section when one of its
432
+ * keywords appears in it, or its topic is one of the section's. */
433
+ export declare class Sections {
434
+ private readonly client;
435
+ constructor(client: Geniffy);
436
+ /** The sections, the app's own first, then the built-in ones. */
437
+ list(): Promise<Section[]>;
438
+ /** Add a section (or, under a name it already has, update it). Profiles regroup within a minute or so. */
439
+ create(section: {
440
+ name: string;
441
+ keywords?: string[];
442
+ topics?: string[];
443
+ description?: string;
444
+ }): Promise<Section>;
445
+ delete(id: number): Promise<void>;
446
+ }
325
447
  export declare class Sources {
326
448
  private readonly client;
327
449
  constructor(client: Geniffy);
450
+ /** What was added, newest first; with labels, only the sources carrying them. */
328
451
  list(opts?: {
329
452
  limit?: number;
330
453
  cursor?: number;
454
+ labels?: LabelFilter;
331
455
  }): Promise<SourcePage>;
332
- get(id: string): Promise<Source>;
333
- /** Delete a source and every memory learned only from it. */
334
- delete(id: string): Promise<void>;
456
+ /** Delete every source carrying these labels, and every memory learned only from them: the call when your
457
+ * user disconnects a data source whose things you added under its label. Resolves to how many.
458
+ *
459
+ * `keep`: the external ids to leave, for the end of a sync that read everything: every other source with
460
+ * these labels, such as what is gone from the data source, is deleted. */
461
+ deleteLabelled(labels: LabelFilter, opts?: {
462
+ keep?: Iterable<string>;
463
+ }): Promise<number>;
464
+ private deleteAllBut;
465
+ /** A source, by its id or as { externalId } (a NotFoundError when no source has that external id). */
466
+ get(ref: SourceLookup): Promise<Source>;
467
+ /** Delete a source and every memory learned only from it, by its id or as { externalId }: the call for a
468
+ * record your app deleted. */
469
+ delete(ref: SourceLookup): Promise<void>;
335
470
  /** Wait until Geniffy has learned from a source (or could not), then return it. Geniffy holds the
336
471
  * call open until the source is done, so this returns the moment it is, usually in one call. */
337
472
  wait(id: string, opts?: {
package/dist/index.js CHANGED
@@ -10,8 +10,30 @@
10
10
  * Retries: reads and deletes are retried on network errors, 408, 429 and 5xx; adding is retried only on
11
11
  * 429, so a retry never saves a note twice.
12
12
  */
13
- export const VERSION = "0.1.1";
13
+ export const VERSION = "0.2.0";
14
14
  export const DEFAULT_BASE_URL = "https://api.geniffy.com";
15
+ /** A filter in a query string: label=name:value, once for each value. */
16
+ function labelQuery(labels) {
17
+ if (!labels)
18
+ return undefined;
19
+ return Object.entries(labels).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map((x) => `${k}:${x}`));
20
+ }
21
+ const INTEGRATION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/[A-Za-z0-9][A-Za-z0-9._+-]{0,31}$/;
22
+ // One of your users, by your own name for them: a string, or an integer id. A blank one is refused, not
23
+ // read as no space: a client with no space reads YOUR memory, so a user with no id would land in it.
24
+ function spaceName(space, what) {
25
+ const named = typeof space === "number" && Number.isSafeInteger(space) ? String(space) : space;
26
+ if (typeof named !== "string") {
27
+ throw new TypeError(`${what} takes your name for one of your users, a string or an integer id, not ` +
28
+ `${named === null ? "null" : typeof named}.`);
29
+ }
30
+ const name = named.trim();
31
+ if (!name) {
32
+ throw new TypeError(`${what} got a blank space. A client with no space reads your own memory, so a user ` +
33
+ "with no id would land in it. Pass the user's id, or use the client itself for your own memory.");
34
+ }
35
+ return name;
36
+ }
15
37
  // ── errors ────────────────────────────────────────────────────────────────────
16
38
  export class GeniffyError extends Error {
17
39
  status;
@@ -84,6 +106,10 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
84
106
  export class Geniffy {
85
107
  memories;
86
108
  sources;
109
+ /** Keys limited to one of your users, on a client bound to them: client.space(id).keys */
110
+ keys;
111
+ /** The sections profiles are grouped into: every user's on the plain client, one user's on client.space(id) */
112
+ sections;
87
113
  maxRetries;
88
114
  timeout;
89
115
  /** The one of your users this client is bound to, or "" for your own memory. */
@@ -103,9 +129,14 @@ export class Geniffy {
103
129
  this.#fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
104
130
  this.timeout = opts.timeout ?? 60_000;
105
131
  this.maxRetries = Math.max(0, opts.maxRetries ?? 2);
106
- this.boundSpace = (opts.space ?? "").trim();
132
+ this.boundSpace = opts.space === undefined || opts.space === null ? "" : spaceName(opts.space, "space:");
133
+ if (opts.integration !== undefined && !INTEGRATION.test(opts.integration)) {
134
+ throw new TypeError('integration is a name and a version, such as "geniffy-ai-sdk/0.1.0".');
135
+ }
107
136
  this.memories = new Memories(this);
108
137
  this.sources = new Sources(this);
138
+ this.keys = new Keys(this);
139
+ this.sections = new Sections(this);
109
140
  }
110
141
  /**
111
142
  * The same client, pointed at one of YOUR users. Everything it reads and writes is that user's
@@ -116,22 +147,27 @@ export class Geniffy {
116
147
  * await mem.memories.add("Prefers WhatsApp.");
117
148
  * const answer = await mem.ask("How should we reach them?");
118
149
  *
119
- * `space` is your own name for that user and nothing is read into it: an id, an email, whatever
120
- * you already call them. Up to 128 letters, digits, dots, dashes or underscores.
150
+ * `space` is your own name for that user and nothing is read into it: the id you already give them,
151
+ * up to 128 letters, digits, dots, dashes or underscores, so an id rather than an email. A blank one
152
+ * (or undefined, or null) throws rather than reading your own memory.
121
153
  */
122
154
  space(space) {
123
- return new Geniffy({ ...this.#opts, apiKey: this.#key, space });
155
+ return new Geniffy({ ...this.#opts, apiKey: this.#key, space: spaceName(space, "space()") });
124
156
  }
125
157
  /** @internal */
126
158
  async request(method, path, body = {}) {
127
159
  const url = new URL(this.#base + path);
128
- for (const [k, v] of Object.entries(body.query ?? {}))
129
- if (v !== undefined)
160
+ for (const [k, v] of Object.entries(body.query ?? {})) {
161
+ if (Array.isArray(v))
162
+ for (const each of v)
163
+ url.searchParams.append(k, each);
164
+ else if (v !== undefined)
130
165
  url.searchParams.set(k, String(v));
166
+ }
131
167
  const headers = {
132
168
  Authorization: `Bearer ${this.#key}`,
133
169
  Accept: "application/json",
134
- "X-Geniffy-Client": `geniffy-js/${VERSION}`,
170
+ "X-Geniffy-Client": `geniffy-js/${VERSION}${this.#opts.integration ? ` ${this.#opts.integration}` : ""}`,
135
171
  };
136
172
  // One header carries the space, so every call a bound client makes is scoped without any
137
173
  // method having to take it, and a space can never be dropped by forgetting an argument.
@@ -178,13 +214,17 @@ export class Geniffy {
178
214
  return data;
179
215
  }
180
216
  }
181
- /** An answer from your memory only. `answer` is null when nothing you added supports one. */
182
- ask(question) {
183
- return this.request("POST", "/v1/ask", { json: { question } });
217
+ /** An answer from your memory only. `answer` is null when nothing you added supports one. With labels, only
218
+ * from what the sources carrying them said. */
219
+ ask(question, opts = {}) {
220
+ return this.request("POST", "/v1/ask", { json: { question, labels: opts.labels } });
184
221
  }
185
- /** The memories that best match `q`, best first. */
222
+ /** The memories that best match `q`, best first. `labels: { channel: "email" }` keeps to the sources
223
+ * carrying them: every name must match, and a list of values is any one of them. */
186
224
  async search(q, opts = {}) {
187
- const out = await this.request("POST", "/v1/search", { json: { q, limit: opts.limit ?? 10, kind: opts.kind } });
225
+ const out = await this.request("POST", "/v1/search", {
226
+ json: { q, limit: opts.limit ?? 10, kind: opts.kind, labels: opts.labels },
227
+ });
188
228
  return out.memories;
189
229
  }
190
230
  /**
@@ -205,7 +245,8 @@ export class Geniffy {
205
245
  /** The same, with the memories behind it and whether anything was found. */
206
246
  contextFull(question, opts = {}) {
207
247
  return this.request("POST", "/v1/context", {
208
- json: { question, limit: opts.limit ?? 12, kind: opts.kind, with_sources: opts.withSources ?? true },
248
+ json: { question, limit: opts.limit ?? 12, kind: opts.kind, with_sources: opts.withSources ?? true,
249
+ labels: opts.labels },
209
250
  });
210
251
  }
211
252
  /** What stays true about someone, and what is going on with them now. */
@@ -214,12 +255,17 @@ export class Geniffy {
214
255
  }
215
256
  /** What to read before dealing with someone. */
216
257
  brief(subject, opts = {}) {
217
- return this.request("GET", "/v1/brief", { query: { subject, limit: opts.limit } });
258
+ return this.request("GET", "/v1/brief", { query: { subject, limit: opts.limit, label: labelQuery(opts.labels) } });
218
259
  }
219
260
  /** What the memory holds and what connects to what. Every line has a memory behind it. */
220
261
  graph() {
221
262
  return this.request("GET", "/v1/graph");
222
263
  }
264
+ /** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
265
+ * came from, and every source. On client.space(id), for a user who asks what you hold about them. */
266
+ export() {
267
+ return this.request("GET", "/v1/export");
268
+ }
223
269
  /** Whose key this is, and which space this client is reading. */
224
270
  me() {
225
271
  return this.request("GET", "/v1/me");
@@ -234,9 +280,27 @@ export class Geniffy {
234
280
  * make when they ask to be forgotten. It cannot be undone.
235
281
  */
236
282
  async forgetSpace(space) {
237
- await this.request("DELETE", `/v1/spaces/${encodeURIComponent(space)}`);
283
+ await this.request("DELETE", `/v1/spaces/${encodeURIComponent(spaceName(space, "forgetSpace()"))}`);
238
284
  }
239
285
  }
286
+ // The body the API takes: saidAt goes as said_at, a Date as its moment in UTC; externalId as external_id.
287
+ function addBody(input) {
288
+ const given = typeof input === "string" ? { text: input } : input;
289
+ const { saidAt, externalId, ...rest } = given;
290
+ const body = { ...rest };
291
+ if (saidAt !== undefined)
292
+ body.said_at = saidAt instanceof Date ? saidAt.toISOString() : String(saidAt);
293
+ if (externalId !== undefined)
294
+ body.external_id = String(externalId);
295
+ return body;
296
+ }
297
+ function lookup(ref) {
298
+ if (typeof ref === "string")
299
+ return { id: ref };
300
+ if (ref && typeof ref.externalId === "string")
301
+ return { externalId: ref.externalId };
302
+ throw new TypeError("Name the source by its id, or as { externalId }.");
303
+ }
240
304
  export class Memories {
241
305
  client;
242
306
  constructor(client) {
@@ -244,11 +308,12 @@ export class Memories {
244
308
  }
245
309
  /** Add a note (a string or { text }), or a web page ({ url }) that Geniffy reads once. */
246
310
  async add(input) {
247
- const json = typeof input === "string" ? { text: input } : input;
311
+ const json = addBody(input);
248
312
  const out = await this.client.request("POST", "/v1/memories", { json });
249
313
  return out.source;
250
314
  }
251
- /** Add a PDF or Word (.docx) file. */
315
+ /** Add a file: PDF, Word (.docx), PowerPoint (.pptx), Excel (.xlsx), or text (.txt, .md, .csv, .html). Under an
316
+ * externalId, a new version updates the source that id names. */
252
317
  async addFile(file, opts = {}) {
253
318
  const blob = file instanceof Blob ? file : new Blob([file]);
254
319
  const named = file.name;
@@ -257,6 +322,10 @@ export class Memories {
257
322
  form.append("file", blob, name);
258
323
  if (opts.title)
259
324
  form.append("title", opts.title);
325
+ if (opts.externalId !== undefined)
326
+ form.append("external_id", String(opts.externalId));
327
+ if (opts.labels !== undefined)
328
+ form.append("labels", JSON.stringify(opts.labels));
260
329
  const out = await this.client.request("POST", "/v1/memories/file", { form });
261
330
  return out.source;
262
331
  }
@@ -265,7 +334,7 @@ export class Memories {
265
334
  * the order you sent it, with either its source or why it was refused.
266
335
  */
267
336
  async addMany(items) {
268
- const json = { items: items.map((i) => (typeof i === "string" ? { text: i } : i)) };
337
+ const json = { items: items.map(addBody) };
269
338
  return this.client.request("POST", "/v1/memories/batch", { json });
270
339
  }
271
340
  /** Say what we got wrong and what is right. The wrong one is marked and never used again; what
@@ -273,17 +342,17 @@ export class Memories {
273
342
  async correct(id, text) {
274
343
  return this.client.request("PATCH", `/v1/memories/${id}`, { json: { text } });
275
344
  }
276
- /** One page of memories, newest first. */
345
+ /** One page of memories, newest first; with labels, only what the sources carrying them said. */
277
346
  list(opts = {}) {
278
347
  return this.client.request("GET", "/v1/memories", {
279
- query: { kind: opts.kind, limit: opts.limit ?? 50, cursor: opts.cursor ?? 0 },
348
+ query: { kind: opts.kind, limit: opts.limit ?? 50, cursor: opts.cursor ?? 0, label: labelQuery(opts.labels) },
280
349
  });
281
350
  }
282
351
  /** Every memory, newest first, a page at a time: for await (const m of g.memories.iterate()) */
283
352
  async *iterate(opts = {}) {
284
353
  let cursor = 0;
285
354
  while (cursor !== null) {
286
- const page = await this.list({ kind: opts.kind, limit: opts.pageSize ?? 100, cursor });
355
+ const page = await this.list({ kind: opts.kind, limit: opts.pageSize ?? 100, cursor, labels: opts.labels });
287
356
  yield* page.memories;
288
357
  cursor = page.next;
289
358
  }
@@ -297,20 +366,139 @@ export class Memories {
297
366
  await this.client.request("DELETE", `/v1/memories/${Math.trunc(id)}`);
298
367
  }
299
368
  }
369
+ /** Keys limited to one of your users, on a client bound to that user: `client.space(id).keys`. Such a key is
370
+ * safe to hand to that user's own app or device, since it reaches their memory and nothing else. */
371
+ export class Keys {
372
+ client;
373
+ constructor(client) {
374
+ this.client = client;
375
+ }
376
+ /** A new key limited to this client's user. `key` is shown once. rpm: requests a minute (up to 600, the default).
377
+ * expiresAt: when it stops working by itself (a Date, or an ISO date it works through); left out, never. */
378
+ create(opts = {}) {
379
+ const json = {};
380
+ if (opts.name)
381
+ json.name = opts.name;
382
+ if (opts.rpm !== undefined)
383
+ json.rpm = opts.rpm;
384
+ if (opts.expiresAt !== undefined) {
385
+ json.expires_at = opts.expiresAt instanceof Date ? opts.expiresAt.toISOString() : String(opts.expiresAt);
386
+ }
387
+ return this.client.request("POST", "/v1/keys", { json });
388
+ }
389
+ /** The keys limited to this client's user that still work. */
390
+ async list() {
391
+ return (await this.client.request("GET", "/v1/keys")).keys;
392
+ }
393
+ /** One of this user's keys stops at once. */
394
+ async revoke(id) {
395
+ await this.client.request("DELETE", `/v1/keys/${Math.trunc(id)}`);
396
+ }
397
+ }
398
+ /** The sections profiles are grouped into. On the plain client, for every one of your users; on a client bound
399
+ * to one user (`client.space(id).sections`), for that user only. A memory goes in a section when one of its
400
+ * keywords appears in it, or its topic is one of the section's. */
401
+ export class Sections {
402
+ client;
403
+ constructor(client) {
404
+ this.client = client;
405
+ }
406
+ /** The sections, the app's own first, then the built-in ones. */
407
+ async list() {
408
+ return (await this.client.request("GET", "/v1/profile/sections")).sections;
409
+ }
410
+ /** Add a section (or, under a name it already has, update it). Profiles regroup within a minute or so. */
411
+ create(section) {
412
+ const json = { name: section.name, description: section.description ?? "", keywords: section.keywords ?? [],
413
+ topics: section.topics ?? [] };
414
+ return this.client.request("POST", "/v1/profile/sections", { json });
415
+ }
416
+ async delete(id) {
417
+ await this.client.request("DELETE", `/v1/profile/sections/${Math.trunc(id)}`);
418
+ }
419
+ }
420
+ // Each call deletes up to 100 sources and says whether more carry the labels; this many calls is the most one
421
+ // deleteLabelled() makes, so a filter that somehow keeps matching cannot loop for ever.
422
+ const LABELLED_CALLS = 1000;
300
423
  export class Sources {
301
424
  client;
302
425
  constructor(client) {
303
426
  this.client = client;
304
427
  }
428
+ /** What was added, newest first; with labels, only the sources carrying them. */
305
429
  list(opts = {}) {
306
- return this.client.request("GET", "/v1/sources", { query: { limit: opts.limit ?? 100, cursor: opts.cursor ?? 0 } });
430
+ return this.client.request("GET", "/v1/sources", {
431
+ query: { limit: opts.limit ?? 100, cursor: opts.cursor ?? 0, label: labelQuery(opts.labels) },
432
+ });
307
433
  }
308
- async get(id) {
309
- return (await this.client.request("GET", `/v1/sources/${encodeURIComponent(id)}`)).source;
434
+ /** Delete every source carrying these labels, and every memory learned only from them: the call when your
435
+ * user disconnects a data source whose things you added under its label. Resolves to how many.
436
+ *
437
+ * `keep`: the external ids to leave, for the end of a sync that read everything: every other source with
438
+ * these labels, such as what is gone from the data source, is deleted. */
439
+ async deleteLabelled(labels, opts = {}) {
440
+ if (!labels || !Object.keys(labels).length) {
441
+ throw new TypeError('Name the labels whose sources to delete, such as { channel: "gmail" }.');
442
+ }
443
+ if (opts.keep !== undefined)
444
+ return this.deleteAllBut(labels, opts.keep);
445
+ let total = 0;
446
+ for (let i = 0; i < LABELLED_CALLS; i++) {
447
+ const out = await this.client.request("DELETE", "/v1/sources", {
448
+ query: { label: labelQuery(labels) },
449
+ });
450
+ total += out.sources_deleted ?? 0;
451
+ if (!out.more)
452
+ break;
453
+ }
454
+ return total;
310
455
  }
311
- /** Delete a source and every memory learned only from it. */
312
- async delete(id) {
313
- await this.client.request("DELETE", `/v1/sources/${encodeURIComponent(id)}`);
456
+ async deleteAllBut(labels, keep) {
457
+ // one id on its own would read as its letters, and keep nothing
458
+ if (typeof keep === "string")
459
+ throw new TypeError("keep is a list or set of external ids, not one id.");
460
+ const kept = new Set(Array.from(keep, String));
461
+ const gone = [];
462
+ for (let cursor = 0; cursor !== null;) { // the whole list first: deleting moves the pages
463
+ const page = await this.list({ labels, cursor });
464
+ for (const s of page.sources)
465
+ if (!(s.external_id != null && kept.has(s.external_id)))
466
+ gone.push(s.id);
467
+ cursor = page.next;
468
+ }
469
+ let deleted = 0;
470
+ for (const id of gone) {
471
+ try {
472
+ await this.delete(id);
473
+ deleted++;
474
+ }
475
+ catch (e) {
476
+ if (!(e instanceof NotFoundError))
477
+ throw e; // deleted meanwhile: gone either way
478
+ }
479
+ }
480
+ return deleted;
481
+ }
482
+ /** A source, by its id or as { externalId } (a NotFoundError when no source has that external id). */
483
+ async get(ref) {
484
+ const { id, externalId } = lookup(ref);
485
+ if (id !== undefined) {
486
+ return (await this.client.request("GET", `/v1/sources/${encodeURIComponent(id)}`)).source;
487
+ }
488
+ const { sources } = await this.client.request("GET", "/v1/sources", { query: { external_id: externalId } });
489
+ if (!sources.length) {
490
+ throw new NotFoundError("No source in this space has that external_id.", { status: 404, code: "not_found" });
491
+ }
492
+ return sources[0];
493
+ }
494
+ /** Delete a source and every memory learned only from it, by its id or as { externalId }: the call for a
495
+ * record your app deleted. */
496
+ async delete(ref) {
497
+ const { id, externalId } = lookup(ref);
498
+ if (id !== undefined)
499
+ await this.client.request("DELETE", `/v1/sources/${encodeURIComponent(id)}`);
500
+ else
501
+ await this.client.request("DELETE", "/v1/sources", { query: { external_id: externalId } });
314
502
  }
315
503
  /** Wait until Geniffy has learned from a source (or could not), then return it. Geniffy holds the
316
504
  * call open until the source is done, so this returns the moment it is, usually in one call. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "geniffy",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Geniffy for TypeScript and JavaScript: add notes, files and links to a memory, then search it and ask it.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",