geniffy 0.2.0 → 0.4.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
@@ -41,6 +41,31 @@ await mem.search("renewal", { limit: 5 }); // the raw memories, ranke
41
41
  `context()` and `ask()` judge whether anything bears on the question. `search()` ranks and does not
42
42
  judge: it returns its best matches for any question at all.
43
43
 
44
+ ## Agents: open with the briefing, save every turn
45
+
46
+ An agent, or any chat that runs over many turns, does two things: it opens each session with the briefing, and it
47
+ saves every turn as it goes.
48
+
49
+ ```ts
50
+ const system = await mem.briefing({ project: "checkout", cue: task }); // where things stand, what is due, the
51
+ // rules that apply, what happened, then
52
+ // the memories, each dated
53
+ const run = mem.session(runId, { title: "Refund agent" });
54
+ // ...
55
+ await run.save(messages); // after every turn: only what is new is sent
56
+ ```
57
+
58
+ `briefing()` is written to go straight into a system prompt. `briefingFull()` has its parts, and each part can be
59
+ read on its own: `now()` (where each project stands), `episodes()`, `lessons()` and `intentions()`;
60
+ `setIntention(id, "done")` marks a promise kept, and `memoryHealth()` says how well the memory answers about its
61
+ own work.
62
+
63
+ A session's turns go into one memory for the whole session, tool calls and what came back included, in the shapes
64
+ OpenAI, Anthropic, the Vercel AI SDK, Gemini and LangChain hold them. `save()` sends only the messages after the
65
+ last one it sent, 500 at a time, so a session of any length is never sent twice; if your agent rewrites its
66
+ history, what it holds now is saved again rather than lost. Sending the new turns yourself instead:
67
+ `mem.memories.add({ messages: newTurns, session: runId })`.
68
+
44
69
  ## Spaces: one memory per user
45
70
 
46
71
  A space is your own name for one of your users. Bind a client to it and every call stays inside it.
@@ -114,13 +139,61 @@ await mem.sources.list();
114
139
  await mem.sources.delete(source.id); // a source, and what only it taught
