geniffy 0.3.0 → 0.5.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
@@ -30,16 +30,46 @@ Ask about something that was never stored and it returns one sentence, `There is
30
30
  this yet. Say so rather than guessing.`, never an empty string: a model reads silence as permission to
31
31
  invent.
32
32
 
33
- ## Three ways to recall
33
+ ## Recall: fast reads every turn, a checked answer when it matters
34
34
 
35
35
  ```ts
36
- await mem.context("Who signs the renewal?"); // a block for your own prompt; the one most apps want
36
+ await mem.briefing({ cue: userMessage }); // what this moment needs, for your system prompt; read, not
37
+ // generated: a fraction of a second, fit for every turn
38
+ await mem.search("renewal", { limit: 5 }); // the memories, ranked, fast
39
+ await mem.searchFull("port 6543"); // the same, with the lessons, stories and open promises
37
40
  await mem.ask("Who signs the renewal?"); // { answer, memories }, or answer: null and a message
38
- await mem.search("renewal", { limit: 5 }); // the raw memories, ranked, to do with as you like
41
+ await mem.context("Who signs the renewal?"); // the memories an answer stands on, as a prompt block
39
42
  ```
40
43
 
41
- `context()` and `ask()` judge whether anything bears on the question. `search()` ranks and does not
42
- judge: it returns its best matches for any question at all.
44
+ `briefing()` and `search()` read: nothing is generated, so they are fast enough for every turn, voice calls included.
45
+ `ask()` and `context()` have a model judge whether anything bears on the question, which takes a couple of seconds
46
+ and never invents: use them when an answer must be checked, not on every turn of a call. `search()` ranks and does
47
+ not judge: it returns its best matches for any question at all.
48
+
49
+ ## Agents: open with the briefing, save every turn
50
+
51
+ An agent, or any chat that runs over many turns, does two things: it opens each session with the briefing, and it
52
+ saves every turn as it goes.
53
+
54
+ ```ts
55
+ const system = await mem.briefing({ project: "checkout", cue: task }); // where things stand, what is due, the
56
+ // rules that apply, what happened, then
57
+ // the memories, each dated
58
+ const run = mem.session(runId, { title: "Refund agent" });
59
+ // ...
60
+ await run.save(messages); // after every turn: only what is new is sent
61
+ ```
62
+
63
+ `briefing()` is written to go straight into a system prompt. `briefingFull()` has its parts, and each part can be
64
+ read on its own: `now()` (where each project stands), `episodes()`, `lessons()` and `intentions()`;
65
+ `setIntention(id, "done")` marks a promise kept, and `memoryHealth()` says how well the memory answers about its
66
+ own work.
67
+
68
+ A session's turns go into one memory for the whole session, tool calls and what came back included, in the shapes
69
+ OpenAI, Anthropic, the Vercel AI SDK, Gemini and LangChain hold them. `save()` sends only the messages after the
70
+ last one it sent, 500 at a time, so a session of any length is never sent twice; if your agent rewrites its
71
+ history, what it holds now is saved again rather than lost. Sending the new turns yourself instead:
72
+ `mem.memories.add({ messages: newTurns, session: runId })`.
43
73
 
44
74
  ## Spaces: one memory per user
45
75
 
