geniffy 0.5.0 → 0.6.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 +70 -3
- package/dist/index.d.ts +144 -11
- package/dist/index.js +82 -6
- package/dist/wrap.d.ts +37 -0
- package/dist/wrap.js +362 -0
- package/package.json +24 -7
package/README.md
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/Geniffy/geniffy-typescript/actions/workflows/ci.yml) [](https://www.npmjs.com/package/geniffy) [](LICENSE) [](https://docs.geniffy.com/sdks/typescript)
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
The official TypeScript and JavaScript SDK for Geniffy, the memory infrastructure for AI applications
|
|
6
|
+
and agents. Write what each of your users tells you, and put what is known about them in front of your
|
|
7
|
+
model, with where every line came from. When nothing is known, it says so instead of guessing. No
|
|
8
|
+
dependencies: it uses the platform's `fetch` (Node 18+, Deno, Bun, edge runtimes).
|
|
8
9
|
|
|
9
10
|
```bash
|
|
10
11
|
npm install geniffy
|
|
@@ -71,6 +72,63 @@ last one it sent, 500 at a time, so a session of any length is never sent twice;
|
|
|
71
72
|
history, what it holds now is saved again rather than lost. Sending the new turns yourself instead:
|
|
72
73
|
`mem.memories.add({ messages: newTurns, session: runId })`.
|
|
73
74
|
|
|
75
|
+
## One line: wrap your model client
|
|
76
|
+
|
|
77
|
+
Hand `wrap()` your Anthropic or OpenAI client and use what comes back the same way. Before each reply the user's
|
|
78
|
+
briefing goes in the system prompt, after your own. After the final answer the run is saved, tool calls included.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
82
|
+
import { Geniffy } from "geniffy";
|
|
83
|
+
|
|
84
|
+
const client = new Geniffy();
|
|
85
|
+
const claude = client.space(user.id).wrap(new Anthropic(), { session: chat.id });
|
|
86
|
+
|
|
87
|
+
const reply = await claude.messages.create({ model: "claude-opus-5-5", max_tokens: 1024, messages });
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const gpt = client.space(user.id).wrap(new OpenAI(), { session: chat.id });
|
|
92
|
+
|
|
93
|
+
await gpt.chat.completions.create({ model: "gpt-5.5", messages });
|
|
94
|
+
await gpt.responses.create({ model: "gpt-5.5", input: "What did I say about refunds?" });
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
- **Memory is on** `messages.create`, `chat.completions.create` and `responses.create`, with `stream: true` too, and
|
|
98
|
+
a stream handed on with `toReadableStream()` is saved as well. The rest of the client is its own. The `stream()`
|
|
99
|
+
helpers start the model before Geniffy can be read, so they are refused rather than quietly left without memory.
|
|
100
|
+
- **`session`** is the conversation, your chat's id. The history you send with every call is not saved again. Without
|
|
101
|
+
it, each run is a memory of its own.
|
|
102
|
+
- **A run with tools** asks Geniffy once and saves once, when the final answer comes.
|
|
103
|
+
- **If Geniffy can't be reached**, the reply goes on without memory, and `onError` hears about it.
|
|
104
|
+
- **A cached system prompt** stays cached: the memory goes after your blocks.
|
|
105
|
+
- `project: "billing"` keeps the briefing to one project and labels what is saved. `remember: false` only reads, and
|
|
106
|
+
`briefing: false` only saves.
|
|
107
|
+
- A client with no space is refused, since every user of your app would land in your own memory. For your own memory,
|
|
108
|
+
pass `{ ownMemory: true }`.
|
|
109
|
+
|
|
110
|
+
Building on the Vercel AI SDK? `geniffy-ai-sdk` does this for any model the AI SDK supports.
|
|
111
|
+
|
|
112
|
+
## When something changes
|
|
113
|
+
|
|
114
|
+
Memory stays current by itself. `changes()` says what ended, was replaced, was done or moved after a cursor, so an agent
|
|
115
|
+
that holds a briefing through a long run hears about it:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const held = await mem.briefingFull({ cue: task });
|
|
119
|
+
// ...
|
|
120
|
+
const news = await mem.changes({ since: held.cursor ?? 0 }); // { changes, cursor, more }
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Set where a user is once, and "tomorrow" and "the end of the month" read on their clock:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
await mem.setTimezone("Europe/Berlin"); // or an offset, "+05:30"; { dateOrder: "MDY" } for 11/12 as November
|
|
127
|
+
await mem.memories.add({ text: "Call me tomorrow", timezone: "America/Los_Angeles" }); // or for one save
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`said_at` on a memory is when it was said, and `date` is the day it is about.
|
|
131
|
+
|
|
74
132
|
## Spaces: one memory per user
|
|
75
133
|
|
|
76
134
|
A space is your own name for one of your users. Bind a client to it and every call stays inside it.
|
|
@@ -144,6 +202,15 @@ await mem.sources.list();
|
|
|
144
202
|
await mem.sources.delete(source.id); // a source, and what only it taught
|
|
145
203
|
```
|
|
146
204
|
|
|
205
|
+
`sources.text(id)` gives a saved prompt, rule or document back word for word and whole, not the facts learned from
|
|
206
|
+
it. `sources.text({ externalId: "doc-1" })` finds it by your own id. `sources.learnAgain(id)` reads one again, for a
|
|
207
|
+
source read before the reader improved or one that failed: what only it taught is taken back and learned anew, and what
|
|
208
|
+
you struck or forgot stays that way.
|
|
209
|
+
|
|
210
|
+
`graph()` is who and what the memory holds and how they connect. `graph({ history: true })` adds the lines that ended.
|
|
211
|
+
Each of `(await graph()).possible_duplicates` names two nodes that may be one: `resolveDuplicate(pair.id, { same: true })`
|
|
212
|
+
merges them and `undoMerge(mergeId)` takes that back, while `{ same: false }` keeps them apart for good.
|
|
213
|
+
|
|
147
214
|
## Files, and Claude's memory tool
|
|
148
215
|
|
|
149
216
|
Keep files by path with their text exactly as written, whitespace and line endings included. Geniffy also learns
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* The official TypeScript and JavaScript SDK for Geniffy, the memory infrastructure for AI applications and agents.
|
|
3
3
|
*
|
|
4
4
|
* import { Geniffy } from "geniffy";
|
|
5
5
|
* const g = new Geniffy(); // reads GENIFFY_API_KEY
|
|
@@ -10,7 +10,9 @@
|
|
|
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
|
-
|
|
13
|
+
import { type WrapOptions } from "./wrap.js";
|
|
14
|
+
export type { WrapOptions };
|
|
15
|
+
export declare const VERSION = "0.6.0";
|
|
14
16
|
export declare const DEFAULT_BASE_URL = "https://api.geniffy.com";
|
|
15
17
|
/** 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
18
|
* there, so a client calls that region; "in" is the default. */
|
|
@@ -36,7 +38,10 @@ export interface Memory {
|
|
|
36
38
|
/** current, or clash when two memories disagree */
|
|
37
39
|
status: string;
|
|
38
40
|
learned_at?: string | null;
|
|
41
|
+
/** when it was said */
|
|
39
42
|
said_at?: string | null;
|
|
43
|
+
/** the day it is about, when it is about one */
|
|
44
|
+
date?: string | null;
|
|
40
45
|
source?: SourceRef | null;
|
|
41
46
|
/** the sentence it came from (on memories.get) */
|
|
42
47
|
quote?: string | null;
|
|
@@ -70,7 +75,7 @@ export interface Usage {
|
|
|
70
75
|
/** written answers and context blocks */
|
|
71
76
|
answers: number;
|
|
72
77
|
included_answers: number;
|
|
73
|
-
/** extra learning: past the plan, learned and answered at once,
|
|
78
|
+
/** extra learning: past the plan, learned and answered at once, per million tokens and per 1,000 answers at the rate on geniffy.com/pricing */
|
|
74
79
|
extra_on: boolean;
|
|
75
80
|
extra_cap_usd: number;
|
|
76
81
|
extra_used_usd: number;
|
|
@@ -285,7 +290,9 @@ export declare class Geniffy {
|
|
|
285
290
|
cue?: string;
|
|
286
291
|
budgetChars?: number;
|
|
287
292
|
}): Promise<string>;
|
|
288
|
-
/** The same, with its parts: now, due
|
|
293
|
+
/** The same, with its parts: now (each with its status), due (each with due and overdue), lessons, episodes and
|
|
294
|
+
* memories, each with its source; last (the latest sitting), unread (the newest turns not yet read into the rest)
|
|
295
|
+
* and cursor (what changes() takes, to hear what ends while you hold this). */
|
|
289
296
|
briefingFull(opts?: {
|
|
290
297
|
project?: string;
|
|
291
298
|
cue?: string;
|
|
@@ -314,8 +321,43 @@ export declare class Geniffy {
|
|
|
314
321
|
memoryHealth(): Promise<MemoryHealth>;
|
|
315
322
|
/** Mark a promise or plan done, dropped, or open again. */
|
|
316
323
|
setIntention(id: number, status?: "done" | "dropped" | "open"): Promise<Intention>;
|
|
317
|
-
/**
|
|
318
|
-
|
|
324
|
+
/** Who and what the memory holds, and how they connect, as it is now: nodes, edges, possible_duplicates (pairs to
|
|
325
|
+
* decide with resolveDuplicate) and typing (true while older memories are still being sorted). { history: true }
|
|
326
|
+
* adds lines that ended: such an edge has current false and until, the day it ended. */
|
|
327
|
+
graph(opts?: {
|
|
328
|
+
history?: boolean;
|
|
329
|
+
}): Promise<Graph>;
|
|
330
|
+
/** Decide one of graph()'s possible_duplicates. same: true merges the two, keeping the fuller name and every memory
|
|
331
|
+
* and line of both, and returns merge_id, which undoMerge takes. same: false keeps them apart, and the pair is not
|
|
332
|
+
* suggested again. */
|
|
333
|
+
resolveDuplicate(id: number, opts: {
|
|
334
|
+
same: boolean;
|
|
335
|
+
}): Promise<{
|
|
336
|
+
id: number;
|
|
337
|
+
same: boolean;
|
|
338
|
+
merge_id: number | null;
|
|
339
|
+
}>;
|
|
340
|
+
/** The two records apart again, each with its own memories and lines. */
|
|
341
|
+
undoMerge(mergeId: number): Promise<{
|
|
342
|
+
merge_id: number;
|
|
343
|
+
undone: boolean;
|
|
344
|
+
already: boolean;
|
|
345
|
+
}>;
|
|
346
|
+
/** What changed after a cursor, oldest first: what ended, was replaced, was done, was moved or now clashes. For an
|
|
347
|
+
* agent that holds a briefing through a long run: pass briefingFull()'s cursor, act on what comes back, then pass
|
|
348
|
+
* the cursor this returns. since 0 reads every change. */
|
|
349
|
+
changes(opts?: {
|
|
350
|
+
since?: number;
|
|
351
|
+
limit?: number;
|
|
352
|
+
}): Promise<Changes>;
|
|
353
|
+
/** Where this user is, as setTimezone left it. */
|
|
354
|
+
timezone(): Promise<Timezone>;
|
|
355
|
+
/** Set where this user is, once, so their dates read right: "tomorrow" said at 22:30 in Los Angeles is the next day
|
|
356
|
+
* there, whatever the day is in UTC. timezone is an IANA zone or an offset ("Europe/Berlin", "+05:30"; "" goes back
|
|
357
|
+
* to UTC). dateOrder is how they write a numeric date: "DMY", "MDY", or "" for their zone's way. */
|
|
358
|
+
setTimezone(timezone?: string, opts?: {
|
|
359
|
+
dateOrder?: string;
|
|
360
|
+
}): Promise<Timezone>;
|
|
319
361
|
/** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
|
|
320
362
|
* came from, every source, every file by its path (files.get(path) reads each one's text), and the stories,
|
|
321
363
|
* lessons and promises read from them, each with every source it names, and where things stand. On
|
|
@@ -341,7 +383,19 @@ export declare class Geniffy {
|
|
|
341
383
|
*/
|
|
342
384
|
session(id: string, opts?: {
|
|
343
385
|
title?: string;
|
|
344
|
-
} & WithLabels): Session;
|
|
386
|
+
} & WithLabels & WithTimezone): Session;
|
|
387
|
+
/**
|
|
388
|
+
* A model client that remembers, in one line. Hand it an Anthropic or OpenAI client and use what comes back the same
|
|
389
|
+
* way:
|
|
390
|
+
*
|
|
391
|
+
* const claude = client.space(user.id).wrap(new Anthropic(), { session: chat.id });
|
|
392
|
+
* const reply = await claude.messages.create({ model, max_tokens: 1024, messages });
|
|
393
|
+
*
|
|
394
|
+
* Before each reply the user's briefing goes in the system prompt, after your own. After the final answer the run is
|
|
395
|
+
* saved, tool calls included, into one memory for the session. `stream: true` works as it did. If Geniffy can't be
|
|
396
|
+
* reached the reply goes on without memory, and onError hears about it.
|
|
397
|
+
*/
|
|
398
|
+
wrap<T extends object>(client: T, options?: WrapOptions): T;
|
|
345
399
|
/** Which of your users have memory, busiest first. */
|
|
346
400
|
spaces(): Promise<SpaceRow[]>;
|
|
347
401
|
/**
|
|
@@ -420,6 +474,8 @@ export interface State {
|
|
|
420
474
|
project: string | null;
|
|
421
475
|
goal: string | null;
|
|
422
476
|
focus: string | null;
|
|
477
|
+
/** the work's state in a line: where it stopped */
|
|
478
|
+
status?: string | null;
|
|
423
479
|
open: Array<{
|
|
424
480
|
text: string;
|
|
425
481
|
since: string | null;
|
|
@@ -429,11 +485,14 @@ export interface State {
|
|
|
429
485
|
why: string | null;
|
|
430
486
|
when: string | null;
|
|
431
487
|
}>;
|
|
488
|
+
/** in the order they were said */
|
|
432
489
|
next_steps: string[];
|
|
433
490
|
blockers: string[];
|
|
491
|
+
/** what was finished; `by`, the words that closed it */
|
|
434
492
|
done: Array<{
|
|
435
493
|
text: string;
|
|
436
494
|
when: string | null;
|
|
495
|
+
by?: string | null;
|
|
437
496
|
}>;
|
|
438
497
|
updated_at: string | null;
|
|
439
498
|
}
|
|
@@ -485,6 +544,10 @@ export interface Intention {
|
|
|
485
544
|
trigger: "time" | "context" | "person" | "event" | null;
|
|
486
545
|
/** when it is due, for a time */
|
|
487
546
|
at: string | null;
|
|
547
|
+
/** when it is due, as the person's own day or time */
|
|
548
|
+
due?: string | null;
|
|
549
|
+
/** true when that has passed and it is still open */
|
|
550
|
+
overdue?: boolean;
|
|
488
551
|
/** its trigger in words: "when testing ends" */
|
|
489
552
|
when: string | null;
|
|
490
553
|
status: "open" | "done" | "dropped" | null;
|
|
@@ -528,21 +591,76 @@ export interface Briefing {
|
|
|
528
591
|
due: Intention[];
|
|
529
592
|
lessons: Lesson[];
|
|
530
593
|
episodes: Episode[];
|
|
594
|
+
/** the latest sitting, oldest first */
|
|
595
|
+
last?: Episode[];
|
|
596
|
+
/** the newest turns, not yet read into the rest */
|
|
597
|
+
unread?: {
|
|
598
|
+
at: string | null;
|
|
599
|
+
turns: Array<{
|
|
600
|
+
speaker: string | null;
|
|
601
|
+
text: string | null;
|
|
602
|
+
}>;
|
|
603
|
+
} | null;
|
|
531
604
|
memories: Memory[];
|
|
605
|
+
/** what changes() takes, to hear what ends while you hold this */
|
|
606
|
+
cursor?: number | null;
|
|
532
607
|
}
|
|
533
608
|
export interface Graph {
|
|
609
|
+
/** type: person, company, project, place or other */
|
|
534
610
|
nodes: Array<{
|
|
535
611
|
id: string;
|
|
536
612
|
label: string;
|
|
537
613
|
type: string;
|
|
538
614
|
memories: number;
|
|
539
615
|
}>;
|
|
616
|
+
/** current is false, and until is the day it ended, on a line from history: true */
|
|
540
617
|
edges: Array<{
|
|
541
618
|
from: string;
|
|
542
619
|
to: string;
|
|
543
620
|
label: string;
|
|
544
621
|
memory_ids: number[];
|
|
622
|
+
current?: boolean;
|
|
623
|
+
until?: string | null;
|
|
545
624
|
}>;
|
|
625
|
+
/** two nodes that may be one, a and b by their ids, to decide with resolveDuplicate() */
|
|
626
|
+
possible_duplicates?: Array<{
|
|
627
|
+
id: number;
|
|
628
|
+
a: string;
|
|
629
|
+
b: string;
|
|
630
|
+
reason: string;
|
|
631
|
+
}>;
|
|
632
|
+
/** true while older memories are still being sorted */
|
|
633
|
+
typing?: boolean;
|
|
634
|
+
}
|
|
635
|
+
/** Something that stopped being true: what ended, was replaced, was done, was moved or now clashes. */
|
|
636
|
+
export interface Change {
|
|
637
|
+
id: number;
|
|
638
|
+
at: string;
|
|
639
|
+
/** replaced, ended, done, scheduled, moved or clash */
|
|
640
|
+
change: string;
|
|
641
|
+
/** memory, rule, promise, or where_things_stand */
|
|
642
|
+
kind: string;
|
|
643
|
+
was?: string | null;
|
|
644
|
+
now?: string | null;
|
|
645
|
+
because?: string | null;
|
|
646
|
+
/** the day it ends, when that is still to come */
|
|
647
|
+
until?: string | null;
|
|
648
|
+
memory_id?: number | null;
|
|
649
|
+
field?: string | null;
|
|
650
|
+
project?: string | null;
|
|
651
|
+
source: SourceRef;
|
|
652
|
+
}
|
|
653
|
+
export interface Changes {
|
|
654
|
+
changes: Change[];
|
|
655
|
+
/** pass this as `since` next time */
|
|
656
|
+
cursor: number;
|
|
657
|
+
more: boolean;
|
|
658
|
+
}
|
|
659
|
+
/** Where a user is, so their dates read right. */
|
|
660
|
+
export interface Timezone {
|
|
661
|
+
space?: string | null;
|
|
662
|
+
timezone: string | null;
|
|
663
|
+
date_order: string | null;
|
|
546
664
|
}
|
|
547
665
|
export interface SpaceRow {
|
|
548
666
|
/** Your own name for that user. */
|
|
@@ -588,10 +706,16 @@ export interface ExternalId {
|
|
|
588
706
|
export interface WithLabels {
|
|
589
707
|
labels?: Labels;
|
|
590
708
|
}
|
|
709
|
+
/** Where it was said: an IANA zone or an offset ("America/Los_Angeles", "+05:30"), so "tomorrow" and "the end of the
|
|
710
|
+
* month" read on that person's clock. Left out: the offset saidAt or the messages' times carry, else the zone
|
|
711
|
+
* setTimezone gave them, else UTC. */
|
|
712
|
+
export interface WithTimezone {
|
|
713
|
+
timezone?: string;
|
|
714
|
+
}
|
|
591
715
|
export type AddInput = string | ({
|
|
592
716
|
text: string;
|
|
593
717
|
title?: string;
|
|
594
|
-
} & SaidAt & ExternalId & WithLabels) | ({
|
|
718
|
+
} & SaidAt & ExternalId & WithLabels & WithTimezone) | ({
|
|
595
719
|
url: string;
|
|
596
720
|
title?: string;
|
|
597
721
|
} & ExternalId & WithLabels)
|
|
@@ -600,14 +724,14 @@ export type AddInput = string | ({
|
|
|
600
724
|
| ({
|
|
601
725
|
messages: ChatMessage[];
|
|
602
726
|
title?: string;
|
|
603
|
-
} & SaidAt & ExternalId & WithLabels)
|
|
727
|
+
} & SaidAt & ExternalId & WithLabels & WithTimezone)
|
|
604
728
|
/** The next turns of an agent's or a chat's session: each call adds its messages to one memory for the whole
|
|
605
729
|
* session, however long it gets, so send only what is new since the last call (session().save() works that out). */
|
|
606
730
|
| ({
|
|
607
731
|
messages: ChatMessage[];
|
|
608
732
|
session: string;
|
|
609
733
|
title?: string;
|
|
610
|
-
} & WithLabels);
|
|
734
|
+
} & WithLabels & WithTimezone);
|
|
611
735
|
/** A source named by Geniffy's id, or by the external id you added it under. */
|
|
612
736
|
export type SourceLookup = string | {
|
|
613
737
|
externalId: string;
|
|
@@ -731,6 +855,14 @@ export declare class Sources {
|
|
|
731
855
|
private deleteAllBut;
|
|
732
856
|
/** A source, by its id or as { externalId } (a NotFoundError when no source has that external id). */
|
|
733
857
|
get(ref: SourceLookup): Promise<Source>;
|
|
858
|
+
/** What a source said, word for word and whole, by its id or as { externalId }: a saved prompt, rule or document back
|
|
859
|
+
* as it went in, not the facts learned from it. A conversation comes turn by turn with who said each. Secrets are
|
|
860
|
+
* masked and a forgotten person is redacted, as in every other read. */
|
|
861
|
+
text(ref: SourceLookup): Promise<string>;
|
|
862
|
+
/** Read a source again from the words it holds, for one read before the reader improved or one that failed. What only
|
|
863
|
+
* it taught is taken back and it is learned anew under the same id, so wait() on it as on a new source. It counts
|
|
864
|
+
* like any save. What you struck or forgot stays that way. */
|
|
865
|
+
learnAgain(ref: SourceLookup): Promise<Source>;
|
|
734
866
|
/** Delete a source and every memory learned only from it, by its id or as { externalId }: the call for a
|
|
735
867
|
* record your app deleted. */
|
|
736
868
|
delete(ref: SourceLookup): Promise<void>;
|
|
@@ -811,9 +943,10 @@ export declare class Session {
|
|
|
811
943
|
readonly id: string;
|
|
812
944
|
readonly title?: string;
|
|
813
945
|
readonly labels?: Labels;
|
|
946
|
+
readonly timezone?: string;
|
|
814
947
|
constructor(client: Geniffy, id: string, opts?: {
|
|
815
948
|
title?: string;
|
|
816
|
-
} & WithLabels);
|
|
949
|
+
} & WithLabels & WithTimezone);
|
|
817
950
|
/** Sends what is new; resolves to the session's source, or null when nothing was new. */
|
|
818
951
|
save(messages: ChatMessage[]): Promise<Source | null>;
|
|
819
952
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* The official TypeScript and JavaScript SDK for Geniffy, the memory infrastructure for AI applications and agents.
|
|
3
3
|
*
|
|
4
4
|
* import { Geniffy } from "geniffy";
|
|
5
5
|
* const g = new Geniffy(); // reads GENIFFY_API_KEY
|
|
@@ -10,7 +10,8 @@
|
|
|
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
|
-
|
|
13
|
+
import { wrapClient } from "./wrap.js";
|
|
14
|
+
export const VERSION = "0.6.0";
|
|
14
15
|
export const DEFAULT_BASE_URL = "https://api.geniffy.com";
|
|
15
16
|
/** 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
17
|
* there, so a client calls that region; "in" is the default. */
|
|
@@ -324,7 +325,9 @@ export class Geniffy {
|
|
|
324
325
|
async briefing(opts = {}) {
|
|
325
326
|
return (await this.briefingFull(opts)).briefing;
|
|
326
327
|
}
|
|
327
|
-
/** The same, with its parts: now, due
|
|
328
|
+
/** The same, with its parts: now (each with its status), due (each with due and overdue), lessons, episodes and
|
|
329
|
+
* memories, each with its source; last (the latest sitting), unread (the newest turns not yet read into the rest)
|
|
330
|
+
* and cursor (what changes() takes, to hear what ends while you hold this). */
|
|
328
331
|
briefingFull(opts = {}) {
|
|
329
332
|
return this.request("POST", "/v1/briefing", {
|
|
330
333
|
json: { project: opts.project, cue: opts.cue ?? "", budget_chars: opts.budgetChars ?? 6000 },
|
|
@@ -356,9 +359,40 @@ export class Geniffy {
|
|
|
356
359
|
async setIntention(id, status = "done") {
|
|
357
360
|
return (await this.request("POST", `/v1/intentions/${Number(id)}`, { json: { status } })).intention;
|
|
358
361
|
}
|
|
359
|
-
/**
|
|
360
|
-
|
|
361
|
-
|
|
362
|
+
/** Who and what the memory holds, and how they connect, as it is now: nodes, edges, possible_duplicates (pairs to
|
|
363
|
+
* decide with resolveDuplicate) and typing (true while older memories are still being sorted). { history: true }
|
|
364
|
+
* adds lines that ended: such an edge has current false and until, the day it ended. */
|
|
365
|
+
graph(opts = {}) {
|
|
366
|
+
return this.request("GET", "/v1/graph", { query: { history: opts.history ? "true" : undefined } });
|
|
367
|
+
}
|
|
368
|
+
/** Decide one of graph()'s possible_duplicates. same: true merges the two, keeping the fuller name and every memory
|
|
369
|
+
* and line of both, and returns merge_id, which undoMerge takes. same: false keeps them apart, and the pair is not
|
|
370
|
+
* suggested again. */
|
|
371
|
+
resolveDuplicate(id, opts) {
|
|
372
|
+
return this.request("POST", `/v1/graph/duplicates/${Number(id)}`, { json: { same: Boolean(opts.same) } });
|
|
373
|
+
}
|
|
374
|
+
/** The two records apart again, each with its own memories and lines. */
|
|
375
|
+
undoMerge(mergeId) {
|
|
376
|
+
return this.request("POST", `/v1/graph/merges/${Number(mergeId)}/undo`);
|
|
377
|
+
}
|
|
378
|
+
/** What changed after a cursor, oldest first: what ended, was replaced, was done, was moved or now clashes. For an
|
|
379
|
+
* agent that holds a briefing through a long run: pass briefingFull()'s cursor, act on what comes back, then pass
|
|
380
|
+
* the cursor this returns. since 0 reads every change. */
|
|
381
|
+
changes(opts = {}) {
|
|
382
|
+
return this.request("GET", "/v1/changes", { query: { since: opts.since ?? 0, limit: opts.limit ?? 50 } });
|
|
383
|
+
}
|
|
384
|
+
/** Where this user is, as setTimezone left it. */
|
|
385
|
+
timezone() {
|
|
386
|
+
return this.request("GET", "/v1/timezone");
|
|
387
|
+
}
|
|
388
|
+
/** Set where this user is, once, so their dates read right: "tomorrow" said at 22:30 in Los Angeles is the next day
|
|
389
|
+
* there, whatever the day is in UTC. timezone is an IANA zone or an offset ("Europe/Berlin", "+05:30"; "" goes back
|
|
390
|
+
* to UTC). dateOrder is how they write a numeric date: "DMY", "MDY", or "" for their zone's way. */
|
|
391
|
+
setTimezone(timezone, opts = {}) {
|
|
392
|
+
if (timezone === undefined && opts.dateOrder === undefined) {
|
|
393
|
+
throw new TypeError("Pass a timezone (an IANA zone or an offset such as +05:30), dateOrder, or both.");
|
|
394
|
+
}
|
|
395
|
+
return this.request("PUT", "/v1/timezone", { json: { timezone, date_order: opts.dateOrder } });
|
|
362
396
|
}
|
|
363
397
|
/** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
|
|
364
398
|
* came from, every source, every file by its path (files.get(path) reads each one's text), and the stories,
|
|
@@ -388,6 +422,20 @@ export class Geniffy {
|
|
|
388
422
|
session(id, opts = {}) {
|
|
389
423
|
return new Session(this, id, opts);
|
|
390
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* A model client that remembers, in one line. Hand it an Anthropic or OpenAI client and use what comes back the same
|
|
427
|
+
* way:
|
|
428
|
+
*
|
|
429
|
+
* const claude = client.space(user.id).wrap(new Anthropic(), { session: chat.id });
|
|
430
|
+
* const reply = await claude.messages.create({ model, max_tokens: 1024, messages });
|
|
431
|
+
*
|
|
432
|
+
* Before each reply the user's briefing goes in the system prompt, after your own. After the final answer the run is
|
|
433
|
+
* saved, tool calls included, into one memory for the session. `stream: true` works as it did. If Geniffy can't be
|
|
434
|
+
* reached the reply goes on without memory, and onError hears about it.
|
|
435
|
+
*/
|
|
436
|
+
wrap(client, options = {}) {
|
|
437
|
+
return wrapClient(this, client, options);
|
|
438
|
+
}
|
|
391
439
|
/** Which of your users have memory, busiest first. */
|
|
392
440
|
async spaces() {
|
|
393
441
|
const out = await this.request("GET", "/v1/spaces");
|
|
@@ -546,6 +594,7 @@ export class Sections {
|
|
|
546
594
|
// Each call deletes up to 100 sources (or files) and says whether more are left; this many calls is the most one
|
|
547
595
|
// deleteLabelled() or files.deletePrefix() makes, so a filter that somehow keeps matching cannot loop for ever.
|
|
548
596
|
const DELETE_CALLS = 1000;
|
|
597
|
+
const TEXT_PAGE = 100_000; // the most characters one call returns
|
|
549
598
|
export class Sources {
|
|
550
599
|
client;
|
|
551
600
|
constructor(client) {
|
|
@@ -617,6 +666,29 @@ export class Sources {
|
|
|
617
666
|
}
|
|
618
667
|
return sources[0];
|
|
619
668
|
}
|
|
669
|
+
/** What a source said, word for word and whole, by its id or as { externalId }: a saved prompt, rule or document back
|
|
670
|
+
* as it went in, not the facts learned from it. A conversation comes turn by turn with who said each. Secrets are
|
|
671
|
+
* masked and a forgotten person is redacted, as in every other read. */
|
|
672
|
+
async text(ref) {
|
|
673
|
+
const { id, externalId } = lookup(ref);
|
|
674
|
+
const sid = id !== undefined ? id : (await this.get({ externalId: externalId })).id;
|
|
675
|
+
let out = "";
|
|
676
|
+
let offset = 0;
|
|
677
|
+
while (offset !== null) {
|
|
678
|
+
const page = await this.client.request("GET", `/v1/sources/${encodeURIComponent(sid)}/text`, { query: { offset, limit: TEXT_PAGE } });
|
|
679
|
+
out += page.text ?? "";
|
|
680
|
+
offset = page.next ?? null;
|
|
681
|
+
}
|
|
682
|
+
return out;
|
|
683
|
+
}
|
|
684
|
+
/** Read a source again from the words it holds, for one read before the reader improved or one that failed. What only
|
|
685
|
+
* it taught is taken back and it is learned anew under the same id, so wait() on it as on a new source. It counts
|
|
686
|
+
* like any save. What you struck or forgot stays that way. */
|
|
687
|
+
async learnAgain(ref) {
|
|
688
|
+
const { id, externalId } = lookup(ref);
|
|
689
|
+
const sid = id !== undefined ? id : (await this.get({ externalId: externalId })).id;
|
|
690
|
+
return (await this.client.request("POST", `/v1/sources/${encodeURIComponent(sid)}/learn`)).source;
|
|
691
|
+
}
|
|
620
692
|
/** Delete a source and every memory learned only from it, by its id or as { externalId }: the call for a
|
|
621
693
|
* record your app deleted. */
|
|
622
694
|
async delete(ref) {
|
|
@@ -737,11 +809,13 @@ export class Session {
|
|
|
737
809
|
id;
|
|
738
810
|
title;
|
|
739
811
|
labels;
|
|
812
|
+
timezone;
|
|
740
813
|
constructor(client, id, opts = {}) {
|
|
741
814
|
this.client = client;
|
|
742
815
|
this.id = String(id);
|
|
743
816
|
this.title = opts.title;
|
|
744
817
|
this.labels = opts.labels;
|
|
818
|
+
this.timezone = opts.timezone;
|
|
745
819
|
}
|
|
746
820
|
/** Sends what is new; resolves to the session's source, or null when nothing was new. */
|
|
747
821
|
async save(messages) {
|
|
@@ -756,6 +830,8 @@ export class Session {
|
|
|
756
830
|
input.title = this.title;
|
|
757
831
|
if (this.labels)
|
|
758
832
|
input.labels = this.labels;
|
|
833
|
+
if (this.timezone)
|
|
834
|
+
input.timezone = this.timezone;
|
|
759
835
|
source = await this.client.memories.add(input);
|
|
760
836
|
this.#last = stable(part[part.length - 1]);
|
|
761
837
|
this.#at = from + i + part.length;
|
package/dist/wrap.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mem.wrap(client): a model client that remembers, in one line.
|
|
3
|
+
*
|
|
4
|
+
* const claude = client.space(user.id).wrap(new Anthropic(), { session: chat.id });
|
|
5
|
+
* const reply = await claude.messages.create({ model, max_tokens: 1024, messages });
|
|
6
|
+
*
|
|
7
|
+
* Before each reply the user's briefing goes in the system prompt, after the app's own. After the final answer the
|
|
8
|
+
* run is saved, tool calls included, into one memory for the conversation. Nothing here imports a model's SDK: a
|
|
9
|
+
* client is told apart by what it has. Three calls carry memory: Anthropic's messages.create, and OpenAI's
|
|
10
|
+
* chat.completions.create and responses.create, each with `stream: true` too. The SDKs' stream() helpers start the
|
|
11
|
+
* model before anything can be awaited, so they are refused rather than quietly left without memory; everything else
|
|
12
|
+
* on the client goes straight through.
|
|
13
|
+
*
|
|
14
|
+
* A failed read or save never fails the reply: the model is called without memory, and onError hears about it.
|
|
15
|
+
*/
|
|
16
|
+
import type { Geniffy } from "./index.js";
|
|
17
|
+
export interface WrapOptions {
|
|
18
|
+
/** The conversation: your chat's id. The history you send with every call is not saved again. Without it, each run
|
|
19
|
+
* is a memory of its own. */
|
|
20
|
+
session?: string;
|
|
21
|
+
/** The project label its sources carry, and what the briefing is read for. */
|
|
22
|
+
project?: string;
|
|
23
|
+
/** false: read only, nothing is saved. */
|
|
24
|
+
remember?: boolean;
|
|
25
|
+
/** false: save only, nothing is read. */
|
|
26
|
+
briefing?: boolean;
|
|
27
|
+
/** How long the briefing may be. 6000 by default. */
|
|
28
|
+
budgetChars?: number;
|
|
29
|
+
/** Replaces the words that tell the model what its memory is. "" for none. */
|
|
30
|
+
instructions?: string;
|
|
31
|
+
/** Hears a read or a save that failed. By default, console.warn. */
|
|
32
|
+
onError?: (error: unknown) => void;
|
|
33
|
+
/** A client with no space is refused, since a user with no id would land in your own memory. true allows it. */
|
|
34
|
+
ownMemory?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export declare const DEFAULT_INSTRUCTIONS: string;
|
|
37
|
+
export declare function wrapClient<T extends object>(mem: Geniffy, client: T, options?: WrapOptions): T;
|
package/dist/wrap.js
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
export const DEFAULT_INSTRUCTIONS = "What follows is this user's memory: what this app knows from before, each line with its date. " +
|
|
2
|
+
"Use it when it helps and don't recite it. If it doesn't cover something, say so instead of guessing.";
|
|
3
|
+
// Without this a model tells the user it can't remember anything, in the very turn that is being saved.
|
|
4
|
+
const SAVED_AS_IT_GOES = " This conversation is saved to that memory as it goes, so what the user tells you here will be there next time. " +
|
|
5
|
+
"Never tell them you can't remember things.";
|
|
6
|
+
// A briefing with nothing in it still says so: a model reads an empty memory as permission to invent.
|
|
7
|
+
const NOTHING_YET = "Nothing is remembered about this user yet.";
|
|
8
|
+
const NO_SPACE = "wrap() needs a user: client.space(userId).wrap(...). A client with no space reads your own memory, so every user " +
|
|
9
|
+
"of your app would land in it. For your own memory, pass { ownMemory: true }.";
|
|
10
|
+
const NOT_A_MODEL = "wrap() takes an Anthropic or OpenAI client, one that has messages, or chat and responses.";
|
|
11
|
+
const NO_HELPER = "A wrapped client remembers through create({ stream: true }). The stream() helper starts the model before Geniffy " +
|
|
12
|
+
"can be read, so it is refused rather than left without memory.";
|
|
13
|
+
const PER_CALL = 500; // the most messages Geniffy takes in one call
|
|
14
|
+
// What Geniffy keeps of a message, so nothing larger is sent: a turn's words, a tool call's input and a tool's output.
|
|
15
|
+
const TURN_CHARS = 50_000;
|
|
16
|
+
const CALL_CHARS = 2_000;
|
|
17
|
+
const RESULT_CHARS = 4_000;
|
|
18
|
+
// A run with tools calls the model once per step with the same question, so Geniffy is asked once. Kept for a few
|
|
19
|
+
// seconds and a few hundred questions, so a client wrapped once for a whole app neither grows nor goes stale.
|
|
20
|
+
const KEEP_MS = 30_000;
|
|
21
|
+
const MOST_HELD = 256;
|
|
22
|
+
const TEXT_TYPES = new Set(["text", "input_text", "output_text"]);
|
|
23
|
+
function textOf(content) {
|
|
24
|
+
if (typeof content === "string")
|
|
25
|
+
return content;
|
|
26
|
+
if (Array.isArray(content)) {
|
|
27
|
+
return content.filter((p) => TEXT_TYPES.has(p?.type) && p.text).map((p) => String(p.text)).join("\n");
|
|
28
|
+
}
|
|
29
|
+
return "";
|
|
30
|
+
}
|
|
31
|
+
const clip = (text, most) => String(text ?? "").trim().slice(0, most);
|
|
32
|
+
function call(name, args, id) {
|
|
33
|
+
let input = args;
|
|
34
|
+
if (typeof input === "string") {
|
|
35
|
+
try {
|
|
36
|
+
input = JSON.parse(input); // OpenAI hands a call's input as JSON text
|
|
37
|
+
}
|
|
38
|
+
catch { /* kept as it came */ }
|
|
39
|
+
}
|
|
40
|
+
const shown = typeof input === "string" ? input : JSON.stringify(input ?? {});
|
|
41
|
+
const out = {
|
|
42
|
+
name: String(name || "tool").slice(0, 200),
|
|
43
|
+
args: shown.length <= CALL_CHARS ? (input ?? {}) : shown.slice(0, CALL_CHARS),
|
|
44
|
+
};
|
|
45
|
+
if (id)
|
|
46
|
+
out.id = String(id).slice(0, 200);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
function toolResult(content, id, name) {
|
|
50
|
+
const text = typeof content === "string" ? content : textOf(content) || JSON.stringify(content ?? "");
|
|
51
|
+
const out = { role: "tool", content: clip(text, RESULT_CHARS) };
|
|
52
|
+
if (name)
|
|
53
|
+
out.name = String(name).slice(0, 200);
|
|
54
|
+
if (id)
|
|
55
|
+
out.tool_call_id = String(id).slice(0, 200);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
// The run being answered: from just after the last answer before the user's last words, so the history an app sends
|
|
59
|
+
// with every call is not saved again, and two messages sent at once are both in it.
|
|
60
|
+
function turnOf(said) {
|
|
61
|
+
let user = -1;
|
|
62
|
+
for (let i = said.length - 1; i >= 0; i--)
|
|
63
|
+
if (said[i].role === "user") {
|
|
64
|
+
user = i;
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
for (let i = user - 1; i >= 0; i--)
|
|
68
|
+
if (said[i].role === "assistant")
|
|
69
|
+
return said.slice(i + 1);
|
|
70
|
+
return said;
|
|
71
|
+
}
|
|
72
|
+
function titleOf(said) {
|
|
73
|
+
const first = said.find((m) => m.role === "user" && m.content.trim());
|
|
74
|
+
if (!first)
|
|
75
|
+
return undefined;
|
|
76
|
+
const words = first.content.split(/\s+/).join(" ").trim();
|
|
77
|
+
return words.length <= 80 ? words : `${words.slice(0, 80).replace(/\s+\S*$/, "")}...`;
|
|
78
|
+
}
|
|
79
|
+
function lastUser(said) {
|
|
80
|
+
for (let i = said.length - 1; i >= 0; i--)
|
|
81
|
+
if (said[i].role === "user" && said[i].content)
|
|
82
|
+
return said[i].content;
|
|
83
|
+
return "";
|
|
84
|
+
}
|
|
85
|
+
const ANTHROPIC_FINAL = new Set(["end_turn", "stop_sequence", "max_tokens"]);
|
|
86
|
+
const OPENAI_FINAL = new Set(["stop", "length"]);
|
|
87
|
+
// ── each API's shapes: what was said, where the memory goes, what came back ──────────────────────────────────────
|
|
88
|
+
const anthropic = {
|
|
89
|
+
said(params) {
|
|
90
|
+
const out = [];
|
|
91
|
+
for (const m of params.messages ?? []) {
|
|
92
|
+
const blocks = Array.isArray(m.content) ? m.content : [];
|
|
93
|
+
if (m.role === "user") {
|
|
94
|
+
for (const b of blocks) { // what a tool returned arrives in a user message
|
|
95
|
+
if (b?.type === "tool_result")
|
|
96
|
+
out.push(toolResult(b.content ?? "", b.tool_use_id));
|
|
97
|
+
}
|
|
98
|
+
const text = clip(textOf(m.content), TURN_CHARS);
|
|
99
|
+
if (text)
|
|
100
|
+
out.push({ role: "user", content: text });
|
|
101
|
+
}
|
|
102
|
+
else if (m.role === "assistant") {
|
|
103
|
+
const turn = { role: "assistant", content: clip(textOf(m.content), TURN_CHARS) };
|
|
104
|
+
const calls = blocks.filter((b) => b?.type === "tool_use").slice(0, 100).map((b) => call(b.name, b.input, b.id));
|
|
105
|
+
if (calls.length)
|
|
106
|
+
turn.tool_calls = calls;
|
|
107
|
+
out.push(turn);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
},
|
|
112
|
+
withMemory(params, block) {
|
|
113
|
+
const { system } = params;
|
|
114
|
+
if (Array.isArray(system))
|
|
115
|
+
return { ...params, system: [...system, { type: "text", text: block }] }; // a cached prefix stays cached
|
|
116
|
+
return { ...params, system: typeof system === "string" && system ? `${system}\n\n${block}` : block };
|
|
117
|
+
},
|
|
118
|
+
reply(response) {
|
|
119
|
+
return { text: textOf(response?.content), final: ANTHROPIC_FINAL.has(response?.stop_reason) };
|
|
120
|
+
},
|
|
121
|
+
collect(reply, event) {
|
|
122
|
+
if (event?.type === "content_block_delta" && event.delta?.type === "text_delta")
|
|
123
|
+
reply.text += event.delta.text ?? "";
|
|
124
|
+
else if (event?.type === "message_delta")
|
|
125
|
+
reply.final = ANTHROPIC_FINAL.has(event.delta?.stop_reason);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
const openaiChat = {
|
|
129
|
+
said(params) {
|
|
130
|
+
const out = [];
|
|
131
|
+
for (const m of params.messages ?? []) {
|
|
132
|
+
if (m.role === "user") {
|
|
133
|
+
const text = clip(textOf(m.content), TURN_CHARS);
|
|
134
|
+
if (text)
|
|
135
|
+
out.push({ role: "user", content: text });
|
|
136
|
+
}
|
|
137
|
+
else if (m.role === "assistant") {
|
|
138
|
+
const turn = { role: "assistant", content: clip(textOf(m.content), TURN_CHARS) };
|
|
139
|
+
const calls = (m.tool_calls ?? []).slice(0, 100).map((c) => call(c.function?.name, c.function?.arguments, c.id));
|
|
140
|
+
if (calls.length)
|
|
141
|
+
turn.tool_calls = calls;
|
|
142
|
+
out.push(turn);
|
|
143
|
+
}
|
|
144
|
+
else if (m.role === "tool") {
|
|
145
|
+
out.push(toolResult(m.content ?? "", m.tool_call_id, m.name));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
},
|
|
150
|
+
withMemory(params, block) {
|
|
151
|
+
const messages = [...(params.messages ?? [])];
|
|
152
|
+
let at = 0;
|
|
153
|
+
while (at < messages.length && (messages[at].role === "system" || messages[at].role === "developer"))
|
|
154
|
+
at++; // after the app's own
|
|
155
|
+
messages.splice(at, 0, { role: "system", content: block });
|
|
156
|
+
return { ...params, messages };
|
|
157
|
+
},
|
|
158
|
+
reply(response) {
|
|
159
|
+
const choice = response?.choices?.[0];
|
|
160
|
+
return { text: textOf(choice?.message?.content), final: OPENAI_FINAL.has(choice?.finish_reason) };
|
|
161
|
+
},
|
|
162
|
+
collect(reply, chunk) {
|
|
163
|
+
const choice = chunk?.choices?.[0];
|
|
164
|
+
if (!choice)
|
|
165
|
+
return;
|
|
166
|
+
reply.text += choice.delta?.content ?? "";
|
|
167
|
+
if (choice.finish_reason)
|
|
168
|
+
reply.final = OPENAI_FINAL.has(choice.finish_reason);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
const finishedResponse = (response) => response?.status === "completed" && !(response?.output ?? []).some((item) => item?.type === "function_call");
|
|
172
|
+
const openaiResponses = {
|
|
173
|
+
said(params) {
|
|
174
|
+
const given = params.input;
|
|
175
|
+
if (typeof given === "string")
|
|
176
|
+
return given.trim() ? [{ role: "user", content: clip(given, TURN_CHARS) }] : [];
|
|
177
|
+
const out = [];
|
|
178
|
+
for (const item of given ?? []) {
|
|
179
|
+
if (item?.type === "function_call") {
|
|
180
|
+
out.push({ role: "assistant", content: "", tool_calls: [call(item.name, item.arguments, item.call_id)] });
|
|
181
|
+
}
|
|
182
|
+
else if (item?.type === "function_call_output") {
|
|
183
|
+
out.push(toolResult(item.output ?? "", item.call_id));
|
|
184
|
+
}
|
|
185
|
+
else if (item?.role === "user" || item?.role === "assistant") {
|
|
186
|
+
const text = clip(textOf(item.content), TURN_CHARS);
|
|
187
|
+
if (text)
|
|
188
|
+
out.push({ role: item.role, content: text });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
},
|
|
193
|
+
withMemory(params, block) {
|
|
194
|
+
const own = params.instructions;
|
|
195
|
+
return { ...params, instructions: typeof own === "string" && own ? `${own}\n\n${block}` : block };
|
|
196
|
+
},
|
|
197
|
+
reply(response) {
|
|
198
|
+
const text = response?.output_text ||
|
|
199
|
+
(response?.output ?? []).filter((item) => item?.type === "message").map((item) => textOf(item.content)).join("\n");
|
|
200
|
+
return { text: String(text ?? ""), final: finishedResponse(response) };
|
|
201
|
+
},
|
|
202
|
+
collect(reply, event) {
|
|
203
|
+
if (event?.type === "response.output_text.delta")
|
|
204
|
+
reply.text += event.delta ?? "";
|
|
205
|
+
else if (event?.type === "response.completed")
|
|
206
|
+
reply.final = finishedResponse(event.response);
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
// ── what the wrapper does around a call ──────────────────────────────────────────────────────────────────────────
|
|
210
|
+
class Memory {
|
|
211
|
+
#mem;
|
|
212
|
+
#session;
|
|
213
|
+
#project;
|
|
214
|
+
#remember;
|
|
215
|
+
#briefing;
|
|
216
|
+
#budgetChars;
|
|
217
|
+
#instructions;
|
|
218
|
+
#onError;
|
|
219
|
+
#held = new Map();
|
|
220
|
+
constructor(mem, options) {
|
|
221
|
+
this.#mem = mem;
|
|
222
|
+
this.#session = options.session;
|
|
223
|
+
this.#project = options.project;
|
|
224
|
+
this.#remember = options.remember !== false;
|
|
225
|
+
this.#briefing = options.briefing !== false;
|
|
226
|
+
this.#budgetChars = options.budgetChars ?? 6000;
|
|
227
|
+
this.#instructions = options.instructions ?? DEFAULT_INSTRUCTIONS + (this.#remember ? SAVED_AS_IT_GOES : "");
|
|
228
|
+
this.#onError = options.onError ?? ((error) => console.warn(`[geniffy] ${error?.message || error}`));
|
|
229
|
+
}
|
|
230
|
+
#heard(error) {
|
|
231
|
+
try {
|
|
232
|
+
this.#onError(error);
|
|
233
|
+
}
|
|
234
|
+
catch (broken) { // a broken handler must not take the reply down either
|
|
235
|
+
console.warn(`[geniffy] onError failed: ${broken?.message || broken}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
#read(cue) {
|
|
239
|
+
if (!this.#briefing)
|
|
240
|
+
return Promise.resolve(null);
|
|
241
|
+
const held = this.#held.get(cue);
|
|
242
|
+
if (held && Date.now() - held.at < KEEP_MS)
|
|
243
|
+
return held.text;
|
|
244
|
+
this.#held.delete(cue);
|
|
245
|
+
const text = this.#mem.briefing({ project: this.#project, cue, budgetChars: this.#budgetChars })
|
|
246
|
+
.then((got) => got || NOTHING_YET)
|
|
247
|
+
.catch((error) => {
|
|
248
|
+
this.#held.delete(cue);
|
|
249
|
+
this.#heard(error);
|
|
250
|
+
return null;
|
|
251
|
+
});
|
|
252
|
+
this.#held.set(cue, { at: Date.now(), text });
|
|
253
|
+
while (this.#held.size > MOST_HELD)
|
|
254
|
+
this.#held.delete(this.#held.keys().next().value);
|
|
255
|
+
return text;
|
|
256
|
+
}
|
|
257
|
+
async prepared(shape, params) {
|
|
258
|
+
const context = await this.#read(lastUser(shape.said(params)));
|
|
259
|
+
if (!context)
|
|
260
|
+
return params;
|
|
261
|
+
const words = this.#instructions ? `${this.#instructions}\n\n` : "";
|
|
262
|
+
return shape.withMemory(params, `${words}<memory>\n${context}\n</memory>`);
|
|
263
|
+
}
|
|
264
|
+
async save(shape, params, reply) {
|
|
265
|
+
if (!this.#remember || !reply.final || !reply.text.trim())
|
|
266
|
+
return;
|
|
267
|
+
const said = turnOf(shape.said(params)).filter((m) => m.content || m.tool_calls || m.role === "tool");
|
|
268
|
+
if (!said.some((m) => m.role === "user"))
|
|
269
|
+
return;
|
|
270
|
+
const all = [...said, { role: "assistant", content: clip(reply.text, TURN_CHARS) }];
|
|
271
|
+
const name = this.#session ?? `run-${globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`}`;
|
|
272
|
+
const title = titleOf(all);
|
|
273
|
+
try {
|
|
274
|
+
for (let i = 0; i < all.length; i += PER_CALL) {
|
|
275
|
+
await this.#mem.memories.add({ messages: all.slice(i, i + PER_CALL), session: name,
|
|
276
|
+
...(title ? { title } : {}), ...(this.#project ? { labels: { project: this.#project } } : {}) });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
this.#heard(error);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
// The model's stream, passed on as it comes, and the end of it is the save. The rest (controller, tee) is the stream's;
|
|
285
|
+
// toReadableStream reads through the iterator below, so a stream handed straight to a Response is saved too.
|
|
286
|
+
function watched(stream, memory, shape, params) {
|
|
287
|
+
const reply = { text: "", final: false };
|
|
288
|
+
let saved = false;
|
|
289
|
+
const iterate = async function* () {
|
|
290
|
+
for await (const event of stream) {
|
|
291
|
+
shape.collect(reply, event);
|
|
292
|
+
yield event;
|
|
293
|
+
}
|
|
294
|
+
if (!saved) {
|
|
295
|
+
saved = true;
|
|
296
|
+
await memory.save(shape, params, reply);
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
const proxy = new Proxy(stream, {
|
|
300
|
+
get(target, name) {
|
|
301
|
+
if (name === Symbol.asyncIterator)
|
|
302
|
+
return iterate;
|
|
303
|
+
const value = Reflect.get(target, name, target);
|
|
304
|
+
if (name === "toReadableStream")
|
|
305
|
+
return value.bind(proxy);
|
|
306
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
return proxy;
|
|
310
|
+
}
|
|
311
|
+
function door(real, shape, memory) {
|
|
312
|
+
return new Proxy(real, {
|
|
313
|
+
get(target, name) {
|
|
314
|
+
if (name === "create") {
|
|
315
|
+
return async (params, ...rest) => {
|
|
316
|
+
const response = await target.create(await memory.prepared(shape, params), ...rest);
|
|
317
|
+
if (params?.stream === true)
|
|
318
|
+
return watched(response, memory, shape, params);
|
|
319
|
+
await memory.save(shape, params, shape.reply(response));
|
|
320
|
+
return response;
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
if (name === "stream")
|
|
324
|
+
return () => { throw new TypeError(NO_HELPER); };
|
|
325
|
+
const value = Reflect.get(target, name, target);
|
|
326
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
327
|
+
},
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function withMemory(client, memory) {
|
|
331
|
+
return new Proxy(client, {
|
|
332
|
+
get(target, name) {
|
|
333
|
+
const value = Reflect.get(target, name, target);
|
|
334
|
+
if (name === "messages" && value)
|
|
335
|
+
return door(value, anthropic, memory);
|
|
336
|
+
if (name === "responses" && value)
|
|
337
|
+
return door(value, openaiResponses, memory);
|
|
338
|
+
if (name === "chat" && value) {
|
|
339
|
+
return new Proxy(value, {
|
|
340
|
+
get(chat, part) {
|
|
341
|
+
const got = Reflect.get(chat, part, chat);
|
|
342
|
+
if (part === "completions")
|
|
343
|
+
return door(got, openaiChat, memory);
|
|
344
|
+
return typeof got === "function" ? got.bind(chat) : got;
|
|
345
|
+
},
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
if (name === "withOptions" && typeof value === "function") {
|
|
349
|
+
return (...args) => withMemory(value.apply(target, args), memory);
|
|
350
|
+
}
|
|
351
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
352
|
+
},
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
export function wrapClient(mem, client, options = {}) {
|
|
356
|
+
if (!mem.boundSpace && !options.ownMemory)
|
|
357
|
+
throw new TypeError(NO_SPACE);
|
|
358
|
+
const given = client;
|
|
359
|
+
if (!given || !(given.messages || given.chat || given.responses))
|
|
360
|
+
throw new TypeError(NOT_A_MODEL);
|
|
361
|
+
return withMemory(client, new Memory(mem, options));
|
|
362
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "geniffy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "The official TypeScript and JavaScript SDK for Geniffy, the memory infrastructure for AI applications and agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -15,14 +15,28 @@
|
|
|
15
15
|
"import": "./dist/claude.js"
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
|
-
"files": [
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
19
22
|
"sideEffects": false,
|
|
20
|
-
"engines": {
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
21
26
|
"scripts": {
|
|
22
27
|
"build": "tsc -p tsconfig.json",
|
|
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"
|
|
28
|
+
"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 test/changes-timezone-graph.test.mjs test/wrap.test.mjs"
|
|
24
29
|
},
|
|
25
|
-
"keywords": [
|
|
30
|
+
"keywords": [
|
|
31
|
+
"memory",
|
|
32
|
+
"ai",
|
|
33
|
+
"agents",
|
|
34
|
+
"llm",
|
|
35
|
+
"rag",
|
|
36
|
+
"geniffy",
|
|
37
|
+
"claude",
|
|
38
|
+
"memory-tool"
|
|
39
|
+
],
|
|
26
40
|
"homepage": "https://docs.geniffy.com/sdks/typescript",
|
|
27
41
|
"repository": {
|
|
28
42
|
"type": "git",
|
|
@@ -37,10 +51,13 @@
|
|
|
37
51
|
"@anthropic-ai/sdk": ">=0.72.0"
|
|
38
52
|
},
|
|
39
53
|
"peerDependenciesMeta": {
|
|
40
|
-
"@anthropic-ai/sdk": {
|
|
54
|
+
"@anthropic-ai/sdk": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
41
57
|
},
|
|
42
58
|
"devDependencies": {
|
|
43
59
|
"@anthropic-ai/sdk": "^0.131.0",
|
|
60
|
+
"openai": "^7.50.0",
|
|
44
61
|
"typescript": "^5.6.0"
|
|
45
62
|
}
|
|
46
63
|
}
|