115
140
  ```
116
141
 
142
+ ## Files, and Claude's memory tool
143
+
144
+ Keep files by path with their text exactly as written, whitespace and line endings included. Geniffy also learns
145
+ from each one like a note titled by its path, so `context()` and `ask()` recall what it says: a replace learns only
146
+ what changed, and deleting a file takes back what only it taught.
147
+
148
+ ```ts
149
+ await mem.files.put("/notes/plan.md", "# Plan\n- Pilots run for 6 weeks.\n"); // creates or replaces it
150
+ const { text } = await mem.files.get("/notes/plan.md"); // exactly as it was put
151
+ await mem.files.list({ prefix: "/notes/" }); // by path, without the text
152
+ await mem.files.move("/notes", "/archive/notes"); // a file, or a folder and all in it
153
+ await mem.files.delete("/archive/notes/plan.md");
154
+ await mem.files.deletePrefix("/archive/"); // everything in that folder
155
+ ```
156
+
157
+ That makes Geniffy the storage for Claude's memory tool, which keeps Claude's own notes as files under `/memories`.
158
+ With `geniffy/claude` those files live in that user's memory: each comes back to Claude exactly as it wrote it, and
159
+ what Claude wrote is recalled by `context()` and `ask()` like anything else the user told you.
160
+
161
+ ```ts
162
+ import Anthropic from "@anthropic-ai/sdk";
163
+ import { betaMemoryTool } from "@anthropic-ai/sdk/helpers/beta/memory";
164
+ import { geniffyMemoryHandlers } from "geniffy/claude";
165
+
166
+ const message = await new Anthropic().beta.messages.toolRunner({
167
+ model: "claude-opus-5-5",
168
+ max_tokens: 16000,
169
+ tools: [betaMemoryTool(geniffyMemoryHandlers(client.space(`user_${user.id}`)))],
170
+ messages: [{ role: "user", content: "Remember that I prefer email follow-ups." }],
171
+ });
172
+ ```
173
+
174
+ Every command answers with the sentences Anthropic's memory tool documentation gives, a path outside `/memories` is
175
+ refused, and every file carries the labels `{ channel: "claude-memory" }`: `{ labels: LABELS }` keeps a read to what
176
+ Claude wrote, and `clearAllMemory(mem)` deletes it all (both from `geniffy/claude`). The tool runner runs the tool
177
+ calls of one reply at the same time, so the handlers take them one after another: two edits to one file both land.
178
+ `geniffy/claude` needs `@anthropic-ai/sdk` 0.72 or later, an optional peer dependency; `geniffy` itself still has none.
179
+
180
+ ## This month's use
181
+
182
+ ```ts
183
+ await client.usage(); // tokens learned and waiting, answers, what the plan includes, extra learning, when it resets
184
+ ```
185
+
186
+ Saving, briefings, search and recall are free. Past your plan, a source comes back with status `"waiting"`: kept,
187
+ found by search, and learned next month or at once with extra learning on. Only at the fair-use limit does adding
188
+ throw `UsageLimitError`.
189
+
117
190
  ## Errors, retries and request ids
118
191
 
119
192
  Every error carries the API's own sentence: `AuthenticationError` (a wrong or revoked key),
120
- `NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `InternalServerError`,
121
- `APIConnectionError`; all extend `GeniffyError`. Reads are retried twice on network errors, 408, 429 and
122
- 5xx; adding is retried only on 429, so a retry never saves a note twice. Pass `{ maxRetries, timeout }`
123
- to the constructor to change that.
193
+ `NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `UsageLimitError` (this month's use is
194
+ up; not retried), `InternalServerError`, `APIConnectionError`; all extend `GeniffyError`. Reads, and putting a file (the same text twice is the same
195
+ file), are retried twice on network errors, 408, 429 and 5xx; adding is retried only on 429, so a retry never
196
+ saves a note twice. Pass `{ maxRetries, timeout }` to the constructor to change that.
124
197
 
125
198
  Every response carries an `X-Request-ID`, and every error carries it as `error.requestId`. Paste it into
126
199
  **Requests** in the Geniffy app to see that exact call: what was asked, what came back, and how long it took.
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Claude's memory tool, stored in Geniffy.
3
+ *
4
+ * import Anthropic from "@anthropic-ai/sdk";
5
+ * import { betaMemoryTool } from "@anthropic-ai/sdk/helpers/beta/memory";
6
+ * import { Geniffy } from "geniffy";
7
+ * import { geniffyMemoryHandlers } from "geniffy/claude";
8
+ *
9
+ * const mem = new Geniffy().space("customer_1042"); // one of your users
10
+ * const message = await new Anthropic().beta.messages.toolRunner({
11
+ * model: "claude-opus-5-5",
12
+ * max_tokens: 16000,
13
+ * tools: [betaMemoryTool(geniffyMemoryHandlers(mem))],
14
+ * messages: [{ role: "user", content: "Remember that I prefer email follow-ups." }],
15
+ * });
16
+ *
17
+ * Claude's memory tool (type memory_20250818) keeps notes as files under /memories and needs each one back exactly as
18
+ * it wrote it. These handlers keep them as files in a Geniffy memory: the text comes back character for character,
19
+ * and Geniffy also learns from it like a note, so context() and ask() recall what Claude wrote anywhere else in your
20
+ * app. Deleting a file takes back what only it taught.
21
+ *
22
+ * Needs @anthropic-ai/sdk 0.72 or later (npm install @anthropic-ai/sdk); `geniffy` itself does not. Every file the
23
+ * tool writes carries LABELS. A directory is every file whose path starts with it, and its size is what they hold;
24
+ * sizes are in characters. Each command answers with the sentences Anthropic's memory tool documentation gives, the
25
+ * same as geniffy.claude in Python; a command that cannot be done throws the SDK's ToolError with that sentence, so
26
+ * the tool runner sends it back to Claude as an error result.
27
+ */
28
+ import type { Geniffy, Labels } from "./index.js";
29
+ /** The memory tool's commands, as Claude sends them. */
30
+ export interface MemoryViewCommand {
31
+ command: "view";
32
+ path: string;
33
+ /** [start_line, end_line], 1-indexed; [start_line, -1] is the rest of the file */
34
+ view_range?: number[];
35
+ }
36
+ export interface MemoryCreateCommand {
37
+ command: "create";
38
+ path: string;
39
+ file_text: string;
40
+ }
41
+ export interface MemoryStrReplaceCommand {
42
+ command: "str_replace";
43
+ path: string;
44
+ old_str: string;
45
+ /** left out, old_str is deleted */
46
+ new_str?: string;
47
+ }
48
+ export interface MemoryInsertCommand {
49
+ command: "insert";
50
+ path: string;
51
+ /** the line to insert after; 0 is before the first */
52
+ insert_line: number;
53
+ insert_text: string;
54
+ }
55
+ export interface MemoryDeleteCommand {
56
+ command: "delete";
57
+ path: string;
58
+ }
59
+ export interface MemoryRenameCommand {
60
+ command: "rename";
61
+ old_path: string;
62
+ new_path: string;
63
+ }
64
+ export type MemoryCommand = MemoryViewCommand | MemoryCreateCommand | MemoryStrReplaceCommand | MemoryInsertCommand | MemoryDeleteCommand | MemoryRenameCommand;
65
+ /** A handler for each command: what `betaMemoryTool` takes. Each resolves to the tool result's text. A command that
66
+ * cannot be done rejects with the SDK's ToolError, whose `content` is the sentence for Claude; a failure of Geniffy
67
+ * itself (a revoked key, no connection) rejects with its GeniffyError. */
68
+ export interface GeniffyMemoryHandlers {
69
+ view(command: MemoryViewCommand): Promise<string>;
70
+ create(command: MemoryCreateCommand): Promise<string>;
71
+ str_replace(command: MemoryStrReplaceCommand): Promise<string>;
72
+ insert(command: MemoryInsertCommand): Promise<string>;
73
+ delete(command: MemoryDeleteCommand): Promise<string>;
74
+ rename(command: MemoryRenameCommand): Promise<string>;
75
+ }
76
+ export declare const ROOT = "/memories";
77
+ /** On every file the tool writes, so a read can keep to what Claude wrote: `{ labels: LABELS }`. */
78
+ export declare const LABELS: Readonly<Labels>;
79
+ /**
80
+ * Claude's memory tool, kept in a Geniffy memory: `betaMemoryTool(geniffyMemoryHandlers(client.space(userId)))` in
81
+ * the tools of `client.beta.messages.toolRunner`.
82
+ *
83
+ * `memory` is a Geniffy client bound to one of your users with client.space(userId), so each user's Claude keeps its
84
+ * own notes, or the client itself for your own memory. Claude's files are that memory's files under /memories, each
85
+ * labelled { channel: "claude-memory" }: mem.files.list({ prefix: "/memories/" }) lists them, and context() and ask()
86
+ * recall what they say.
87
+ *
88
+ * The handlers run one command at a time, in the order they are called, so the edits of one reply all land. Use one
89
+ * set of handlers for each conversation: two sets editing the same user's files at once can still overwrite each
90
+ * other's edits, as two editors of one file would.
91
+ */
92
+ export declare function geniffyMemoryHandlers(memory: Geniffy): GeniffyMemoryHandlers;
93
+ /** Delete every file under /memories, and what only they taught: for your app to call, such as when a user resets
94
+ * their assistant. It is not one of the tool's commands, so Claude cannot call it. */
95
+ export declare function clearAllMemory(memory: Geniffy): Promise<string>;
package/dist/claude.js ADDED
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Claude's memory tool, stored in Geniffy.
3
+ *
4
+ * import Anthropic from "@anthropic-ai/sdk";
5
+ * import { betaMemoryTool } from "@anthropic-ai/sdk/helpers/beta/memory";
6
+ * import { Geniffy } from "geniffy";
7
+ * import { geniffyMemoryHandlers } from "geniffy/claude";
8
+ *
9
+ * const mem = new Geniffy().space("customer_1042"); // one of your users
10
+ * const message = await new Anthropic().beta.messages.toolRunner({
11
+ * model: "claude-opus-5-5",
12
+ * max_tokens: 16000,
13
+ * tools: [betaMemoryTool(geniffyMemoryHandlers(mem))],
14
+ * messages: [{ role: "user", content: "Remember that I prefer email follow-ups." }],
15
+ * });
16
+ *
17
+ * Claude's memory tool (type memory_20250818) keeps notes as files under /memories and needs each one back exactly as
18
+ * it wrote it. These handlers keep them as files in a Geniffy memory: the text comes back character for character,
19
+ * and Geniffy also learns from it like a note, so context() and ask() recall what Claude wrote anywhere else in your
20
+ * app. Deleting a file takes back what only it taught.
21
+ *
22
+ * Needs @anthropic-ai/sdk 0.72 or later (npm install @anthropic-ai/sdk); `geniffy` itself does not. Every file the
23
+ * tool writes carries LABELS. A directory is every file whose path starts with it, and its size is what they hold;
24
+ * sizes are in characters. Each command answers with the sentences Anthropic's memory tool documentation gives, the
25
+ * same as geniffy.claude in Python; a command that cannot be done throws the SDK's ToolError with that sentence, so
26
+ * the tool runner sends it back to Claude as an error result.
27
+ */
28
+ import { ToolError } from "@anthropic-ai/sdk/resources/beta/messages";
29
+ import { BadRequestError, NotFoundError } from "./index.js";
30
+ export const ROOT = "/memories";
31
+ /** On every file the tool writes, so a read can keep to what Claude wrote: `{ labels: LABELS }`. */
32
+ export const LABELS = Object.freeze({ channel: "claude-memory" });
33
+ const PAGE = 200; // the most files one listing returns
34
+ const PAGES = 1000; // the most pages one view reads, so a listing that keeps going cannot loop for ever
35
+ const MAX_PATH = 255; // the longest path Geniffy keeps
36
+ const MAX_LINES = 999_999;
37
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
38
+ function filesOf(memory) {
39
+ const files = memory?.files;
40
+ if (!files || typeof files.get !== "function") {
41
+ throw new TypeError("Pass a Geniffy client: client.space(userId) for one of your users, or the client itself for your own memory.");
42
+ }
43
+ return files;
44
+ }
45
+ /**
46
+ * Claude's memory tool, kept in a Geniffy memory: `betaMemoryTool(geniffyMemoryHandlers(client.space(userId)))` in
47
+ * the tools of `client.beta.messages.toolRunner`.
48
+ *
49
+ * `memory` is a Geniffy client bound to one of your users with client.space(userId), so each user's Claude keeps its
50
+ * own notes, or the client itself for your own memory. Claude's files are that memory's files under /memories, each
51
+ * labelled { channel: "claude-memory" }: mem.files.list({ prefix: "/memories/" }) lists them, and context() and ask()
52
+ * recall what they say.
53
+ *
54
+ * The handlers run one command at a time, in the order they are called, so the edits of one reply all land. Use one
55
+ * set of handlers for each conversation: two sets editing the same user's files at once can still overwrite each
56
+ * other's edits, as two editors of one file would.
57
+ */
58
+ export function geniffyMemoryHandlers(memory) {
59
+ const files = filesOf(memory);
60
+ async function read(path) {
61
+ if (path === ROOT)
62
+ return null;
63
+ try {
64
+ return await files.get(path);
65
+ }
66
+ catch (e) {
67
+ if (e instanceof NotFoundError)
68
+ return null;
69
+ throw e;
70
+ }
71
+ }
72
+ async function under(path) {
73
+ const found = [];
74
+ let cursor = 0;
75
+ for (let page = 0; page < (holdsFiles(path) ? PAGES : 0); page++) {
76
+ const listed = await files.list({ prefix: `${path}/`, limit: PAGE, cursor });
77
+ found.push(...listed.files);
78
+ if (listed.next === null || listed.next === undefined)
79
+ break;
80
+ cursor = listed.next;
81
+ }
82
+ return found;
83
+ }
84
+ // A file at path, or a directory: files under it.
85
+ async function exists(path) {
86
+ if (path === ROOT || (await read(path)) !== null)
87
+ return true;
88
+ return holdsFiles(path) && (await files.list({ prefix: `${path}/`, limit: 1 })).files.length > 0;
89
+ }
90
+ const put = (path, text) => files.put(path, text, { labels: { ...LABELS } });
91
+ async function view(c) {
92
+ const path = memoryPath(c?.path);
93
+ const found = await read(path);
94
+ if (found)
95
+ return showFile(path, found.text, c.view_range);
96
+ const held = await under(path);
97
+ if (!held.length && path !== ROOT)
98
+ throw new ToolError(`The path ${path} does not exist. Please provide a valid path.`);
99
+ return showDirectory(path, held);
100
+ }
101
+ async function create(c) {
102
+ const path = memoryPath(c?.path);
103
+ if (path === ROOT) {
104
+ throw new ToolError(`Error: ${ROOT} is the memory directory itself. Create files inside it, such as ${ROOT}/notes.md.`);
105
+ }
106
+ if (typeof c.file_text !== "string")
107
+ throw new ToolError("Error: create needs file_text, the whole text of the file.");
108
+ await put(path, c.file_text);
109
+ return `File created successfully at: ${path}`;
110
+ }
111
+ async function strReplace(c) {
112
+ const path = memoryPath(c?.path);
113
+ const found = await read(path);
114
+ if (!found)
115
+ throw new ToolError(`Error: The path ${path} does not exist. Please provide a valid path.`);
116
+ const [text, said] = replaced(path, found.text, c.old_str, c.new_str);
117
+ await put(path, text);
118
+ return said;
119
+ }
120
+ async function insert(c) {
121
+ const path = memoryPath(c?.path);
122
+ const found = await read(path);
123
+ if (!found)
124
+ throw noFile(path);
125
+ await put(path, inserted(found.text, c.insert_line, c.insert_text));
126
+ return `The file ${path} has been edited.`;
127
+ }
128
+ async function remove(c) {
129
+ const path = memoryPath(c?.path);
130
+ if (path === ROOT)
131
+ throw new ToolError(`Error: Cannot delete the ${ROOT} directory itself`);
132
+ let found = true;
133
+ try {
134
+ await files.delete(path);
135
+ }
136
+ catch (e) {
137
+ if (!(e instanceof NotFoundError))
138
+ throw e;
139
+ found = false;
140
+ }
141
+ if (holdsFiles(path))
142
+ found = (await files.deletePrefix(`${path}/`)) > 0 || found; // a directory too: nothing is left at that path
143
+ if (!found)
144
+ throw noFile(path);
145
+ return `Successfully deleted ${path}`;
146
+ }
147
+ async function rename(c) {
148
+ const old = memoryPath(c?.old_path);
149
+ const to = memoryPath(c?.new_path);
150
+ if (old === ROOT)
151
+ throw new ToolError(`Error: Cannot rename the ${ROOT} directory itself`);
152
+ if (to.startsWith(`${old}/`))
153
+ throw new ToolError(`Error: Cannot rename ${old} to ${to}, a path inside it`);
154
+ if (await exists(to))
155
+ throw taken(to);
156
+ try {
157
+ await files.move(old, to); // the text and what was learned go with it; nothing is learned again
158
+ }
159
+ catch (e) {
160
+ if (e instanceof NotFoundError)
161
+ throw noFile(old);
162
+ if (e instanceof BadRequestError && e.status === 409)
163
+ throw taken(to); // taken meanwhile
164
+ throw e;
165
+ }
166
+ return `Successfully renamed ${old} to ${to}`;
167
+ }
168
+ // One command at a time, in the order they came. The tool runner runs every tool call of a reply at once
169
+ // (Promise.all), and an edit is a read and then a write: two edits to one file side by side would both read the
170
+ // old text, the second write would drop the first edit, and both would tell Claude it was done. A command that
171
+ // fails does not hold up the next.
172
+ let queue = Promise.resolve();
173
+ function inTurn(work) {
174
+ const done = queue.then(work);
175
+ queue = done.catch(() => undefined);
176
+ return done;
177
+ }
178
+ // betaMemoryTool looks a handler up by the command's name, so the object has no prototype: nothing but these six
179
+ // answers to a name Claude sends.
180
+ return Object.assign(Object.create(null), {
181
+ view: (c) => inTurn(() => refusing(() => view(c))),
182
+ create: (c) => inTurn(() => refusing(() => create(c))),
183
+ str_replace: (c) => inTurn(() => refusing(() => strReplace(c))),
184
+ insert: (c) => inTurn(() => refusing(() => insert(c))),
185
+ delete: (c) => inTurn(() => refusing(() => remove(c))),
186
+ rename: (c) => inTurn(() => refusing(() => rename(c))),
187
+ });
188
+ }
189
+ /** Delete every file under /memories, and what only they taught: for your app to call, such as when a user resets
190
+ * their assistant. It is not one of the tool's commands, so Claude cannot call it. */
191
+ export async function clearAllMemory(memory) {
192
+ const files = filesOf(memory);
193
+ await refusing(() => files.deletePrefix(`${ROOT}/`));
194
+ return "All memory cleared";
195
+ }
196
+ // A request Geniffy refused as sent (a path or a text too long, say) goes back to Claude in Geniffy's words.
197
+ async function refusing(work) {
198
+ try {
199
+ return await work();
200
+ }
201
+ catch (e) {
202
+ if (e instanceof BadRequestError)
203
+ throw new ToolError(`Error: ${e.message}`);
204
+ throw e;
205
+ }
206
+ }
207
+ const noFile = (path) => new ToolError(`Error: The path ${path} does not exist`);
208
+ const taken = (path) => new ToolError(`Error: The destination ${path} already exists`);
209
+ // ── paths ─────────────────────────────────────────────────────────────────────
210
+ const outside = (path) => new ToolError(`Error: The path ${path} is outside /memories. Use a path under it, such as /memories/notes.md.`);
211
+ // The path as Geniffy keeps it: /memories or a path under it, with doubled and trailing slashes dropped. Anything that
212
+ // could lead out of /memories is refused, typed plainly or URL-encoded, however often.
213
+ function memoryPath(path) {
214
+ if (typeof path !== "string" || !path.startsWith("/"))
215
+ throw outside(path);
216
+ for (let form = path;;) {
217
+ if (form.includes("\\") || CONTROL.test(form) || form.split("/").some((part) => part === "." || part === "..")) {
218
+ throw new ToolError(`Error: The path ${path} is not allowed: a memory path has no '.' or '..' parts, ` +
219
+ "backslashes or control characters. Use a plain path such as /memories/notes.md.");
220
+ }
221
+ const decoded = unquote(form); // %2e%2e, and %252e%252e encoded again; each decoding is shorter
222
+ if (decoded === form)
223
+ break;
224
+ form = decoded;
225
+ }
226
+ const clean = `/${path.split("/").filter(Boolean).join("/")}`;
227
+ if (clean !== ROOT && !clean.startsWith(`${ROOT}/`))
228
+ throw outside(path);
229
+ return clean;
230
+ }
231
+ // %XX escapes decoded as UTF-8, a byte that is not one left as U+FFFD, and anything else kept: Python's unquote, so a
232
+ // path is refused or kept here exactly as geniffy.claude does it.
233
+ function unquote(text) {
234
+ if (!text.includes("%"))
235
+ return text;
236
+ return text.replace(/[\u0000-\u007f]+/g, (ascii) => {
237
+ if (!ascii.includes("%"))
238
+ return ascii;
239
+ const bytes = [];
240
+ for (let i = 0; i < ascii.length; i++) {
241
+ const hex = ascii.slice(i + 1, i + 3);
242
+ if (ascii[i] === "%" && /^[0-9a-fA-F]{2}$/.test(hex)) {
243
+ bytes.push(parseInt(hex, 16));
244
+ i += 2;
245
+ }
246
+ else {
247
+ bytes.push(ascii.charCodeAt(i));
248
+ }
249
+ }
250
+ return new TextDecoder().decode(new Uint8Array(bytes));
251
+ });
252
+ }
253
+ // Whether any file can be under path: one under it is longer by "/" and a name, at least two characters.
254
+ const holdsFiles = (path) => [...path].length + 2 <= MAX_PATH;
255
+ // ── what each command says ────────────────────────────────────────────────────
256
+ // A size as the memory tool shows one: 0B, 512B, 1.5K, 2M. One decimal rounds a tie to even (1.25K is 1.2K), as
257
+ // Python's format does.
258
+ function size(chars) {
259
+ if (!(chars > 0))
260
+ return "0B";
261
+ let unit = 0;
262
+ while (unit < 3 && chars >= 1024 ** (unit + 1))
263
+ unit++;
264
+ const n = chars / 1024 ** unit;
265
+ if (Number.isInteger(n))
266
+ return `${n}${"BKMG"[unit]}`;
267
+ const tenths = n * 10; // exact: a whole number of characters over a power of 2
268
+ let rounded = Math.round(tenths);
269
+ if (tenths - Math.floor(tenths) === 0.5 && rounded % 2)
270
+ rounded--;
271
+ return `${(rounded / 10).toFixed(1)}${"BKMG"[unit]}`;
272
+ }
273
+ // A text's lines, split at each newline. The newline that ends the last line starts no new one, so view and insert
274
+ // count lines the same way.
275
+ function linesOf(text) {
276
+ const lines = text.split("\n");
277
+ if (lines[lines.length - 1] === "")
278
+ lines.pop();
279
+ return lines;
280
+ }
281
+ const numbered = (n, line) => `${String(n).padStart(6, " ")}\t${line}`;
282
+ const hidden = (name) => name.startsWith(".") || name === "node_modules";
283
+ // Names first (each in turn, a shorter list before a longer one that starts the same), then a file before a
284
+ // directory: how Python sorts the (names, is a directory) pairs geniffy.claude lists.
285
+ function byPath(a, b) {
286
+ for (let i = 0; i < Math.min(a.names.length, b.names.length); i++) {
287
+ if (a.names[i] !== b.names[i])
288
+ return byCodePoint(a.names[i], b.names[i]);
289
+ }
290
+ return a.names.length - b.names.length || Number(a.directory) - Number(b.directory);
291
+ }
292
+ // Two names in code point order, as Python compares them and Geniffy lists paths. JavaScript's < compares UTF-16
293
+ // units, which puts a name with an emoji (or anything else past U+FFFF) before one with a character from U+E000 to
294
+ // U+FFFF. Up to the first unit that differs the two are the same, so the code points there decide; inside a
295
+ // surrogate pair the first halves match, and the second halves are in code point order too.
296
+ function byCodePoint(a, b) {
297
+ let at = 0;
298
+ while (at < a.length && at < b.length && a[at] === b[at])
299
+ at++;
300
+ if (at === a.length || at === b.length)
301
+ return a.length - b.length;
302
+ return (a.codePointAt(at) ?? 0) - (b.codePointAt(at) ?? 0);
303
+ }
304
+ // A directory as view shows one: its own size and path, then everything in it two levels deep, by name, directories
305
+ // ending in "/", hidden items and node_modules left out. A directory's size is all it holds.
306
+ function showDirectory(path, held) {
307
+ const inside = `${path}/`;
308
+ let total = 0;
309
+ const listed = new Map();
310
+ for (const f of held) {
311
+ if (!f.path.startsWith(inside))
312
+ continue;
313
+ total += f.size;
314
+ const names = f.path.slice(inside.length).split("/");
315
+ for (let depth = 0; depth < Math.min(2, names.length); depth++) {
316
+ if (hidden(names[depth]))
317
+ break;
318
+ const entry = { names: names.slice(0, depth + 1), directory: depth + 1 < names.length, size: 0 };
319
+ const key = JSON.stringify([entry.names, entry.directory]);
320
+ let known = listed.get(key);
321
+ if (!known)
322
+ listed.set(key, (known = entry));
323
+ known.size += f.size;
324
+ }
325
+ }
326
+ return [
327
+ `Here're the files and directories up to 2 levels deep in ${path}, excluding hidden items and node_modules:`,
328
+ `${size(total)}\t${path}`,
329
+ ...[...listed.values()].sort(byPath).map((e) => `${size(e.size)}\t${inside}${e.names.join("/")}${e.directory ? "/" : ""}`),
330
+ ].join("\n");
331
+ }
332
+ // A file as view shows one: each line numbered from 1, or only the lines view_range names ([start, -1] for the rest
333
+ // of the file).
334
+ function showFile(path, text, range) {
335
+ let lines = linesOf(text);
336
+ if (lines.length > MAX_LINES)
337
+ throw new ToolError(`File ${path} exceeds maximum line limit of 999,999 lines.`);
338
+ let first = 1;
339
+ if (Array.isArray(range) && range.length === 2) {
340
+ if (!range.every((n) => Number.isInteger(n))) {
341
+ throw new ToolError("Error: view_range is [start_line, end_line], such as [1, 20], or [start_line, -1] for the rest of the file.");
342
+ }
343
+ const [start, end] = range;
344
+ first = Math.max(1, start);
345
+ lines = lines.slice(first - 1, end === -1 ? lines.length : end);
346
+ }
347
+ return [`Here's the content of ${path} with line numbers:`, ...lines.map((line, i) => numbered(first + i, line))].join("\n");
348
+ }
349
+ // str_replace on a file's text: the text after it, and what to tell Claude. new_str left out deletes old_str.
350
+ function replaced(path, text, old, replacement) {
351
+ if (typeof old !== "string" || !old) {
352
+ throw new ToolError("Error: old_str is missing or empty. Give the exact text to replace, as it appears in the file.");
353
+ }
354
+ let count = 0;
355
+ for (let at = text.indexOf(old); at !== -1; at = text.indexOf(old, at + old.length))
356
+ count++;
357
+ if (count === 0)
358
+ throw new ToolError(`No replacement was performed, old_str \`${old}\` did not appear verbatim in ${path}.`);
359
+ if (count > 1) {
360
+ const starts = [];
361
+ for (let at = text.indexOf(old); at !== -1; at = text.indexOf(old, at + 1))
362
+ starts.push(at);
363
+ throw new ToolError(`No replacement was performed. Multiple occurrences of old_str \`${old}\` in lines: ` +
364
+ `${lineNumbers(text, starts).join(", ")}. Please ensure it is unique`);
365
+ }
366
+ const at = text.indexOf(old);
367
+ // spliced in, not String.replace, which would read $& and $1 in new_str as patterns
368
+ const edited = text.slice(0, at) + (typeof replacement === "string" ? replacement : "") + text.slice(at + old.length);
369
+ const changed = lineNumbers(text, [at])[0] - 1;
370
+ const lines = linesOf(edited);
371
+ const shown = [];
372
+ for (let n = Math.max(0, changed - 2); n < Math.min(lines.length, changed + 3); n++)
373
+ shown.push(numbered(n + 1, lines[n]));
374
+ return [edited, ["The memory file has been edited. Here is the snippet showing the change (with line numbers):", ...shown].join("\n")];
375
+ }
376
+ // insert on a file's text: insert_text as lines of its own after line `line` (0: before the first).
377
+ function inserted(text, line, insertText) {
378
+ const lines = linesOf(text);
379
+ if (typeof line !== "number" || !Number.isInteger(line) || line < 0 || line > lines.length) {
380
+ throw new ToolError(`Error: Invalid \`insert_line\` parameter: ${line}. It should be within the range of lines of ` +
381
+ `the file: [0, ${lines.length}]`);
382
+ }
383
+ if (typeof insertText !== "string")
384
+ throw new ToolError("Error: insert needs insert_text, the text to insert.");
385
+ lines.splice(line, 0, insertText.endsWith("\n") ? insertText.slice(0, -1) : insertText);
386
+ const edited = lines.join("\n");
387
+ return edited.endsWith("\n") ? edited : `${edited}\n`;
388
+ }
389
+ // The 1-indexed line each of these offsets is on; the offsets go up.
390
+ function lineNumbers(text, offsets) {
391
+ let line = 1;
392
+ let from = 0;
393
+ return offsets.map((offset) => {
394
+ for (let nl = text.indexOf("\n", from); nl !== -1 && nl < offset; nl = text.indexOf("\n", nl + 1))
395
+ line++;
396
+ from = offset;
397
+ return line;
398
+ });
399
+ }
package/dist/index.d.ts CHANGED
@@ -7,10 +7,10 @@
7
7
  * const { answer } = await g.ask("Who signs the Lumen renewal?");