@@ -152,11 +182,21 @@ Claude wrote, and `clearAllMemory(mem)` deletes it all (both from `geniffy/claud
152
182
  calls of one reply at the same time, so the handlers take them one after another: two edits to one file both land.
153
183
  `geniffy/claude` needs `@anthropic-ai/sdk` 0.72 or later, an optional peer dependency; `geniffy` itself still has none.
154
184
 
185
+ ## This month's use
186
+
187
+ ```ts
188
+ await client.usage(); // tokens learned and waiting, answers, what the plan includes, extra learning, when it resets
189
+ ```
190
+
191
+ Saving, briefings, search and recall are free. Past your plan, a source comes back with status `"waiting"`: kept,
192
+ found by search, and learned next month or at once with extra learning on. Only at the fair-use limit does adding
193
+ throw `UsageLimitError`.
194
+
155
195
  ## Errors, retries and request ids
156
196
 
157
197
  Every error carries the API's own sentence: `AuthenticationError` (a wrong or revoked key),
158
- `NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `InternalServerError`,
159
- `APIConnectionError`; all extend `GeniffyError`. Reads, and putting a file (the same text twice is the same
198
+ `NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `UsageLimitError` (this month's use is
199
+ up; not retried), `InternalServerError`, `APIConnectionError`; all extend `GeniffyError`. Reads, and putting a file (the same text twice is the same
160
200
  file), are retried twice on network errors, 408, 429 and 5xx; adding is retried only on 429, so a retry never
161
201
  saves a note twice. Pass `{ maxRetries, timeout }` to the constructor to change that.
162
202
 
package/dist/index.d.ts CHANGED
@@ -10,8 +10,15 @@
10
10
  * Retries: reads, deletes and files.put (the same text twice is the same file) are retried on network errors,
11
11
  * 408, 429 and 5xx; adding is retried only on 429, so a retry never saves a note twice.
12
12
  */
13
- export declare const VERSION = "0.3.0";
13
+ export declare const VERSION = "0.5.0";
14
14
  export declare const DEFAULT_BASE_URL = "https://api.geniffy.com";
15
+ /** Each region's address, by name. An account's memory is stored in the region it was made in, and its key works only
16
+ * there, so a client calls that region; "in" is the default. */
17
+ export declare const REGIONS: {
18
+ readonly in: "https://api.geniffy.com";
19
+ readonly eu: "https://eu.api.geniffy.com";
20
+ };
21
+ export type Region = keyof typeof REGIONS;
15
22
  export type Kind = "all" | "people" | "plan" | "pref" | "detail";
16
23
  export interface SourceRef {
17
24
  id: string | null;
@@ -44,11 +51,38 @@ export interface MemoryDetail {
44
51
  memory: Memory;
45
52
  history: Memory[];
46
53
  }
54
+ /** This month's use, for the whole account, against the plan (usage()). Saving, briefings and search are free and
55
+ * never counted. */
56
+ export interface Usage {
57
+ /** free, pro or max: the same plans for everyone, the API in every one; startup or scale: a company's plan */
58
+ plan: string;
59
+ /** on the 14 days of Pro every account gets once */
60
+ trial: boolean;
61
+ period_start: string;
62
+ /** when it resets */
63
+ period_end: string;
64
+ /** tokens learned this month from everything saved, every way in, your app's users included */
65
+ learned_tokens: number;
66
+ /** the tokens the plan learns in a month */
67
+ included_tokens: number;
68
+ /** saved and searchable, waiting to be learned next month (or at once with extra learning on) */
69
+ waiting_tokens: number;
70
+ /** written answers and context blocks */
71
+ answers: number;
72
+ included_answers: number;
73
+ /** extra learning: past the plan, learned and answered at once, $15 per million tokens, $15 per 1,000 answers */
74
+ extra_on: boolean;
75
+ extra_cap_usd: number;
76
+ extra_used_usd: number;
77
+ /** learning against the plan: near at 80%; over: new saves wait; extra: extra learning carries on */
78
+ state: "ok" | "near" | "over" | "extra" | "paused";
79
+ }
47
80
  export interface Source {
48
81
  id: string;
49
82
  kind: "note" | "file" | "link";
50
83
  title: string;
51
- status: "reading" | "learned" | "failed";
84
+ /** waiting: saved past this month's use, kept, and learned once there is room */
85
+ status: "reading" | "learned" | "failed" | "waiting";
52
86
  /** why it failed, in plain words */
53
87
  error?: string | null;
54
88
  facts?: number | null;
@@ -84,8 +118,11 @@ export interface Answer {
84
118
  export interface ClientOptions {
85
119
  /** Defaults to GENIFFY_API_KEY. */
86
120
  apiKey?: string;
87
- /** Defaults to GENIFFY_BASE_URL, then https://api.geniffy.com */
121
+ /** Defaults to GENIFFY_BASE_URL, then the address of `region`. */
88
122
  baseURL?: string;
123
+ /** The region your account was made in; leave it out. Defaults to GENIFFY_REGION. A baseURL wins over it, but one
124
+ * that is another region's address is refused. */
125
+ region?: Region;
89
126
  /** Milliseconds per attempt. Default 60000. */
90
127
  timeout?: number;
91
128
  /** Default 2. */
@@ -136,6 +173,13 @@ export declare class UnreadableError extends BadRequestError {
136
173
  }
137
174
  export declare class RateLimitError extends GeniffyError {
138
175
  }
176
+ /**
177
+ * This month's use is up (402, code allowance_used): past the plan, what waits to be learned has reached its fair-use
178
+ * limit (ten months of the plan's learning). Search and recall keep working; saving resumes when the month resets
179
+ * (usage() says when), at once with extra learning on, or on a bigger plan. Not retried.
180
+ */
181
+ export declare class UsageLimitError extends GeniffyError {
182
+ }
139
183
  export declare class InternalServerError extends GeniffyError {
140
184
  }
141
185
  type Body = {
@@ -186,6 +230,14 @@ export declare class Geniffy {
186
230
  kind?: Kind;
187
231
  labels?: LabelFilter;
188
232
  }): Promise<Memory[]>;
233
+ /** The same search, with everything else the memory learned that bears on `q`: the memories, then the lessons
234
+ * (rules and how-tos), episodes (what happened) and intentions (open promises) that match it, by meaning and by
235
+ * the words themselves, each naming its source. With labels, or a kind other than all, only memories come back. */
236
+ searchFull(q: string, opts?: {
237
+ limit?: number;
238
+ kind?: Kind;
239
+ labels?: LabelFilter;
240
+ }): Promise<SearchFull>;
189
241
  /**
190
242
  * The memories that bear on a question, already written out for YOUR prompt.
191
243
  *
@@ -217,10 +269,56 @@ export declare class Geniffy {
217
269
  limit?: number;
218
270
  labels?: LabelFilter;
219
271
  }): Promise<Brief>;
272
+ /**
273
+ * What this moment needs, written out for YOUR prompt within `budgetChars`: where the project stands (goal,
274
+ * focus, open items, decisions, next steps), what is due or was promised, the rules and lessons that apply,
275
+ * what happened (the latest and the most related to `cue` first), then the memories, each dated. Open a session
276
+ * with it, and call it again when the task changes:
277
+ *
278
+ * const system = `${await mem.briefing({ project: "checkout", cue: userMessage })}\n\n${instructions}`;
279
+ *
280
+ * `project` is the label your sources carry (a project, context, thread or repo label); leave it out for every
281
+ * project. Read, not written by a model, so it is fast enough for every turn.
282
+ */
283
+ briefing(opts?: {
284
+ project?: string;
285
+ cue?: string;
286
+ budgetChars?: number;
287
+ }): Promise<string>;
288
+ /** The same, with its parts: now, due, lessons, episodes and memories, each with its source. */
289
+ briefingFull(opts?: {
290
+ project?: string;
291
+ cue?: string;
292
+ budgetChars?: number;
293
+ }): Promise<Briefing>;
294
+ /** Where things stand, per project: goal, focus, what is open (and since when), decisions with their reasons,
295
+ * next steps, blockers and what was finished. */
296
+ now(project?: string): Promise<State[]>;
297
+ /** What happened, as stories, newest first: what happened, how it ended, what it led to, its source. */
298
+ episodes(opts?: {
299
+ project?: string;
300
+ limit?: number;
301
+ }): Promise<Episode[]>;
302
+ /** Rules, how-tos and lessons, strongest first, each with when it applies and why. */
303
+ lessons(opts?: {
304
+ project?: string;
305
+ limit?: number;
306
+ }): Promise<Lesson[]>;
307
+ /** Promises and plans, yours and those made to you, with their triggers: open (the default), done or dropped. */
308
+ intentions(opts?: {
309
+ status?: "open" | "done" | "dropped";
310
+ limit?: number;
311
+ }): Promise<Intention[]>;
312
+ /** How well the memory answers about its own work: each night it writes questions from what it read, answers them
313
+ * and marks the answers. `health` is the share right (0 to 1), with the questions; null before its first night. */
314
+ memoryHealth(): Promise<MemoryHealth>;
315
+ /** Mark a promise or plan done, dropped, or open again. */
316
+ setIntention(id: number, status?: "done" | "dropped" | "open"): Promise<Intention>;
220
317
  /** What the memory holds and what connects to what. Every line has a memory behind it. */
221
318
  graph(): Promise<Graph>;
222
319
  /** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
223
- * came from, every source, and every file by its path (files.get(path) reads each one's text). On
320
+ * came from, every source, every file by its path (files.get(path) reads each one's text), and the stories,
321
+ * lessons and promises read from them, each with every source it names, and where things stand. On
224
322
  * client.space(id), for a user who asks what you hold about them. */
225
323
  export(): Promise<Export>;
226
324
  /** Whose key this is, and which space this client is reading. */
@@ -229,6 +327,21 @@ export declare class Geniffy {
229
327
  memory: string;
230
328
  space: string | null;
231
329
  }>;
330
+ /**
331
+ * This month's use for the whole account, against the plan: tokens learned and waiting, answers, what the plan
332
+ * includes, extra learning, and when it resets. Saving, briefings and search are free and never counted.
333
+ */
334
+ usage(): Promise<Usage>;
335
+ /**
336
+ * An agent's or a chat's session, saved as it goes into one memory: hand save() the whole conversation after each
337
+ * turn, and only the messages it has not sent yet go to Geniffy.
338
+ *
339
+ * const run = mem.session("run-42", { title: "Refund agent" });
340
+ * await run.save(messages); // after every turn
341
+ */
342
+ session(id: string, opts?: {
343
+ title?: string;
344
+ } & WithLabels): Session;
232
345
  /** Which of your users have memory, busiest first. */
233
346
  spaces(): Promise<SpaceRow[]>;
234
347
  /**
@@ -283,6 +396,139 @@ export interface Export {
283
396
  /** every file kept, by path and without its text, which files.get(path) returns exactly as written (left out by
284
397
  * an API from before files) */
285
398
  files?: FileEntry[];
399
+ /** every story of what happened, oldest first, each with its status: closed, or open when it was still going as
400
+ * its source ended (left out by an older API) */
401
+ episodes?: Array<Episode & {
402
+ status: string | null;
403
+ }>;
404
+ /** every rule, how-to and lesson, oldest first, in use or not (its status: current, merged or struck), each with
405
+ * every source it was learned from, oldest first (left out by an older API) */
406
+ lessons?: Array<Omit<Lesson, "sources"> & {
407
+ sources: SourceRef[];
408
+ status: string | null;
409
+ }>;
410
+ /** every promise and plan, oldest first: open, done or dropped, each with every source it came from, oldest first
411
+ * (left out by an older API) */
412
+ intentions?: Array<Omit<Intention, "sources"> & {
413
+ sources: SourceRef[];
414
+ }>;
415
+ /** where things stand, per project (left out by an older API) */
416
+ now?: State[];
417
+ }
418
+ /** Where one project stands. */
419
+ export interface State {
420
+ project: string | null;
421
+ goal: string | null;
422
+ focus: string | null;
423
+ open: Array<{
424
+ text: string;
425
+ since: string | null;
426
+ }>;
427
+ decisions: Array<{
428
+ what: string;
429
+ why: string | null;
430
+ when: string | null;
431
+ }>;
432
+ next_steps: string[];
433
+ blockers: string[];
434
+ done: Array<{
435
+ text: string;
436
+ when: string | null;
437
+ }>;
438
+ updated_at: string | null;
439
+ }
440
+ /** Something that happened, as a story. */
441
+ export interface Episode {
442
+ id: number;
443
+ project: string | null;
444
+ title: string | null;
445
+ what_happened: string | null;
446
+ /** how it ended */
447
+ outcome: string | null;
448
+ led_to: string | null;
449
+ people: string[];
450
+ decisions: Array<{
451
+ what: string;
452
+ why: string | null;
453
+ }>;
454
+ /** endings a later conversation corrected, oldest first: what it first seemed, and what showed otherwise */
455
+ revised?: Array<{
456
+ was: string | null;
457
+ why: string | null;
458
+ at: string | null;
459
+ }>;
460
+ started_at: string | null;
461
+ ended_at: string | null;
462
+ source: SourceRef;
463
+ }
464
+ /** A rule, how-to or lesson, with when it applies and why. */
465
+ export interface Lesson {
466
+ id: number;
467
+ project: string | null;
468
+ kind: "rule" | "how_to" | "lesson" | null;
469
+ statement: string | null;
470
+ applies_when: string | null;
471
+ why: string | null;
472
+ /** how many times it was learned again */
473
+ strength: number;
474
+ /** the sources it was learned from last, five at most, the oldest of them first */
475
+ sources: SourceRef[];
476
+ /** how many sources it was learned from in all (left out by an older API) */
477
+ sources_total?: number;
478
+ }
479
+ /** A promise or plan, with its trigger. */
480
+ export interface Intention {
481
+ id: number;
482
+ project: string | null;
483
+ what: string | null;
484
+ owner: string | null;
485
+ trigger: "time" | "context" | "person" | "event" | null;
486
+ /** when it is due, for a time */
487
+ at: string | null;
488
+ /** its trigger in words: "when testing ends" */
489
+ when: string | null;
490
+ status: "open" | "done" | "dropped" | null;
491
+ /** the sources it came from last, five at most, the oldest of them first */
492
+ sources: SourceRef[];
493
+ /** how many sources it came from in all (left out by an older API) */
494
+ sources_total?: number;
495
+ /** when it was due before a later conversation moved it, oldest first, named as at and when are; empty when it
496
+ * was never moved (left out by an older API) */
497
+ moved_from?: Array<{
498
+ at: string | null;
499
+ when: string | null;
500
+ }>;
501
+ }
502
+ /** What searchFull() found: the memories, then the lessons, episodes and open promises that bear on the query. */
503
+ export interface SearchFull {
504
+ memories: Memory[];
505
+ lessons: Lesson[];
506
+ episodes: Episode[];
507
+ intentions: Intention[];
508
+ }
509
+ /** How well the memory answers about its own work, from the questions it asks itself each night. */
510
+ export interface MemoryHealth {
511
+ health: number | null;
512
+ tested_at: string | null;
513
+ asked: number;
514
+ score: number | null;
515
+ items: Array<{
516
+ question: string | null;
517
+ expected: string | null;
518
+ answer: string | null;
519
+ mark: "correct" | "partial" | "wrong" | null;
520
+ }>;
521
+ }
522
+ /** What a session opens with. */
523
+ export interface Briefing {
524
+ project: string | null;
525
+ /** Put this straight into your prompt. */
526
+ briefing: string;
527
+ now: State[];
528
+ due: Intention[];
529
+ lessons: Lesson[];
530
+ episodes: Episode[];
531
+ memories: Memory[];
286
532
  }
287
533
  export interface Graph {
288
534
  nodes: Array<{
@@ -309,13 +555,20 @@ export interface SpaceRow {
309
555
  }
310
556
  export interface ChatMessage {
311
557
  role: string;
312
- /** The words: a string, or the blocks or parts your framework holds (Anthropic, OpenAI). Only text is
313
- * kept; null is a turn that said nothing in words, such as one that only called a tool. */
558
+ /** The words: a string, or the blocks or parts your framework holds (Anthropic, OpenAI), tool calls and tool
559
+ * results included. Facts come only from what was said; a tool's call and output tell Geniffy what
560
+ * happened. */
314
561
  content?: string | unknown[] | null;
315
562
  /** Or the parts, as the Vercel AI SDK and Gemini hold a message. */
316
563
  parts?: unknown[];
317
564
  /** Who, when the role does not say: a tool name, a participant. */
318
565
  name?: string;
566
+ /** The tools an assistant called, as OpenAI and LangChain hold them. */
567
+ tool_calls?: unknown[];
568
+ /** For a tool result, the call it answers. */
569
+ tool_call_id?: string;
570
+ /** When it was said, ISO 8601, if your app keeps it. */
571
+ time?: string;
319
572
  }
320
573
  /** When a note or conversation from the past was said: a Date, or an ISO 8601 string (2026-03-04,
321
574
  * 2026-03-04T09:30:00Z). What it teaches is dated by it. Left out, now. */
@@ -347,7 +600,14 @@ export type AddInput = string | ({
347
600
  | ({
348
601
  messages: ChatMessage[];
349
602
  title?: string;
350
- } & SaidAt & ExternalId & WithLabels);
603
+ } & SaidAt & ExternalId & WithLabels)
604
+ /** The next turns of an agent's or a chat's session: each call adds its messages to one memory for the whole
605
+ * session, however long it gets, so send only what is new since the last call (session().save() works that out). */
606
+ | ({
607
+ messages: ChatMessage[];
608
+ session: string;
609
+ title?: string;
610
+ } & WithLabels);
351
611
  /** A source named by Geniffy's id, or by the external id you added it under. */
352
612
  export type SourceLookup = string | {
353
613
  externalId: string;
@@ -539,4 +799,22 @@ export declare class Files {
539
799
  * already taken, and then nothing moves. Resolves to how many files moved. */
540
800
  move(from: string, to: string): Promise<number>;
541
801
  }
802
+ /**
803
+ * An agent's or a chat's session, saved as it goes into one memory for the whole session. Hand save() the whole
804
+ * conversation after each turn: only the messages after the last one it sent go to Geniffy, at most 500 a call, so a
805
+ * session of any length is never sent twice. When that message is no longer there (the agent rewrote or compacted
806
+ * its history), what it holds now is saved again rather than lost. Made by client.session(id).
807
+ */
808
+ export declare class Session {
809
+ #private;
810
+ private readonly client;
811
+ readonly id: string;
812
+ readonly title?: string;
813
+ readonly labels?: Labels;
814
+ constructor(client: Geniffy, id: string, opts?: {
815
+ title?: string;
816
+ } & WithLabels);
817
+ /** Sends what is new; resolves to the session's source, or null when nothing was new. */
818
+ save(messages: ChatMessage[]): Promise<Source | null>;
819
+ }
542
820
  export default Geniffy;
package/dist/index.js CHANGED
@@ -10,8 +10,11 @@
10
10
  * Retries: reads, deletes and files.put (the same text twice is the same file) are retried on network errors,
11
11
  * 408, 429 and 5xx; adding is retried only on 429, so a retry never saves a note twice.
12
12
  */
13
- export const VERSION = "0.3.0";
13
+ export const VERSION = "0.5.0";
14
14
  export const DEFAULT_BASE_URL = "https://api.geniffy.com";
15
+ /** Each region's address, by name. An account's memory is stored in the region it was made in, and its key works only
16
+ * there, so a client calls that region; "in" is the default. */
17
+ export const REGIONS = { in: DEFAULT_BASE_URL, eu: "https://eu.api.geniffy.com" };
15
18
  /** A filter in a query string: label=name:value, once for each value. */
16
19
  function labelQuery(labels) {
17
20
  if (!labels)
@@ -70,6 +73,13 @@ export class UnreadableError extends BadRequestError {
70
73
  }
71
74
  export class RateLimitError extends GeniffyError {
72
75
  }
76
+ /**
77
+ * This month's use is up (402, code allowance_used): past the plan, what waits to be learned has reached its fair-use
78
+ * limit (ten months of the plan's learning). Search and recall keep working; saving resumes when the month resets
79
+ * (usage() says when), at once with extra learning on, or on a bigger plan. Not retried.
80
+ */
81
+ export class UsageLimitError extends GeniffyError {
82
+ }
73
83
  export class InternalServerError extends GeniffyError {
74
84
  }
75
85
  function errorFrom(status, body, requestId) {
@@ -84,6 +94,8 @@ function errorFrom(status, body, requestId) {
84
94
  return new UnreadableError(message, opts);
85
95
  if ([400, 409, 413, 422].includes(status))
86
96
  return new BadRequestError(message, opts);
97
+ if (status === 402)
98
+ return new UsageLimitError(message, opts);
87
99
  if (status === 429)
88
100
  return new RateLimitError(message, opts);
89
101
  if (status >= 500)
@@ -96,6 +108,33 @@ function env(name) {
96
108
  const g = globalThis;
97
109
  return g.process?.env?.[name];
98
110
  }
111
+ // An option, else its environment variable. A blank one counts as not set: docker compose passes a variable the
112
+ // host never set as "", which means the default, not a region or an address named "".
113
+ function setting(given, name) {
114
+ return given?.trim() || env(name)?.trim() || undefined;
115
+ }
116
+ // Where calls go: baseURL, else GENIFFY_BASE_URL, else the region's address (region, else GENIFFY_REGION, else "in").
117
+ // A region is checked wherever it is named, a base URL or not. A base URL that is another region's address is refused
118
+ // rather than called: a GENIFFY_BASE_URL left over in an environment would otherwise send one region's data to the
119
+ // other, under a key that works only in its own. Any other address (a local server, a test double) wins as before.
120
+ function baseAddress(baseURL, region) {
121
+ const said = region?.trim() ? "region" : "GENIFFY_REGION";
122
+ const where = setting(region, "GENIFFY_REGION")?.toLowerCase();
123
+ if (where && !Object.prototype.hasOwnProperty.call(REGIONS, where)) {
124
+ throw new TypeError(`${said} is one of: ${Object.keys(REGIONS).join(", ")} (the region your account was made in).`);
125
+ }
126
+ const given = baseURL?.trim() ? "baseURL" : "GENIFFY_BASE_URL";
127
+ const named = setting(baseURL, "GENIFFY_BASE_URL");
128
+ if (!named)
129
+ return REGIONS[(where ?? "in")];
130
+ const url = named.replace(/\/+$/, "");
131
+ const other = Object.keys(REGIONS).find((name) => REGIONS[name] === url.toLowerCase());
132
+ if (where && other && other !== where) {
133
+ throw new TypeError(`${said} is '${where}', but ${given} is the address of region '${other}' (${url}). Keep one ` +
134
+ "of the two: the region your account was made in.");
135
+ }
136
+ return url;
137
+ }
99
138
  function delay(attempt, response) {
100
139
  const after = Number(response?.headers.get("retry-after"));
101
140
  if (response && Number.isFinite(after) && after >= 0 && after <= 60)
@@ -127,7 +166,7 @@ export class Geniffy {
127
166
  }
128
167
  this.#opts = opts;
129
168
  this.#key = key;
130
- this.#base = (opts.baseURL ?? env("GENIFFY_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
169
+ this.#base = baseAddress(opts.baseURL, opts.region);
131
170
  this.#fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
132
171
  this.timeout = opts.timeout ?? 60_000;
133
172
  this.maxRetries = Math.max(0, opts.maxRetries ?? 2);
@@ -230,6 +269,16 @@ export class Geniffy {
230
269
  });
231
270
  return out.memories;
232
271
  }
272
+ /** The same search, with everything else the memory learned that bears on `q`: the memories, then the lessons
273
+ * (rules and how-tos), episodes (what happened) and intentions (open promises) that match it, by meaning and by
274
+ * the words themselves, each naming its source. With labels, or a kind other than all, only memories come back. */
275
+ async searchFull(q, opts = {}) {
276
+ const out = await this.request("POST", "/v1/search", {
277
+ json: { q, limit: opts.limit ?? 10, kind: opts.kind, labels: opts.labels },
278
+ });
279
+ return { memories: out.memories ?? [], lessons: out.lessons ?? [], episodes: out.episodes ?? [],
280
+ intentions: out.intentions ?? [] };
281
+ }
233
282
  /**
234
283
  * The memories that bear on a question, already written out for YOUR prompt.
235
284
  *
@@ -260,12 +309,60 @@ export class Geniffy {
260
309
  brief(subject, opts = {}) {
261
310
  return this.request("GET", "/v1/brief", { query: { subject, limit: opts.limit, label: labelQuery(opts.labels) } });
262
311
  }
312
+ // ── what a session opens with: where things stand, what happened, what was learned and promised
313
+ /**
314
+ * What this moment needs, written out for YOUR prompt within `budgetChars`: where the project stands (goal,
315
+ * focus, open items, decisions, next steps), what is due or was promised, the rules and lessons that apply,
316
+ * what happened (the latest and the most related to `cue` first), then the memories, each dated. Open a session
317
+ * with it, and call it again when the task changes:
318
+ *
319
+ * const system = `${await mem.briefing({ project: "checkout", cue: userMessage })}\n\n${instructions}`;
320
+ *
321
+ * `project` is the label your sources carry (a project, context, thread or repo label); leave it out for every
322
+ * project. Read, not written by a model, so it is fast enough for every turn.
323
+ */
324
+ async briefing(opts = {}) {
325
+ return (await this.briefingFull(opts)).briefing;
326
+ }
327
+ /** The same, with its parts: now, due, lessons, episodes and memories, each with its source. */
328
+ briefingFull(opts = {}) {
329
+ return this.request("POST", "/v1/briefing", {
330
+ json: { project: opts.project, cue: opts.cue ?? "", budget_chars: opts.budgetChars ?? 6000 },
331
+ });
332
+ }
333
+ /** Where things stand, per project: goal, focus, what is open (and since when), decisions with their reasons,
334
+ * next steps, blockers and what was finished. */
335
+ async now(project) {
336
+ return (await this.request("GET", "/v1/now", { query: { project } })).now;
337
+ }
338
+ /** What happened, as stories, newest first: what happened, how it ended, what it led to, its source. */
339
+ async episodes(opts = {}) {
340
+ return (await this.request("GET", "/v1/episodes", { query: { project: opts.project, limit: opts.limit ?? 20 } })).episodes;
341
+ }
342
+ /** Rules, how-tos and lessons, strongest first, each with when it applies and why. */
343
+ async lessons(opts = {}) {
344
+ return (await this.request("GET", "/v1/lessons", { query: { project: opts.project, limit: opts.limit ?? 50 } })).lessons;
345
+ }
346
+ /** Promises and plans, yours and those made to you, with their triggers: open (the default), done or dropped. */
347
+ async intentions(opts = {}) {
348
+ return (await this.request("GET", "/v1/intentions", { query: { status: opts.status ?? "open", limit: opts.limit ?? 50 } })).intentions;
349
+ }
350
+ /** How well the memory answers about its own work: each night it writes questions from what it read, answers them
351
+ * and marks the answers. `health` is the share right (0 to 1), with the questions; null before its first night. */
352
+ memoryHealth() {
353
+ return this.request("GET", "/v1/memory-health");
354
+ }
355
+ /** Mark a promise or plan done, dropped, or open again. */
356
+ async setIntention(id, status = "done") {
357
+ return (await this.request("POST", `/v1/intentions/${Number(id)}`, { json: { status } })).intention;
358
+ }
263
359
  /** What the memory holds and what connects to what. Every line has a memory behind it. */
264
360
  graph() {
265
361
  return this.request("GET", "/v1/graph");
266
362
  }
267
363
  /** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
268
- * came from, every source, and every file by its path (files.get(path) reads each one's text). On
364
+ * came from, every source, every file by its path (files.get(path) reads each one's text), and the stories,
365
+ * lessons and promises read from them, each with every source it names, and where things stand. On
269
366
  * client.space(id), for a user who asks what you hold about them. */
270
367
  export() {
271
368
  return this.request("GET", "/v1/export");
@@ -274,6 +371,23 @@ export class Geniffy {
274
371
  me() {
275
372
  return this.request("GET", "/v1/me");
276
373
  }
374
+ /**
375
+ * This month's use for the whole account, against the plan: tokens learned and waiting, answers, what the plan
376
+ * includes, extra learning, and when it resets. Saving, briefings and search are free and never counted.
377
+ */
378
+ usage() {
379
+ return this.request("GET", "/v1/usage");
380
+ }
381
+ /**
382
+ * An agent's or a chat's session, saved as it goes into one memory: hand save() the whole conversation after each
383
+ * turn, and only the messages it has not sent yet go to Geniffy.
384
+ *
385
+ * const run = mem.session("run-42", { title: "Refund agent" });
386
+ * await run.save(messages); // after every turn
387
+ */
388
+ session(id, opts = {}) {
389
+ return new Session(this, id, opts);
390
+ }
277
391
  /** Which of your users have memory, busiest first. */
278
392
  async spaces() {
279
393
  const out = await this.request("GET", "/v1/spaces");
@@ -291,6 +405,14 @@ export class Geniffy {
291
405
  function addBody(input) {
292
406
  const given = typeof input === "string" ? { text: input } : input;
293
407
  const { saidAt, externalId, ...rest } = given;
408
+ if (rest.session !== undefined) { // the API says the same: refused before anything is sent
409
+ if (!("messages" in rest))
410
+ throw new TypeError("session goes with messages: the turns of the session.");
411
+ if (externalId !== undefined)
412
+ throw new TypeError("Send session or externalId, not both: the session is the source's id.");
413
+ if (saidAt !== undefined)
414
+ throw new TypeError("saidAt does not go with session: each turn is dated as it arrives.");
415
+ }
294
416
  const body = { ...rest };
295
417
  if (saidAt !== undefined)
296
418
  body.said_at = saidAt instanceof Date ? saidAt.toISOString() : String(saidAt);
@@ -575,4 +697,70 @@ export class Files {
575
697
  return out.moved ?? 0;
576
698
  }
577
699
  }
700
+ // ── sessions saved as they go ─────────────────────────────────────────────────────────────────────────────
701
+ const SESSION_CALL = 500; // the most messages one call takes
702
+ // A message written out with its keys in order, so the same message reads the same however it was built.
703
+ function stable(value) {
704
+ if (Array.isArray(value))
705
+ return `[${value.map(stable).join(",")}]`;
706
+ if (value && typeof value === "object") {
707
+ const o = value;
708
+ return `{${Object.keys(o).sort().filter((k) => o[k] !== undefined).map((k) => `${JSON.stringify(k)}:${stable(o[k])}`).join(",")}}`;
709
+ }
710
+ return JSON.stringify(value) ?? "null";
711
+ }
712
+ // Where the messages not sent yet begin: after the last one already sent. A conversation that only grew still has it
713
+ // where it was sent from (at, the count of messages up to it), so a message said again later ("Okay.") is never taken
714
+ // for it and the turns before it lost. When it has moved (the conversation was rewritten or compacted), after its
715
+ // latest copy; when it is no longer there, at the start: saving a turn twice is better than losing what changed.
716
+ function unsentFrom(messages, last, at) {
717
+ if (last === null)
718
+ return 0;
719
+ if (at > 0 && at <= messages.length && stable(messages[at - 1]) === last)
720
+ return at;
721
+ for (let i = messages.length - 1; i >= 0; i--) {
722
+ if (stable(messages[i]) === last)
723
+ return i + 1;
724
+ }
725
+ return 0;
726
+ }
727
+ /**
728
+ * An agent's or a chat's session, saved as it goes into one memory for the whole session. Hand save() the whole
729
+ * conversation after each turn: only the messages after the last one it sent go to Geniffy, at most 500 a call, so a
730
+ * session of any length is never sent twice. When that message is no longer there (the agent rewrote or compacted
731
+ * its history), what it holds now is saved again rather than lost. Made by client.session(id).
732
+ */
733
+ export class Session {
734
+ client;
735
+ #last = null;
736
+ #at = 0; // where the last message sent was: how many messages, up to and including it
737
+ id;
738
+ title;
739
+ labels;
740
+ constructor(client, id, opts = {}) {
741
+ this.client = client;
742
+ this.id = String(id);
743
+ this.title = opts.title;
744
+ this.labels = opts.labels;
745
+ }
746
+ /** Sends what is new; resolves to the session's source, or null when nothing was new. */
747
+ async save(messages) {
748
+ const all = [...messages];
749
+ const from = unsentFrom(all, this.#last, this.#at);
750
+ const fresh = all.slice(from);
751
+ let source = null;
752
+ for (let i = 0; i < fresh.length; i += SESSION_CALL) {
753
+ const part = fresh.slice(i, i + SESSION_CALL);
754
+ const input = { messages: part, session: this.id };
755
+ if (this.title)
756
+ input.title = this.title;
757
+ if (this.labels)
758
+ input.labels = this.labels;
759
+ source = await this.client.memories.add(input);
760
+ this.#last = stable(part[part.length - 1]);
761
+ this.#at = from + i + part.length;
762
+ }
763
+ return source;
764
+ }
765
+ }
578
766
  export default Geniffy;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "geniffy",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",
@@ -20,7 +20,7 @@
20
20
  "engines": { "node": ">=18" },
21
21
  "scripts": {
22
22
  "build": "tsc -p tsconfig.json",
23
- "test": "npm run build && node --test test/client.test.mjs test/claude.test.mjs"
23
+ "test": "npm run build && node --test test/client.test.mjs test/claude.test.mjs test/briefing.test.mjs test/session-usage.test.mjs test/regions-search.test.mjs"
24
24
  },
25
25
  "keywords": ["memory", "ai", "agents", "llm", "rag", "geniffy", "claude", "memory-tool"],
26
26
  "homepage": "https://docs.geniffy.com/sdks/typescript",