geniffy 0.1.1 → 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 CHANGED
@@ -50,21 +50,57 @@ A space exists from the first time you write to it; there is nothing to create.
50
50
  const mem = client.space(`user_${user.id}`); // per request
51
51
  await client.memories.add("..."); // no space: your own memory, the one the Geniffy app shows
52
52
  await client.spaces(); // which spaces hold anything, most recently written first
53
+ await client.space("user_8841").export(); // everything held for that user, as their own copy
53
54
  await client.forgetSpace("user_8841"); // everything held for that user, gone, when they ask
54
55
  ```
55
56
 
57
+ To let a user's own app or device reach their memory, and nothing else, give it a key limited to them:
58
+
59
+ ```ts
60
+ const key = await client.space(`user_${user.id}`).keys.create({ name: "Asha's phone" }); // key.key is shown once
61
+ await client.space(`user_${user.id}`).keys.revoke(key.id);
62
+ ```
63
+
64
+ Group your users' profiles your way with sections: `client.sections.create({ name: "billing", keywords: ["invoice"] })`
65
+ for every user, or on `client.space(id)` for one.
66
+
56
67
  ## Add
57
68
 
58
69
  ```ts
59
70
  await mem.memories.add({ text: "Pilots run for 6 weeks.", title: "GTM plan" });
60
71
  await mem.memories.add({ url: "https://example.com" }); // a web page, read once
61
72
  await mem.memories.add({ messages: chatHistory }); // a conversation, as your framework holds it
62
- await mem.memories.addFile(fileOrBlob, { filename: "Pricing.pdf" }); // PDF or Word (.docx)
73
+ await mem.memories.add({ text: "We moved the launch to March.", saidAt: "2026-09-12" }); // dated by when it was said
74
+ await mem.memories.addFile(fileOrBlob, { filename: "Pricing.pdf" }); // PDF, .docx, .pptx, .xlsx or text
63
75
  await mem.memories.addMany([{ text: "..." }, { url: "https://..." }]);
64
76
  ```
65
77
 
66
78
  A file or page that can't be read rejects with `UnreadableError`; `error.source` is the row it left, with the reason.
67
79
 
80
+ Syncing your own records? Give each its id. Sent again under the same `externalId`, the source is updated
81
+ rather than added twice: only what changed is learned, and what was removed is taken back.
82
+
83
+ ```ts
84
+ await mem.memories.add({ text: ticket.body, title: ticket.subject, externalId: `ticket-${ticket.id}` });
85
+ await mem.sources.get({ externalId: `ticket-${ticket.id}` });
86
+ await mem.sources.delete({ externalId: `ticket-${ticket.id}` }); // when the ticket is deleted in your app
87
+ ```
88
+
89
+ Label what you add with your own name/value pairs, then keep any read to them. Every name must match, and a
90
+ list of values is any one of them.
91
+
92
+ ```ts
93
+ await mem.memories.add({ text: email.body, title: email.subject, labels: { channel: "email", account: "lumen" } });
94
+ await mem.context("When does the renewal come up?", { labels: { account: "lumen" } });
95
+ await mem.search("pricing", { labels: { channel: ["email", "chat"] } });
96
+ await mem.memories.list({ labels: { account: "lumen" } });
97
+ await mem.sources.deleteLabelled({ channel: "email" }); // the user disconnected it: all it brought goes
98
+ await mem.sources.deleteLabelled({ channel: "email" }, { keep: seen }); // the end of a full sync: all but what is still there
99
+ ```
100
+
101
+ To keep a whole data source in step, such as a user's Gmail, Drive or Notion, see
102
+ [Sync a data source](https://docs.geniffy.com/add-memories/sync-a-data-source).
103
+
68
104
  ## Read and correct
69
105
 
70
106
  ```ts
@@ -78,13 +114,51 @@ await mem.sources.list();
78
114
  await mem.sources.delete(source.id); // a source, and what only it taught
79
115
  ```
80
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
+
81
155
  ## Errors, retries and request ids
82
156
 
83
157
  Every error carries the API's own sentence: `AuthenticationError` (a wrong or revoked key),
84
158
  `NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `InternalServerError`,
85
- `APIConnectionError`; all extend `GeniffyError`. Reads are retried twice on network errors, 408, 429 and
86
- 5xx; adding is retried only on 429, so a retry never saves a note twice. Pass `{ maxRetries, timeout }`
87
- 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.
88
162
 
89
163
  Every response carries an `X-Request-ID`, and every error carries it as `error.requestId`. Paste it into
90
164
  **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
+ }