8
8
  *
9
9
  * No dependencies: the platform's fetch, FormData and Blob (Node 18+, Deno, Bun, edge runtimes).
10
- * Retries: reads and deletes are retried on network errors, 408, 429 and 5xx; adding is retried only on
11
- * 429, so a retry never saves a note twice.
10
+ * Retries: reads, deletes and files.put (the same text twice is the same file) are retried on network errors,
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.2.0";
13
+ export declare const VERSION = "0.4.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 {
@@ -44,11 +44,38 @@ export interface MemoryDetail {
44
44
  memory: Memory;
45
45
  history: Memory[];
46
46
  }
47
+ /** This month's use, for the whole account, against the plan (usage()). Saving, briefings and search are free and
48
+ * never counted. */
49
+ export interface Usage {
50
+ /** free, pro or max: the same plans for everyone, the API in every one */
51
+ plan: string;
52
+ /** on the 14 days of Pro every account gets once */
53
+ trial: boolean;
54
+ period_start: string;
55
+ /** when it resets */
56
+ period_end: string;
57
+ /** tokens learned this month from everything saved, every way in, your app's users included */
58
+ learned_tokens: number;
59
+ /** the tokens the plan learns in a month */
60
+ included_tokens: number;
61
+ /** saved and searchable, waiting to be learned next month (or at once with extra learning on) */
62
+ waiting_tokens: number;
63
+ /** written answers and context blocks */
64
+ answers: number;
65
+ included_answers: number;
66
+ /** extra learning: past the plan, learned and answered at once, $15 per million tokens, $15 per 1,000 answers */
67
+ extra_on: boolean;
68
+ extra_cap_usd: number;
69
+ extra_used_usd: number;
70
+ /** learning against the plan: near at 80%; over: new saves wait; extra: extra learning carries on */
71
+ state: "ok" | "near" | "over" | "extra" | "paused";
72
+ }
47
73
  export interface Source {
48
74
  id: string;
49
75
  kind: "note" | "file" | "link";
50
76
  title: string;
51
- status: "reading" | "learned" | "failed";
77
+ /** waiting: saved past this month's use, kept, and learned once there is room */
78
+ status: "reading" | "learned" | "failed" | "waiting";
52
79
  /** why it failed, in plain words */
53
80
  error?: string | null;
54
81
  facts?: number | null;
@@ -136,6 +163,13 @@ export declare class UnreadableError extends BadRequestError {
136
163
  }
137
164
  export declare class RateLimitError extends GeniffyError {
138
165
  }
166
+ /**
167
+ * This month's use is up (402, code allowance_used): past the plan, what waits to be learned has reached its fair-use
168
+ * limit (ten months of the plan's learning). Search and recall keep working; saving resumes when the month resets
169
+ * (usage() says when), at once with extra learning on, or on a bigger plan. Not retried.
170
+ */
171
+ export declare class UsageLimitError extends GeniffyError {
172
+ }
139
173
  export declare class InternalServerError extends GeniffyError {
140
174
  }
141
175
  type Body = {
@@ -147,6 +181,8 @@ export declare class Geniffy {
147
181
  #private;
148
182
  readonly memories: Memories;
149
183
  readonly sources: Sources;
184
+ /** Files kept with their exact text, such as the ones Claude's memory tool writes (see `geniffy/claude`) */
185
+ readonly files: Files;
150
186
  /** Keys limited to one of your users, on a client bound to them: client.space(id).keys */
151
187
  readonly keys: Keys;
152
188
  /** The sections profiles are grouped into: every user's on the plain client, one user's on client.space(id) */
@@ -171,7 +207,7 @@ export declare class Geniffy {
171
207
  */
172
208
  space(space: string | number): Geniffy;
173
209
  /** @internal */
174
- request<T>(method: "GET" | "POST" | "DELETE" | "PATCH", path: string, body?: Body): Promise<T>;
210
+ request<T>(method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", path: string, body?: Body): Promise<T>;
175
211
  /** An answer from your memory only. `answer` is null when nothing you added supports one. With labels, only
176
212
  * from what the sources carrying them said. */
177
213
  ask(question: string, opts?: {
@@ -215,10 +251,56 @@ export declare class Geniffy {
215
251
  limit?: number;
216
252
  labels?: LabelFilter;
217
253
  }): Promise<Brief>;
254
+ /**
255
+ * What this moment needs, written out for YOUR prompt within `budgetChars`: where the project stands (goal,
256
+ * focus, open items, decisions, next steps), what is due or was promised, the rules and lessons that apply,
257
+ * what happened (the latest and the most related to `cue` first), then the memories, each dated. Open a session
258
+ * with it, and call it again when the task changes:
259
+ *
260
+ * const system = `${await mem.briefing({ project: "checkout", cue: userMessage })}\n\n${instructions}`;
261
+ *
262
+ * `project` is the label your sources carry (a project, context, thread or repo label); leave it out for every
263
+ * project. Read, not written by a model, so it is fast enough for every turn.
264
+ */
265
+ briefing(opts?: {
266
+ project?: string;
267
+ cue?: string;
268
+ budgetChars?: number;
269
+ }): Promise<string>;
270
+ /** The same, with its parts: now, due, lessons, episodes and memories, each with its source. */
271
+ briefingFull(opts?: {
272
+ project?: string;
273
+ cue?: string;
274
+ budgetChars?: number;
275
+ }): Promise<Briefing>;
276
+ /** Where things stand, per project: goal, focus, what is open (and since when), decisions with their reasons,
277
+ * next steps, blockers and what was finished. */
278
+ now(project?: string): Promise<State[]>;
279
+ /** What happened, as stories, newest first: what happened, how it ended, what it led to, its source. */
280
+ episodes(opts?: {
281
+ project?: string;
282
+ limit?: number;
283
+ }): Promise<Episode[]>;
284
+ /** Rules, how-tos and lessons, strongest first, each with when it applies and why. */
285
+ lessons(opts?: {
286
+ project?: string;
287
+ limit?: number;
288
+ }): Promise<Lesson[]>;
289
+ /** Promises and plans, yours and those made to you, with their triggers: open (the default), done or dropped. */
290
+ intentions(opts?: {
291
+ status?: "open" | "done" | "dropped";
292
+ limit?: number;
293
+ }): Promise<Intention[]>;
294
+ /** How well the memory answers about its own work: each night it writes questions from what it read, answers them
295
+ * and marks the answers. `health` is the share right (0 to 1), with the questions; null before its first night. */
296
+ memoryHealth(): Promise<MemoryHealth>;
297
+ /** Mark a promise or plan done, dropped, or open again. */
298
+ setIntention(id: number, status?: "done" | "dropped" | "open"): Promise<Intention>;
218
299
  /** What the memory holds and what connects to what. Every line has a memory behind it. */
219
300
  graph(): Promise<Graph>;
220
301
  /** 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. */
302
+ * came from, every source, and every file by its path (files.get(path) reads each one's text). On
303
+ * client.space(id), for a user who asks what you hold about them. */
222
304
  export(): Promise<Export>;
223
305
  /** Whose key this is, and which space this client is reading. */
224
306
  me(): Promise<{
@@ -226,6 +308,22 @@ export declare class Geniffy {
226
308
  memory: string;
227
309
  space: string | null;
228
310
  }>;
311
+ /**
312
+ * This month's use for the whole account: what it comes to in dollars ($4 per million tokens learned, $6 per
313
+ * 1,000 answers), what the plan includes, the most the month can come to, and when it resets. Search and recall
314
+ * are free and not counted.
315
+ */
316
+ usage(): Promise<Usage>;
317
+ /**
318
+ * An agent's or a chat's session, saved as it goes into one memory: hand save() the whole conversation after each
319
+ * turn, and only the messages it has not sent yet go to Geniffy.
320
+ *
321
+ * const run = mem.session("run-42", { title: "Refund agent" });
322
+ * await run.save(messages); // after every turn
323
+ */
324
+ session(id: string, opts?: {
325
+ title?: string;
326
+ } & WithLabels): Session;
229
327
  /** Which of your users have memory, busiest first. */
230
328
  spaces(): Promise<SpaceRow[]>;
231
329
  /**
@@ -277,6 +375,105 @@ export interface Export {
277
375
  quote?: string | null;
278
376
  })[];
279
377
  sources: Source[];
378
+ /** every file kept, by path and without its text, which files.get(path) returns exactly as written (left out by
379
+ * an API from before files) */
380
+ files?: FileEntry[];
381
+ }
382
+ /** Where one project stands. */
383
+ export interface State {
384
+ project: string | null;
385
+ goal: string | null;
386
+ focus: string | null;
387
+ open: Array<{
388
+ text: string;
389
+ since: string | null;
390
+ }>;
391
+ decisions: Array<{
392
+ what: string;
393
+ why: string | null;
394
+ when: string | null;
395
+ }>;
396
+ next_steps: string[];
397
+ blockers: string[];
398
+ done: Array<{
399
+ text: string;
400
+ when: string | null;
401
+ }>;
402
+ updated_at: string | null;
403
+ }
404
+ /** Something that happened, as a story. */
405
+ export interface Episode {
406
+ id: number;
407
+ project: string | null;
408
+ title: string | null;
409
+ what_happened: string | null;
410
+ /** how it ended */
411
+ outcome: string | null;
412
+ led_to: string | null;
413
+ people: string[];
414
+ decisions: Array<{
415
+ what: string;
416
+ why: string | null;
417
+ }>;
418
+ /** endings a later conversation corrected, oldest first: what it first seemed, and what showed otherwise */
419
+ revised?: Array<{
420
+ was: string | null;
421
+ why: string | null;
422
+ at: string | null;
423
+ }>;
424
+ started_at: string | null;
425
+ ended_at: string | null;
426
+ source: SourceRef;
427
+ }
428
+ /** A rule, how-to or lesson, with when it applies and why. */
429
+ export interface Lesson {
430
+ id: number;
431
+ project: string | null;
432
+ kind: "rule" | "how_to" | "lesson" | null;
433
+ statement: string | null;
434
+ applies_when: string | null;
435
+ why: string | null;
436
+ /** how many times it was learned again */
437
+ strength: number;
438
+ sources: SourceRef[];
439
+ }
440
+ /** A promise or plan, with its trigger. */
441
+ export interface Intention {
442
+ id: number;
443
+ project: string | null;
444
+ what: string | null;
445
+ owner: string | null;
446
+ trigger: "time" | "context" | "person" | "event" | null;
447
+ /** when it is due, for a time */
448
+ at: string | null;
449
+ /** its trigger in words: "when testing ends" */
450
+ when: string | null;
451
+ status: "open" | "done" | "dropped" | null;
452
+ sources: SourceRef[];
453
+ }
454
+ /** How well the memory answers about its own work, from the questions it asks itself each night. */
455
+ export interface MemoryHealth {
456
+ health: number | null;
457
+ tested_at: string | null;
458
+ asked: number;
459
+ score: number | null;
460
+ items: Array<{
461
+ question: string | null;
462
+ expected: string | null;
463
+ answer: string | null;
464
+ mark: "correct" | "partial" | "wrong" | null;
465
+ }>;
466
+ }
467
+ /** What a session opens with. */
468
+ export interface Briefing {
469
+ project: string | null;
470
+ /** Put this straight into your prompt. */
471
+ briefing: string;
472
+ now: State[];
473
+ due: Intention[];
474
+ lessons: Lesson[];
475
+ episodes: Episode[];
476
+ memories: Memory[];
280
477
  }
281
478
  export interface Graph {
282
479
  nodes: Array<{
@@ -303,13 +500,20 @@ export interface SpaceRow {
303
500
  }
304
501
  export interface ChatMessage {
305
502
  role: string;
306
- /** The words: a string, or the blocks or parts your framework holds (Anthropic, OpenAI). Only text is
307
- * kept; null is a turn that said nothing in words, such as one that only called a tool. */
503
+ /** The words: a string, or the blocks or parts your framework holds (Anthropic, OpenAI), tool calls and tool
504
+ * results included. Facts come only from what was said; a tool's call and output tell Geniffy what
505
+ * happened. */
308
506
  content?: string | unknown[] | null;
309
507
  /** Or the parts, as the Vercel AI SDK and Gemini hold a message. */
310
508
  parts?: unknown[];
311
509
  /** Who, when the role does not say: a tool name, a participant. */
312
510
  name?: string;
511
+ /** The tools an assistant called, as OpenAI and LangChain hold them. */
512
+ tool_calls?: unknown[];
513
+ /** For a tool result, the call it answers. */
514
+ tool_call_id?: string;
515
+ /** When it was said, ISO 8601, if your app keeps it. */
516
+ time?: string;
313
517
  }
314
518
  /** When a note or conversation from the past was said: a Date, or an ISO 8601 string (2026-03-04,
315
519
  * 2026-03-04T09:30:00Z). What it teaches is dated by it. Left out, now. */
@@ -318,7 +522,8 @@ export interface SaidAt {
318
522
  }
319
523
  /** Your own id for what you add: a ticket's, a document's, a conversation's. Sent again under the same id,
320
524
  * 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`. */
525
+ * taken back. Find or delete it by the same id with `sources.get({ externalId })` and `sources.delete`.
526
+ * An id that starts with "file:" is refused: those name the files kept with `files.put`. */
322
527
  export interface ExternalId {
323
528
  externalId?: string;
324
529
  }
@@ -340,7 +545,14 @@ export type AddInput = string | ({
340
545
  | ({
341
546
  messages: ChatMessage[];
342
547
  title?: string;
343
- } & SaidAt & ExternalId & WithLabels);
548
+ } & SaidAt & ExternalId & WithLabels)
549
+ /** The next turns of an agent's or a chat's session: each call adds its messages to one memory for the whole
550
+ * session, however long it gets, so send only what is new since the last call (session().save() works that out). */
551
+ | ({
552
+ messages: ChatMessage[];
553
+ session: string;
554
+ title?: string;
555
+ } & WithLabels);
344
556
  /** A source named by Geniffy's id, or by the external id you added it under. */
345
557
  export type SourceLookup = string | {
346
558
  externalId: string;
@@ -474,4 +686,80 @@ export declare class Sources {
474
686
  intervalMs?: number;
475
687
  }): Promise<Source>;
476
688
  }
689
+ /** A file kept in a memory, without its text. */
690
+ export interface FileEntry {
691
+ /** such as /memories/notes.md */
692
+ path: string;
693
+ /** how long its text is, in characters */
694
+ size: number;
695
+ updated_at: string;
696
+ }
697
+ /** A file and its text, exactly as it was put. */
698
+ export interface MemoryFile extends FileEntry {
699
+ text: string;
700
+ }
701
+ /** What files.put did. */
702
+ export interface FileInfo extends FileEntry {
703
+ /** true when no file had that path before */
704
+ created: boolean;
705
+ /** the source it is learned from, titled by its path */
706
+ source: SourceRef;
707
+ }
708
+ export interface FilePage {
709
+ files: FileEntry[];
710
+ total: number;
711
+ next: number | null;
712
+ }
713
+ /**
714
+ * Files kept exactly as they were written, each under a path such as /memories/notes.md: what an agent keeps for
715
+ * itself, like the notes Claude's memory tool writes (see `geniffy/claude`). Geniffy also learns from each file like
716
+ * a note titled by its path, so context() and ask() recall what it says, and deleting it takes back what only it
717
+ * taught.
718
+ *
719
+ * A path starts with "/" and has at most 255 characters, with no empty, "." or ".." parts and no backslash.
720
+ */
721
+ export declare class Files {
722
+ private readonly client;
723
+ constructor(client: Geniffy);
724
+ /** Create a file, or replace its text. The text is kept exactly as sent, whitespace and line endings included,
725
+ * and learned like a note; a replace learns only what changed. An empty file is kept too, with nothing learned
726
+ * from it. labels: as on memories.add. */
727
+ put(path: string, text: string, opts?: WithLabels): Promise<FileInfo>;
728
+ /** A file and its exact text (a NotFoundError when no file has that path). */
729
+ get(path: string): Promise<MemoryFile>;
730
+ /** The files whose paths start with `prefix`, by path, without their text ("/", the default, for all of them).
731
+ * Up to 200 a page; `next` is the cursor of the page after, null at the end. */
732
+ list(opts?: {
733
+ prefix?: string;
734
+ limit?: number;
735
+ cursor?: number;
736
+ }): Promise<FilePage>;
737
+ /** Delete a file, its text and what only it taught (a NotFoundError when no file has that path). */
738
+ delete(path: string): Promise<void>;
739
+ /** Delete every file whose path starts with `prefix` ("/memories/" for everything in that folder), with what
740
+ * only they taught. Resolves to how many. */
741
+ deletePrefix(prefix: string): Promise<number>;
742
+ /** Move a file, or, when `from` is a folder, every file in it, keeping the text and what was learned. A
743
+ * NotFoundError when there is nothing to move; a BadRequestError with code "conflict" when a destination is
744
+ * already taken, and then nothing moves. Resolves to how many files moved. */
745
+ move(from: string, to: string): Promise<number>;
746
+ }
747
+ /**
748
+ * An agent's or a chat's session, saved as it goes into one memory for the whole session. Hand save() the whole
749
+ * conversation after each turn: only the messages after the last one it sent go to Geniffy, at most 500 a call, so a
750
+ * session of any length is never sent twice. When that message is no longer there (the agent rewrote or compacted
751
+ * its history), what it holds now is saved again rather than lost. Made by client.session(id).
752
+ */
753
+ export declare class Session {
754
+ #private;
755
+ private readonly client;
756
+ readonly id: string;
757
+ readonly title?: string;
758
+ readonly labels?: Labels;
759
+ constructor(client: Geniffy, id: string, opts?: {
760
+ title?: string;
761
+ } & WithLabels);
762
+ /** Sends what is new; resolves to the session's source, or null when nothing was new. */
763
+ save(messages: ChatMessage[]): Promise<Source | null>;
764
+ }
477
765
  export default Geniffy;
package/dist/index.js CHANGED
@@ -7,10 +7,10 @@
7
7
  * const { answer } = await g.ask("Who signs the Lumen renewal?");
8
8
  *
9
9
  * No dependencies: the platform's fetch, FormData and Blob (Node 18+, Deno, Bun, edge runtimes).
10
- * Retries: reads and deletes are retried on network errors, 408, 429 and 5xx; adding is retried only on
11
- * 429, so a retry never saves a note twice.
10
+ * Retries: reads, deletes and files.put (the same text twice is the same file) are retried on network errors,
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.2.0";
13
+ export const VERSION = "0.4.0";
14
14
  export const DEFAULT_BASE_URL = "https://api.geniffy.com";
15
15
  /** A filter in a query string: label=name:value, once for each value. */
16
16
  function labelQuery(labels) {
@@ -70,6 +70,13 @@ export class UnreadableError extends BadRequestError {
70
70
  }
71
71
  export class RateLimitError extends GeniffyError {
72
72
  }
73
+ /**
74
+ * This month's use is up (402, code allowance_used): past the plan, what waits to be learned has reached its fair-use
75
+ * limit (ten months of the plan's learning). Search and recall keep working; saving resumes when the month resets
76
+ * (usage() says when), at once with extra learning on, or on a bigger plan. Not retried.
77
+ */
78
+ export class UsageLimitError extends GeniffyError {
79
+ }
73
80
  export class InternalServerError extends GeniffyError {
74
81
  }
75
82
  function errorFrom(status, body, requestId) {
@@ -84,6 +91,8 @@ function errorFrom(status, body, requestId) {
84
91
  return new UnreadableError(message, opts);
85
92
  if ([400, 409, 413, 422].includes(status))
86
93
  return new BadRequestError(message, opts);
94
+ if (status === 402)
95
+ return new UsageLimitError(message, opts);
87
96
  if (status === 429)
88
97
  return new RateLimitError(message, opts);
89
98
  if (status >= 500)
@@ -106,6 +115,8 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
106
115
  export class Geniffy {
107
116
  memories;
108
117
  sources;
118
+ /** Files kept with their exact text, such as the ones Claude's memory tool writes (see `geniffy/claude`) */
119
+ files;
109
120
  /** Keys limited to one of your users, on a client bound to them: client.space(id).keys */
110
121
  keys;
111
122
  /** The sections profiles are grouped into: every user's on the plain client, one user's on client.space(id) */
@@ -135,6 +146,7 @@ export class Geniffy {
135
146
  }
136
147
  this.memories = new Memories(this);
137
148
  this.sources = new Sources(this);
149
+ this.files = new Files(this);
138
150
  this.keys = new Keys(this);
139
151
  this.sections = new Sections(this);
140
152
  }
@@ -257,12 +269,60 @@ export class Geniffy {
257
269
  brief(subject, opts = {}) {
258
270
  return this.request("GET", "/v1/brief", { query: { subject, limit: opts.limit, label: labelQuery(opts.labels) } });
259
271
  }
272
+ // ── what a session opens with: where things stand, what happened, what was learned and promised
273
+ /**
274
+ * What this moment needs, written out for YOUR prompt within `budgetChars`: where the project stands (goal,
275
+ * focus, open items, decisions, next steps), what is due or was promised, the rules and lessons that apply,
276
+ * what happened (the latest and the most related to `cue` first), then the memories, each dated. Open a session
277
+ * with it, and call it again when the task changes:
278
+ *
279
+ * const system = `${await mem.briefing({ project: "checkout", cue: userMessage })}\n\n${instructions}`;
280
+ *
281
+ * `project` is the label your sources carry (a project, context, thread or repo label); leave it out for every
282
+ * project. Read, not written by a model, so it is fast enough for every turn.
283
+ */
284
+ async briefing(opts = {}) {
285
+ return (await this.briefingFull(opts)).briefing;
286
+ }
287
+ /** The same, with its parts: now, due, lessons, episodes and memories, each with its source. */
288
+ briefingFull(opts = {}) {
289
+ return this.request("POST", "/v1/briefing", {
290
+ json: { project: opts.project, cue: opts.cue ?? "", budget_chars: opts.budgetChars ?? 6000 },
291
+ });
292
+ }
293
+ /** Where things stand, per project: goal, focus, what is open (and since when), decisions with their reasons,
294
+ * next steps, blockers and what was finished. */
295
+ async now(project) {
296
+ return (await this.request("GET", "/v1/now", { query: { project } })).now;
297
+ }
298
+ /** What happened, as stories, newest first: what happened, how it ended, what it led to, its source. */
299
+ async episodes(opts = {}) {
300
+ return (await this.request("GET", "/v1/episodes", { query: { project: opts.project, limit: opts.limit ?? 20 } })).episodes;
301
+ }
302
+ /** Rules, how-tos and lessons, strongest first, each with when it applies and why. */
303
+ async lessons(opts = {}) {
304
+ return (await this.request("GET", "/v1/lessons", { query: { project: opts.project, limit: opts.limit ?? 50 } })).lessons;
305
+ }
306
+ /** Promises and plans, yours and those made to you, with their triggers: open (the default), done or dropped. */
307
+ async intentions(opts = {}) {
308
+ return (await this.request("GET", "/v1/intentions", { query: { status: opts.status ?? "open", limit: opts.limit ?? 50 } })).intentions;
309
+ }
310
+ /** How well the memory answers about its own work: each night it writes questions from what it read, answers them
311
+ * and marks the answers. `health` is the share right (0 to 1), with the questions; null before its first night. */
312
+ memoryHealth() {
313
+ return this.request("GET", "/v1/memory-health");
314
+ }
315
+ /** Mark a promise or plan done, dropped, or open again. */
316
+ async setIntention(id, status = "done") {
317
+ return (await this.request("POST", `/v1/intentions/${Number(id)}`, { json: { status } })).intention;
318
+ }
260
319
  /** What the memory holds and what connects to what. Every line has a memory behind it. */
261
320
  graph() {
262
321
  return this.request("GET", "/v1/graph");
263
322
  }
264
323
  /** 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. */
324
+ * came from, every source, and every file by its path (files.get(path) reads each one's text). On
325
+ * client.space(id), for a user who asks what you hold about them. */
266
326
  export() {
267
327
  return this.request("GET", "/v1/export");
268
328
  }
@@ -270,6 +330,24 @@ export class Geniffy {
270
330
  me() {
271
331
  return this.request("GET", "/v1/me");
272
332
  }
333
+ /**
334
+ * This month's use for the whole account: what it comes to in dollars ($4 per million tokens learned, $6 per
335
+ * 1,000 answers), what the plan includes, the most the month can come to, and when it resets. Search and recall
336
+ * are free and not counted.
337
+ */
338
+ usage() {
339
+ return this.request("GET", "/v1/usage");
340
+ }
341
+ /**
342
+ * An agent's or a chat's session, saved as it goes into one memory: hand save() the whole conversation after each
343
+ * turn, and only the messages it has not sent yet go to Geniffy.
344
+ *
345
+ * const run = mem.session("run-42", { title: "Refund agent" });
346
+ * await run.save(messages); // after every turn
347
+ */
348
+ session(id, opts = {}) {
349
+ return new Session(this, id, opts);
350
+ }
273
351
  /** Which of your users have memory, busiest first. */
274
352
  async spaces() {
275
353
  const out = await this.request("GET", "/v1/spaces");
@@ -287,6 +365,14 @@ export class Geniffy {
287
365
  function addBody(input) {
288
366
  const given = typeof input === "string" ? { text: input } : input;
289
367
  const { saidAt, externalId, ...rest } = given;
368
+ if (rest.session !== undefined) { // the API says the same: refused before anything is sent
369
+ if (!("messages" in rest))
370
+ throw new TypeError("session goes with messages: the turns of the session.");
371
+ if (externalId !== undefined)
372
+ throw new TypeError("Send session or externalId, not both: the session is the source's id.");
373
+ if (saidAt !== undefined)
374
+ throw new TypeError("saidAt does not go with session: each turn is dated as it arrives.");
375
+ }
290
376
  const body = { ...rest };
291
377
  if (saidAt !== undefined)
292
378
  body.said_at = saidAt instanceof Date ? saidAt.toISOString() : String(saidAt);
@@ -417,9 +503,9 @@ export class Sections {
417
503
  await this.client.request("DELETE", `/v1/profile/sections/${Math.trunc(id)}`);
418
504
  }
419
505
  }
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;
506
+ // Each call deletes up to 100 sources (or files) and says whether more are left; this many calls is the most one
507
+ // deleteLabelled() or files.deletePrefix() makes, so a filter that somehow keeps matching cannot loop for ever.
508
+ const DELETE_CALLS = 1000;
423
509
  export class Sources {
424
510
  client;
425
511
  constructor(client) {
@@ -443,7 +529,7 @@ export class Sources {
443
529
  if (opts.keep !== undefined)
444
530
  return this.deleteAllBut(labels, opts.keep);
445
531
  let total = 0;
446
- for (let i = 0; i < LABELLED_CALLS; i++) {
532
+ for (let i = 0; i < DELETE_CALLS; i++) {
447
533
  const out = await this.client.request("DELETE", "/v1/sources", {
448
534
  query: { label: labelQuery(labels) },
449
535
  });
@@ -517,4 +603,115 @@ export class Sources {
517
603
  }
518
604
  }
519
605
  }
606
+ /**
607
+ * Files kept exactly as they were written, each under a path such as /memories/notes.md: what an agent keeps for
608
+ * itself, like the notes Claude's memory tool writes (see `geniffy/claude`). Geniffy also learns from each file like
609
+ * a note titled by its path, so context() and ask() recall what it says, and deleting it takes back what only it
610
+ * taught.
611
+ *
612
+ * A path starts with "/" and has at most 255 characters, with no empty, "." or ".." parts and no backslash.
613
+ */
614
+ export class Files {
615
+ client;
616
+ constructor(client) {
617
+ this.client = client;
618
+ }
619
+ /** Create a file, or replace its text. The text is kept exactly as sent, whitespace and line endings included,
620
+ * and learned like a note; a replace learns only what changed. An empty file is kept too, with nothing learned
621
+ * from it. labels: as on memories.add. */
622
+ put(path, text, opts = {}) {
623
+ return this.client.request("PUT", "/v1/files", { json: { path, text, labels: opts.labels } });
624
+ }
625
+ /** A file and its exact text (a NotFoundError when no file has that path). */
626
+ get(path) {
627
+ return this.client.request("GET", "/v1/files", { query: { path } });
628
+ }
629
+ /** The files whose paths start with `prefix`, by path, without their text ("/", the default, for all of them).
630
+ * Up to 200 a page; `next` is the cursor of the page after, null at the end. */
631
+ list(opts = {}) {
632
+ return this.client.request("GET", "/v1/files", {
633
+ query: { prefix: opts.prefix ?? "/", limit: opts.limit ?? 100, cursor: opts.cursor ?? 0 },
634
+ });
635
+ }
636
+ /** Delete a file, its text and what only it taught (a NotFoundError when no file has that path). */
637
+ async delete(path) {
638
+ await this.client.request("DELETE", "/v1/files", { query: { path } });
639
+ }
640
+ /** Delete every file whose path starts with `prefix` ("/memories/" for everything in that folder), with what
641
+ * only they taught. Resolves to how many. */
642
+ async deletePrefix(prefix) {
643
+ let total = 0;
644
+ for (let i = 0; i < DELETE_CALLS; i++) {
645
+ const out = await this.client.request("DELETE", "/v1/files", { query: { prefix } });
646
+ total += out.deleted ?? 0;
647
+ if (!out.more)
648
+ break;
649
+ }
650
+ return total;
651
+ }
652
+ /** Move a file, or, when `from` is a folder, every file in it, keeping the text and what was learned. A
653
+ * NotFoundError when there is nothing to move; a BadRequestError with code "conflict" when a destination is
654
+ * already taken, and then nothing moves. Resolves to how many files moved. */
655
+ async move(from, to) {
656
+ const out = await this.client.request("POST", "/v1/files/move", { json: { from, to } });
657
+ return out.moved ?? 0;
658
+ }
659
+ }
660
+ // ── sessions saved as they go ─────────────────────────────────────────────────────────────────────────────
661
+ const SESSION_CALL = 500; // the most messages one call takes
662
+ // A message written out with its keys in order, so the same message reads the same however it was built.
663
+ function stable(value) {
664
+ if (Array.isArray(value))
665
+ return `[${value.map(stable).join(",")}]`;
666
+ if (value && typeof value === "object") {
667
+ const o = value;
668
+ return `{${Object.keys(o).sort().filter((k) => o[k] !== undefined).map((k) => `${JSON.stringify(k)}:${stable(o[k])}`).join(",")}}`;
669
+ }
670
+ return JSON.stringify(value) ?? "null";
671
+ }
672
+ /**
673
+ * An agent's or a chat's session, saved as it goes into one memory for the whole session. Hand save() the whole
674
+ * conversation after each turn: only the messages after the last one it sent go to Geniffy, at most 500 a call, so a
675
+ * session of any length is never sent twice. When that message is no longer there (the agent rewrote or compacted
676
+ * its history), what it holds now is saved again rather than lost. Made by client.session(id).
677
+ */
678
+ export class Session {
679
+ client;
680
+ #last = null;
681
+ id;
682
+ title;
683
+ labels;
684
+ constructor(client, id, opts = {}) {
685
+ this.client = client;
686
+ this.id = String(id);
687
+ this.title = opts.title;
688
+ this.labels = opts.labels;
689
+ }
690
+ /** Sends what is new; resolves to the session's source, or null when nothing was new. */
691
+ async save(messages) {
692
+ const all = [...messages];
693
+ let from = 0;
694
+ if (this.#last !== null) {
695
+ for (let i = all.length - 1; i >= 0; i--) {
696
+ if (stable(all[i]) === this.#last) {
697
+ from = i + 1;
698
+ break;
699
+ }
700
+ }
701
+ }
702
+ const fresh = all.slice(from);
703
+ let source = null;
704
+ for (let i = 0; i < fresh.length; i += SESSION_CALL) {
705
+ const part = fresh.slice(i, i + SESSION_CALL);
706
+ const input = { messages: part, session: this.id };
707
+ if (this.title)
708
+ input.title = this.title;
709
+ if (this.labels)
710
+ input.labels = this.labels;
711
+ source = await this.client.memories.add(input);
712
+ this.#last = stable(part[part.length - 1]);
713
+ }
714
+ return source;
715
+ }
716
+ }
520
717
  export default Geniffy;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "geniffy",
3
- "version": "0.2.0",
3
+ "version": "0.4.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",
@@ -9,6 +9,10 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
+ },
13
+ "./claude": {
14
+ "types": "./dist/claude.d.ts",
15
+ "import": "./dist/claude.js"
12
16
  }
13
17
  },
14
18
  "files": ["dist", "README.md"],
@@ -16,9 +20,9 @@
16
20
  "engines": { "node": ">=18" },
17
21
  "scripts": {
18
22
  "build": "tsc -p tsconfig.json",
19
- "test": "npm run build && node --test test/client.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"
20
24
  },
21
- "keywords": ["memory", "ai", "agents", "llm", "rag", "geniffy"],
25
+ "keywords": ["memory", "ai", "agents", "llm", "rag", "geniffy", "claude", "memory-tool"],
22
26
  "homepage": "https://docs.geniffy.com/sdks/typescript",
23
27
  "repository": {
24
28
  "type": "git",
@@ -29,7 +33,14 @@
29
33
  },
30
34
  "author": "Geniffy <ops@geniffy.com>",
31
35
  "license": "MIT",
36
+ "peerDependencies": {
37
+ "@anthropic-ai/sdk": ">=0.72.0"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@anthropic-ai/sdk": { "optional": true }
41
+ },
32
42
  "devDependencies": {
43
+ "@anthropic-ai/sdk": "^0.131.0",
33
44
  "typescript": "^5.6.0"
34
45
  }
35
46
  }