geniffy 0.2.0 → 0.3.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 +41 -3
- package/dist/claude.d.ts +95 -0
- package/dist/claude.js +399 -0
- package/dist/index.d.ts +71 -6
- package/dist/index.js +66 -8
- package/package.json +14 -3
package/README.md
CHANGED
|
@@ -114,13 +114,51 @@ await mem.sources.list();
|
|
|
114
114
|
await mem.sources.delete(source.id); // a source, and what only it taught
|
|
115
115
|
```
|
|
116
116
|
|
|
117
|
+
## Files, and Claude's memory tool
|
|
118
|
+
|
|
119
|
+
Keep files by path with their text exactly as written, whitespace and line endings included. Geniffy also learns
|
|
120
|
+
from each one like a note titled by its path, so `context()` and `ask()` recall what it says: a replace learns only
|
|
121
|
+
what changed, and deleting a file takes back what only it taught.
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
await mem.files.put("/notes/plan.md", "# Plan\n- Pilots run for 6 weeks.\n"); // creates or replaces it
|
|
125
|
+
const { text } = await mem.files.get("/notes/plan.md"); // exactly as it was put
|
|
126
|
+
await mem.files.list({ prefix: "/notes/" }); // by path, without the text
|
|
127
|
+
await mem.files.move("/notes", "/archive/notes"); // a file, or a folder and all in it
|
|
128
|
+
await mem.files.delete("/archive/notes/plan.md");
|
|
129
|
+
await mem.files.deletePrefix("/archive/"); // everything in that folder
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
That makes Geniffy the storage for Claude's memory tool, which keeps Claude's own notes as files under `/memories`.
|
|
133
|
+
With `geniffy/claude` those files live in that user's memory: each comes back to Claude exactly as it wrote it, and
|
|
134
|
+
what Claude wrote is recalled by `context()` and `ask()` like anything else the user told you.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
138
|
+
import { betaMemoryTool } from "@anthropic-ai/sdk/helpers/beta/memory";
|
|
139
|
+
import { geniffyMemoryHandlers } from "geniffy/claude";
|
|
140
|
+
|
|
141
|
+
const message = await new Anthropic().beta.messages.toolRunner({
|
|
142
|
+
model: "claude-opus-5-5",
|
|
143
|
+
max_tokens: 16000,
|
|
144
|
+
tools: [betaMemoryTool(geniffyMemoryHandlers(client.space(`user_${user.id}`)))],
|
|
145
|
+
messages: [{ role: "user", content: "Remember that I prefer email follow-ups." }],
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Every command answers with the sentences Anthropic's memory tool documentation gives, a path outside `/memories` is
|
|
150
|
+
refused, and every file carries the labels `{ channel: "claude-memory" }`: `{ labels: LABELS }` keeps a read to what
|
|
151
|
+
Claude wrote, and `clearAllMemory(mem)` deletes it all (both from `geniffy/claude`). The tool runner runs the tool
|
|
152
|
+
calls of one reply at the same time, so the handlers take them one after another: two edits to one file both land.
|
|
153
|
+
`geniffy/claude` needs `@anthropic-ai/sdk` 0.72 or later, an optional peer dependency; `geniffy` itself still has none.
|
|
154
|
+
|
|
117
155
|
## Errors, retries and request ids
|
|
118
156
|
|
|
119
157
|
Every error carries the API's own sentence: `AuthenticationError` (a wrong or revoked key),
|
|
120
158
|
`NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `InternalServerError`,
|
|
121
|
-
`APIConnectionError`; all extend `GeniffyError`. Reads
|
|
122
|
-
5xx; adding is retried only on 429, so a retry never
|
|
123
|
-
to the constructor to change that.
|
|
159
|
+
`APIConnectionError`; all extend `GeniffyError`. Reads, and putting a file (the same text twice is the same
|
|
160
|
+
file), are retried twice on network errors, 408, 429 and 5xx; adding is retried only on 429, so a retry never
|
|
161
|
+
saves a note twice. Pass `{ maxRetries, timeout }` to the constructor to change that.
|
|
124
162
|
|
|
125
163
|
Every response carries an `X-Request-ID`, and every error carries it as `error.requestId`. Paste it into
|
|
126
164
|
**Requests** in the Geniffy app to see that exact call: what was asked, what came back, and how long it took.
|
package/dist/claude.d.ts
ADDED
|
@@ -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
|
|
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.
|
|
13
|
+
export declare const VERSION = "0.3.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 {
|
|
@@ -147,6 +147,8 @@ export declare class Geniffy {
|
|
|
147
147
|
#private;
|
|
148
148
|
readonly memories: Memories;
|
|
149
149
|
readonly sources: Sources;
|
|
150
|
+
/** Files kept with their exact text, such as the ones Claude's memory tool writes (see `geniffy/claude`) */
|
|
151
|
+
readonly files: Files;
|
|
150
152
|
/** Keys limited to one of your users, on a client bound to them: client.space(id).keys */
|
|
151
153
|
readonly keys: Keys;
|
|
152
154
|
/** The sections profiles are grouped into: every user's on the plain client, one user's on client.space(id) */
|
|
@@ -171,7 +173,7 @@ export declare class Geniffy {
|
|
|
171
173
|
*/
|
|
172
174
|
space(space: string | number): Geniffy;
|
|
173
175
|
/** @internal */
|
|
174
|
-
request<T>(method: "GET" | "POST" | "DELETE" | "PATCH", path: string, body?: Body): Promise<T>;
|
|
176
|
+
request<T>(method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH", path: string, body?: Body): Promise<T>;
|
|
175
177
|
/** An answer from your memory only. `answer` is null when nothing you added supports one. With labels, only
|
|
176
178
|
* from what the sources carrying them said. */
|
|
177
179
|
ask(question: string, opts?: {
|
|
@@ -218,7 +220,8 @@ export declare class Geniffy {
|
|
|
218
220
|
/** What the memory holds and what connects to what. Every line has a memory behind it. */
|
|
219
221
|
graph(): Promise<Graph>;
|
|
220
222
|
/** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
|
|
221
|
-
* came from,
|
|
223
|
+
* came from, every source, and every file by its path (files.get(path) reads each one's text). On
|
|
224
|
+
* client.space(id), for a user who asks what you hold about them. */
|
|
222
225
|
export(): Promise<Export>;
|
|
223
226
|
/** Whose key this is, and which space this client is reading. */
|
|
224
227
|
me(): Promise<{
|
|
@@ -277,6 +280,9 @@ export interface Export {
|
|
|
277
280
|
quote?: string | null;
|
|
278
281
|
})[];
|
|
279
282
|
sources: Source[];
|
|
283
|
+
/** every file kept, by path and without its text, which files.get(path) returns exactly as written (left out by
|
|
284
|
+
* an API from before files) */
|
|
285
|
+
files?: FileEntry[];
|
|
280
286
|
}
|
|
281
287
|
export interface Graph {
|
|
282
288
|
nodes: Array<{
|
|
@@ -318,7 +324,8 @@ export interface SaidAt {
|
|
|
318
324
|
}
|
|
319
325
|
/** Your own id for what you add: a ticket's, a document's, a conversation's. Sent again under the same id,
|
|
320
326
|
* 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`.
|
|
327
|
+
* taken back. Find or delete it by the same id with `sources.get({ externalId })` and `sources.delete`.
|
|
328
|
+
* An id that starts with "file:" is refused: those name the files kept with `files.put`. */
|
|
322
329
|
export interface ExternalId {
|
|
323
330
|
externalId?: string;
|
|
324
331
|
}
|
|
@@ -474,4 +481,62 @@ export declare class Sources {
|
|
|
474
481
|
intervalMs?: number;
|
|
475
482
|
}): Promise<Source>;
|
|
476
483
|
}
|
|
484
|
+
/** A file kept in a memory, without its text. */
|
|
485
|
+
export interface FileEntry {
|
|
486
|
+
/** such as /memories/notes.md */
|
|
487
|
+
path: string;
|
|
488
|
+
/** how long its text is, in characters */
|
|
489
|
+
size: number;
|
|
490
|
+
updated_at: string;
|
|
491
|
+
}
|
|
492
|
+
/** A file and its text, exactly as it was put. */
|
|
493
|
+
export interface MemoryFile extends FileEntry {
|
|
494
|
+
text: string;
|
|
495
|
+
}
|
|
496
|
+
/** What files.put did. */
|
|
497
|
+
export interface FileInfo extends FileEntry {
|
|
498
|
+
/** true when no file had that path before */
|
|
499
|
+
created: boolean;
|
|
500
|
+
/** the source it is learned from, titled by its path */
|
|
501
|
+
source: SourceRef;
|
|
502
|
+
}
|
|
503
|
+
export interface FilePage {
|
|
504
|
+
files: FileEntry[];
|
|
505
|
+
total: number;
|
|
506
|
+
next: number | null;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Files kept exactly as they were written, each under a path such as /memories/notes.md: what an agent keeps for
|
|
510
|
+
* itself, like the notes Claude's memory tool writes (see `geniffy/claude`). Geniffy also learns from each file like
|
|
511
|
+
* a note titled by its path, so context() and ask() recall what it says, and deleting it takes back what only it
|
|
512
|
+
* taught.
|
|
513
|
+
*
|
|
514
|
+
* A path starts with "/" and has at most 255 characters, with no empty, "." or ".." parts and no backslash.
|
|
515
|
+
*/
|
|
516
|
+
export declare class Files {
|
|
517
|
+
private readonly client;
|
|
518
|
+
constructor(client: Geniffy);
|
|
519
|
+
/** Create a file, or replace its text. The text is kept exactly as sent, whitespace and line endings included,
|
|
520
|
+
* and learned like a note; a replace learns only what changed. An empty file is kept too, with nothing learned
|
|
521
|
+
* from it. labels: as on memories.add. */
|
|
522
|
+
put(path: string, text: string, opts?: WithLabels): Promise<FileInfo>;
|
|
523
|
+
/** A file and its exact text (a NotFoundError when no file has that path). */
|
|
524
|
+
get(path: string): Promise<MemoryFile>;
|
|
525
|
+
/** The files whose paths start with `prefix`, by path, without their text ("/", the default, for all of them).
|
|
526
|
+
* Up to 200 a page; `next` is the cursor of the page after, null at the end. */
|
|
527
|
+
list(opts?: {
|
|
528
|
+
prefix?: string;
|
|
529
|
+
limit?: number;
|
|
530
|
+
cursor?: number;
|
|
531
|
+
}): Promise<FilePage>;
|
|
532
|
+
/** Delete a file, its text and what only it taught (a NotFoundError when no file has that path). */
|
|
533
|
+
delete(path: string): Promise<void>;
|
|
534
|
+
/** Delete every file whose path starts with `prefix` ("/memories/" for everything in that folder), with what
|
|
535
|
+
* only they taught. Resolves to how many. */
|
|
536
|
+
deletePrefix(prefix: string): Promise<number>;
|
|
537
|
+
/** Move a file, or, when `from` is a folder, every file in it, keeping the text and what was learned. A
|
|
538
|
+
* NotFoundError when there is nothing to move; a BadRequestError with code "conflict" when a destination is
|
|
539
|
+
* already taken, and then nothing moves. Resolves to how many files moved. */
|
|
540
|
+
move(from: string, to: string): Promise<number>;
|
|
541
|
+
}
|
|
477
542
|
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
|
|
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.
|
|
13
|
+
export const VERSION = "0.3.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) {
|
|
@@ -106,6 +106,8 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
106
106
|
export class Geniffy {
|
|
107
107
|
memories;
|
|
108
108
|
sources;
|
|
109
|
+
/** Files kept with their exact text, such as the ones Claude's memory tool writes (see `geniffy/claude`) */
|
|
110
|
+
files;
|
|
109
111
|
/** Keys limited to one of your users, on a client bound to them: client.space(id).keys */
|
|
110
112
|
keys;
|
|
111
113
|
/** The sections profiles are grouped into: every user's on the plain client, one user's on client.space(id) */
|
|
@@ -135,6 +137,7 @@ export class Geniffy {
|
|
|
135
137
|
}
|
|
136
138
|
this.memories = new Memories(this);
|
|
137
139
|
this.sources = new Sources(this);
|
|
140
|
+
this.files = new Files(this);
|
|
138
141
|
this.keys = new Keys(this);
|
|
139
142
|
this.sections = new Sections(this);
|
|
140
143
|
}
|
|
@@ -262,7 +265,8 @@ export class Geniffy {
|
|
|
262
265
|
return this.request("GET", "/v1/graph");
|
|
263
266
|
}
|
|
264
267
|
/** Everything held, as the user's own copy: every memory, current or not, with its status and the sentence it
|
|
265
|
-
* came from,
|
|
268
|
+
* came from, every source, and every file by its path (files.get(path) reads each one's text). On
|
|
269
|
+
* client.space(id), for a user who asks what you hold about them. */
|
|
266
270
|
export() {
|
|
267
271
|
return this.request("GET", "/v1/export");
|
|
268
272
|
}
|
|
@@ -417,9 +421,9 @@ export class Sections {
|
|
|
417
421
|
await this.client.request("DELETE", `/v1/profile/sections/${Math.trunc(id)}`);
|
|
418
422
|
}
|
|
419
423
|
}
|
|
420
|
-
// Each call deletes up to 100 sources and says whether more
|
|
421
|
-
// deleteLabelled() makes, so a filter that somehow keeps matching cannot loop for ever.
|
|
422
|
-
const
|
|
424
|
+
// Each call deletes up to 100 sources (or files) and says whether more are left; this many calls is the most one
|
|
425
|
+
// deleteLabelled() or files.deletePrefix() makes, so a filter that somehow keeps matching cannot loop for ever.
|
|
426
|
+
const DELETE_CALLS = 1000;
|
|
423
427
|
export class Sources {
|
|
424
428
|
client;
|
|
425
429
|
constructor(client) {
|
|
@@ -443,7 +447,7 @@ export class Sources {
|
|
|
443
447
|
if (opts.keep !== undefined)
|
|
444
448
|
return this.deleteAllBut(labels, opts.keep);
|
|
445
449
|
let total = 0;
|
|
446
|
-
for (let i = 0; i <
|
|
450
|
+
for (let i = 0; i < DELETE_CALLS; i++) {
|
|
447
451
|
const out = await this.client.request("DELETE", "/v1/sources", {
|
|
448
452
|
query: { label: labelQuery(labels) },
|
|
449
453
|
});
|
|
@@ -517,4 +521,58 @@ export class Sources {
|
|
|
517
521
|
}
|
|
518
522
|
}
|
|
519
523
|
}
|
|
524
|
+
/**
|
|
525
|
+
* Files kept exactly as they were written, each under a path such as /memories/notes.md: what an agent keeps for
|
|
526
|
+
* itself, like the notes Claude's memory tool writes (see `geniffy/claude`). Geniffy also learns from each file like
|
|
527
|
+
* a note titled by its path, so context() and ask() recall what it says, and deleting it takes back what only it
|
|
528
|
+
* taught.
|
|
529
|
+
*
|
|
530
|
+
* A path starts with "/" and has at most 255 characters, with no empty, "." or ".." parts and no backslash.
|
|
531
|
+
*/
|
|
532
|
+
export class Files {
|
|
533
|
+
client;
|
|
534
|
+
constructor(client) {
|
|
535
|
+
this.client = client;
|
|
536
|
+
}
|
|
537
|
+
/** Create a file, or replace its text. The text is kept exactly as sent, whitespace and line endings included,
|
|
538
|
+
* and learned like a note; a replace learns only what changed. An empty file is kept too, with nothing learned
|
|
539
|
+
* from it. labels: as on memories.add. */
|
|
540
|
+
put(path, text, opts = {}) {
|
|
541
|
+
return this.client.request("PUT", "/v1/files", { json: { path, text, labels: opts.labels } });
|
|
542
|
+
}
|
|
543
|
+
/** A file and its exact text (a NotFoundError when no file has that path). */
|
|
544
|
+
get(path) {
|
|
545
|
+
return this.client.request("GET", "/v1/files", { query: { path } });
|
|
546
|
+
}
|
|
547
|
+
/** The files whose paths start with `prefix`, by path, without their text ("/", the default, for all of them).
|
|
548
|
+
* Up to 200 a page; `next` is the cursor of the page after, null at the end. */
|
|
549
|
+
list(opts = {}) {
|
|
550
|
+
return this.client.request("GET", "/v1/files", {
|
|
551
|
+
query: { prefix: opts.prefix ?? "/", limit: opts.limit ?? 100, cursor: opts.cursor ?? 0 },
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
/** Delete a file, its text and what only it taught (a NotFoundError when no file has that path). */
|
|
555
|
+
async delete(path) {
|
|
556
|
+
await this.client.request("DELETE", "/v1/files", { query: { path } });
|
|
557
|
+
}
|
|
558
|
+
/** Delete every file whose path starts with `prefix` ("/memories/" for everything in that folder), with what
|
|
559
|
+
* only they taught. Resolves to how many. */
|
|
560
|
+
async deletePrefix(prefix) {
|
|
561
|
+
let total = 0;
|
|
562
|
+
for (let i = 0; i < DELETE_CALLS; i++) {
|
|
563
|
+
const out = await this.client.request("DELETE", "/v1/files", { query: { prefix } });
|
|
564
|
+
total += out.deleted ?? 0;
|
|
565
|
+
if (!out.more)
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
return total;
|
|
569
|
+
}
|
|
570
|
+
/** Move a file, or, when `from` is a folder, every file in it, keeping the text and what was learned. A
|
|
571
|
+
* NotFoundError when there is nothing to move; a BadRequestError with code "conflict" when a destination is
|
|
572
|
+
* already taken, and then nothing moves. Resolves to how many files moved. */
|
|
573
|
+
async move(from, to) {
|
|
574
|
+
const out = await this.client.request("POST", "/v1/files/move", { json: { from, to } });
|
|
575
|
+
return out.moved ?? 0;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
520
578
|
export default Geniffy;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "geniffy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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"
|
|
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
|
}
|