notesoup 0.39.0 → 0.40.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 +5 -2
- package/dist/src/boot/render.js +2 -2
- package/dist/src/boot/text.d.ts +0 -4
- package/dist/src/boot/text.js +9 -13
- package/dist/src/history/history.d.ts +23 -18
- package/dist/src/history/history.js +37 -20
- package/dist/src/history/query.d.ts +37 -49
- package/dist/src/history/query.js +114 -56
- package/dist/src/notes/store.d.ts +3 -4
- package/dist/src/notes/store.js +12 -16
- package/dist/src/pi/history-tools.d.ts +1 -1
- package/dist/src/pi/history-tools.js +2 -3
- package/dist/src/pi/runtime.js +1 -1
- package/dist/src/pi/tool-names.d.ts +0 -4
- package/dist/src/pi/tool-names.js +0 -4
- package/dist/src/tools/history.d.ts +24 -33
- package/dist/src/tools/history.js +57 -98
- package/dist/src/tools/notes.d.ts +26 -58
- package/dist/src/tools/notes.js +85 -103
- package/dist/src/tools/result.d.ts +16 -13
- package/dist/src/tools/result.js +24 -50
- package/dist/src/tools/schema.d.ts +2 -2
- package/dist/src/tools/schema.js +3 -3
- package/dist/test/agent-loop.test.js +1 -1
- package/dist/test/boot.integration.test.js +1 -1
- package/dist/test/claude-mod.test.js +4 -4
- package/dist/test/dependencies.test.js +1 -1
- package/dist/test/helpers/extension.js +2 -3
- package/dist/test/history.integration.test.js +200 -123
- package/dist/test/host-neutral.test.js +32 -58
- package/dist/test/notes-library.test.js +8 -8
- package/dist/test/notes.integration.test.js +75 -57
- package/dist/test/notes.test.js +44 -42
- package/docs/architecture.md +3 -3
- package/docs/notes-library.md +6 -6
- package/docs/tool-results.md +15 -25
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +119 -178
- package/mods/notesoup/hooks/register.ts +1 -2
- package/package.json +1 -1
- package/skills/memory/SKILL.md +6 -6
- package/src/boot/render.ts +2 -2
- package/src/boot/text.ts +9 -17
- package/src/history/history.ts +36 -20
- package/src/history/query.ts +130 -55
- package/src/notes/store.ts +15 -18
- package/src/pi/history-tools.ts +2 -3
- package/src/pi/runtime.ts +1 -1
- package/src/pi/tool-names.ts +0 -4
- package/src/tools/history.ts +61 -100
- package/src/tools/notes.ts +84 -97
- package/src/tools/result.ts +24 -49
- package/src/tools/schema.ts +3 -3
package/src/tools/notes.ts
CHANGED
|
@@ -3,47 +3,32 @@ import { Type, type Static } from "typebox";
|
|
|
3
3
|
import { localIso } from "../notes/frontmatter.js";
|
|
4
4
|
import { isFilesystemError } from "../notes/fs-error.js";
|
|
5
5
|
import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow, type Scope } from "../notes/index.js";
|
|
6
|
-
import {
|
|
7
|
-
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowSchema, type Outcome } from "./result.js";
|
|
6
|
+
import { prefixFit } from "./output.js";
|
|
7
|
+
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowRequestSchema, TextWindowSchema, type Outcome } from "./result.js";
|
|
8
8
|
import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
|
|
9
9
|
|
|
10
10
|
const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
|
|
11
11
|
const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
|
|
12
|
-
description: "
|
|
12
|
+
description: "(optional, default self) Who wrote it: user, self, or external.",
|
|
13
13
|
}));
|
|
14
|
-
const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "
|
|
15
|
-
const
|
|
16
|
-
const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
17
|
-
const
|
|
14
|
+
const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
|
|
15
|
+
const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
|
|
16
|
+
const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
|
|
17
|
+
const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
|
|
18
|
+
const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
|
|
18
19
|
|
|
19
20
|
/** The one receipt field a caller cannot derive from the address itself. */
|
|
20
21
|
function projectKeyField(scope: Scope, projectKey: string): { project_key?: string } {
|
|
21
22
|
return scope === "project" ? { project_key: projectKey } : {};
|
|
22
23
|
}
|
|
23
24
|
|
|
24
|
-
const MAX_ERROR_LINE_FACTS = 20;
|
|
25
|
-
|
|
26
25
|
/**
|
|
27
|
-
* Typed refusal.
|
|
26
|
+
* Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
|
|
28
27
|
* Convert expected refusals; unexpected errors propagate unchanged.
|
|
29
28
|
*/
|
|
30
29
|
function failureOf(error: unknown): Outcome<never> {
|
|
31
|
-
if (error instanceof NoteError)
|
|
32
|
-
|
|
33
|
-
let message = error.message;
|
|
34
|
-
if (error.lineNumbers) {
|
|
35
|
-
if (error.lineNumbers.length > MAX_ERROR_LINE_FACTS) {
|
|
36
|
-
details.line_numbers = error.lineNumbers.slice(0, MAX_ERROR_LINE_FACTS);
|
|
37
|
-
details.line_numbers_total = error.lineNumbers.length;
|
|
38
|
-
message = `${message} (this refusal names ${MAX_ERROR_LINE_FACTS} of ${error.lineNumbers.length} match lines; the note is unchanged)`;
|
|
39
|
-
} else {
|
|
40
|
-
details.line_numbers = error.lineNumbers;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
if (error.editIndex !== undefined) details.edit_index = error.editIndex;
|
|
44
|
-
return failure(error.code, message, Object.keys(details).length > 0 ? details : undefined);
|
|
45
|
-
}
|
|
46
|
-
// Address, pattern, and query guards raise declared types; nothing else is converted.
|
|
30
|
+
if (error instanceof NoteError) return failure(error.code, error.message);
|
|
31
|
+
// Address, glob, and query guards raise declared types; nothing else is converted.
|
|
47
32
|
if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
|
|
48
33
|
if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
|
|
49
34
|
throw error;
|
|
@@ -55,9 +40,11 @@ function byRecent<T extends { address: string; meta: { updatedAt: number } }>(a:
|
|
|
55
40
|
|
|
56
41
|
/** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
|
|
57
42
|
const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
|
|
58
|
-
/** One unrecognized entry, and
|
|
43
|
+
/** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
|
|
59
44
|
export const MAX_METADATA_ENTRY_BYTES = 1024;
|
|
60
|
-
const
|
|
45
|
+
const MAX_METADATA_VERBATIM_BYTES = 2048;
|
|
46
|
+
/** An extra value that cannot be carried is named in place, never silently dropped. */
|
|
47
|
+
export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
|
|
61
48
|
|
|
62
49
|
/** Include the key: hand-written frontmatter can have arbitrarily long keys. */
|
|
63
50
|
function extraEntryBytes(key: string, value: unknown): number {
|
|
@@ -71,28 +58,28 @@ export const NoteMetadataSchema = Type.Object({
|
|
|
71
58
|
crumpled_at: Type.Optional(Type.String()),
|
|
72
59
|
project: Type.Optional(Type.String()),
|
|
73
60
|
extra: Type.Record(Type.String(), Type.Unknown()),
|
|
74
|
-
|
|
75
|
-
omitted_extra: Type.Optional(Type.Object({ keys: Type.Integer(), bytes: Type.Integer() })),
|
|
76
|
-
});
|
|
61
|
+
}, { additionalProperties: false });
|
|
77
62
|
export type NoteMetadata = Static<typeof NoteMetadataSchema>;
|
|
78
63
|
|
|
79
|
-
/** Normalize known metadata and bound extras
|
|
64
|
+
/** Normalize known metadata and bound extras, naming an oversized value instead of hiding it. */
|
|
80
65
|
function noteMetadata(meta: NoteMeta): NoteMetadata {
|
|
81
66
|
const extra: Record<string, unknown> = {};
|
|
82
|
-
let
|
|
83
|
-
|
|
84
|
-
|
|
67
|
+
let verbatimBytes = 0;
|
|
68
|
+
const put = (key: string, value: unknown): void => {
|
|
69
|
+
// defineProperty keeps a hand-written `__proto__` key as ordinary data.
|
|
70
|
+
Object.defineProperty(extra, key, { value, enumerable: true, writable: true, configurable: true });
|
|
71
|
+
};
|
|
85
72
|
for (const [key, value] of Object.entries(meta)) {
|
|
86
73
|
if (NORMALIZED_META_KEYS.has(key) || value === undefined) continue;
|
|
87
|
-
|
|
88
|
-
if (
|
|
89
|
-
|
|
90
|
-
|
|
74
|
+
// A key too large to carry cannot be named at all; an oversized value is named in place.
|
|
75
|
+
if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES) continue;
|
|
76
|
+
const entryBytes = extraEntryBytes(key, value);
|
|
77
|
+
if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
|
|
78
|
+
put(key, TOO_LARGE_EXTRA_VALUE);
|
|
91
79
|
continue;
|
|
92
80
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
Object.defineProperty(extra, key, { value, enumerable: true, writable: true, configurable: true });
|
|
81
|
+
verbatimBytes += entryBytes;
|
|
82
|
+
put(key, value);
|
|
96
83
|
}
|
|
97
84
|
return {
|
|
98
85
|
origin: meta.origin,
|
|
@@ -101,7 +88,6 @@ function noteMetadata(meta: NoteMeta): NoteMetadata {
|
|
|
101
88
|
...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
|
|
102
89
|
...(typeof meta.project === "string" ? { project: meta.project } : {}),
|
|
103
90
|
extra,
|
|
104
|
-
...(omittedKeys > 0 ? { omitted_extra: { keys: omittedKeys, bytes: omittedBytes } } : {}),
|
|
105
91
|
};
|
|
106
92
|
}
|
|
107
93
|
|
|
@@ -115,7 +101,6 @@ function renderMetadata(metadata: NoteMetadata): string {
|
|
|
115
101
|
];
|
|
116
102
|
const extra = Object.keys(metadata.extra);
|
|
117
103
|
if (extra.length > 0) fields.push(`extra ${JSON.stringify(metadata.extra)}`);
|
|
118
|
-
if (metadata.omitted_extra !== undefined) fields.push(`${metadata.omitted_extra.keys} more metadata values (${metadata.omitted_extra.bytes} bytes) are in the note file but too large to show`);
|
|
119
104
|
return fields.join(" | ");
|
|
120
105
|
}
|
|
121
106
|
|
|
@@ -129,24 +114,21 @@ const ListedFileSchema = Type.Object({
|
|
|
129
114
|
project_key: Type.Optional(Type.String()),
|
|
130
115
|
updated_at: Type.String(),
|
|
131
116
|
crumpled_at: Type.Optional(Type.String()),
|
|
132
|
-
});
|
|
117
|
+
}, { additionalProperties: false });
|
|
133
118
|
|
|
134
119
|
const MatchSchema = Type.Object({
|
|
135
120
|
line: Type.Integer(),
|
|
136
121
|
text: Type.String(),
|
|
137
|
-
truncated: Type.Boolean(),
|
|
138
122
|
offset_chars: Type.Integer(),
|
|
139
|
-
});
|
|
123
|
+
}, { additionalProperties: false });
|
|
140
124
|
|
|
141
125
|
const SearchedFileSchema = Type.Object({
|
|
142
126
|
...ListedFileSchema.properties,
|
|
143
|
-
matches_total: Type.Integer(),
|
|
144
127
|
matches: Type.Array(MatchSchema),
|
|
145
|
-
});
|
|
128
|
+
}, { additionalProperties: false });
|
|
146
129
|
|
|
147
130
|
const SnapshotSchema = {
|
|
148
|
-
more: Type.Integer(),
|
|
149
|
-
crumpled_excluded: Type.Integer(),
|
|
131
|
+
more: Type.Integer({ description: "How many more were left out." }),
|
|
150
132
|
homes_unavailable: Type.Array(Type.String()),
|
|
151
133
|
};
|
|
152
134
|
|
|
@@ -154,19 +136,16 @@ export const NotesWriteDataSchema = Type.Object({
|
|
|
154
136
|
address: Type.String(),
|
|
155
137
|
project_key: Type.Optional(Type.String()),
|
|
156
138
|
outcome: Type.Union([Type.Literal("created"), Type.Literal("overwrote"), Type.Literal("uncrumpled")]),
|
|
157
|
-
});
|
|
139
|
+
}, { additionalProperties: false });
|
|
158
140
|
export type NotesWriteData = Static<typeof NotesWriteDataSchema>;
|
|
159
141
|
|
|
160
142
|
export const NotesUpdateDataSchema = Type.Object({
|
|
161
143
|
address: Type.String(),
|
|
162
144
|
project_key: Type.Optional(Type.String()),
|
|
163
|
-
|
|
164
|
-
change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("file")]),
|
|
145
|
+
change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("moved")]),
|
|
165
146
|
diff: Type.String(),
|
|
166
|
-
diff_truncated: Type.Optional(Type.Literal(true)),
|
|
167
147
|
rename_from: Type.Optional(Type.String()),
|
|
168
|
-
|
|
169
|
-
});
|
|
148
|
+
}, { additionalProperties: false });
|
|
170
149
|
export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
|
|
171
150
|
|
|
172
151
|
export const NotesReadDataSchema = Type.Object({
|
|
@@ -174,19 +153,19 @@ export const NotesReadDataSchema = Type.Object({
|
|
|
174
153
|
project_key: Type.Optional(Type.String()),
|
|
175
154
|
metadata: NoteMetadataSchema,
|
|
176
155
|
...TextWindowSchema.properties,
|
|
177
|
-
});
|
|
156
|
+
}, { additionalProperties: false });
|
|
178
157
|
export type NotesReadData = Static<typeof NotesReadDataSchema>;
|
|
179
158
|
|
|
180
159
|
export const NotesListDataSchema = Type.Object({
|
|
181
160
|
files: Type.Array(ListedFileSchema),
|
|
182
161
|
...SnapshotSchema,
|
|
183
|
-
});
|
|
162
|
+
}, { additionalProperties: false });
|
|
184
163
|
export type NotesListData = Static<typeof NotesListDataSchema>;
|
|
185
164
|
|
|
186
165
|
export const NotesSearchDataSchema = Type.Object({
|
|
187
166
|
files: Type.Array(SearchedFileSchema),
|
|
188
167
|
...SnapshotSchema,
|
|
189
|
-
});
|
|
168
|
+
}, { additionalProperties: false });
|
|
190
169
|
export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
|
|
191
170
|
|
|
192
171
|
type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
|
|
@@ -200,7 +179,7 @@ function snapshot<T>(
|
|
|
200
179
|
shrink?: (item: T, fits: (candidate: T) => boolean) => T,
|
|
201
180
|
): Outcome<Snapshot<T>> {
|
|
202
181
|
const files: T[] = [];
|
|
203
|
-
const data = (selected: T[]): Snapshot<T> => ({ files: selected, more: rows.length - selected.length,
|
|
182
|
+
const data = (selected: T[]): Snapshot<T> => ({ files: selected, more: rows.length - selected.length, homes_unavailable: status.homesUnavailable });
|
|
204
183
|
const render = (outcome: Outcome<Snapshot<T>>) => renderOutcome(outcome, renderData);
|
|
205
184
|
const fits = (item: T) => fitsResult(success(data([...files, item])), render);
|
|
206
185
|
for (const item of rows.slice(0, limit)) {
|
|
@@ -231,7 +210,7 @@ function renderWriteData(data: NotesWriteData): string {
|
|
|
231
210
|
|
|
232
211
|
export const notesWrite = {
|
|
233
212
|
name: "notes_write", label: "Notes write",
|
|
234
|
-
description: `Create or replace a note body,
|
|
213
|
+
description: `Create or replace a note's body, keeping metadata; uncrumples a crumpled note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
|
|
235
214
|
parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
|
|
236
215
|
async execute(params: Static<typeof notesWriteParameters>, identity: NotesIdentity): Promise<Outcome<NotesWriteData>> {
|
|
237
216
|
try {
|
|
@@ -242,16 +221,21 @@ export const notesWrite = {
|
|
|
242
221
|
render: (result: Outcome<NotesWriteData>): string => renderOutcome(result, renderWriteData),
|
|
243
222
|
} as const;
|
|
244
223
|
|
|
245
|
-
export const notesUpdateParameters = Type.Object({
|
|
224
|
+
export const notesUpdateParameters = Type.Object({
|
|
225
|
+
address: Type.String(),
|
|
226
|
+
edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
|
|
227
|
+
origin: ORIGIN,
|
|
228
|
+
crumpled: CRUMPLED_PARAMETER,
|
|
229
|
+
replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
|
|
230
|
+
rename_to: Type.Optional(Type.String({ description: "(optional) Move to this address, keeping metadata. Use alone. Won't overwrite a live note; references aren't updated." })),
|
|
231
|
+
}, { additionalProperties: false });
|
|
246
232
|
|
|
247
233
|
function renderUpdateData(data: NotesUpdateData): string {
|
|
248
234
|
const head = data.rename_from === undefined
|
|
249
|
-
? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}
|
|
250
|
-
: `moved ${data.rename_from} -> ${data.address}
|
|
235
|
+
? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}`
|
|
236
|
+
: `moved ${data.rename_from} -> ${data.address}`;
|
|
251
237
|
const lines = [head];
|
|
252
|
-
if (data.
|
|
253
|
-
else if (data.diff.length > 0) lines.push("diff:");
|
|
254
|
-
if (data.diff.length > 0) lines.push(data.diff);
|
|
238
|
+
if (data.diff.length > 0) lines.push("diff:", data.diff);
|
|
255
239
|
return lines.join("\n");
|
|
256
240
|
}
|
|
257
241
|
|
|
@@ -259,18 +243,21 @@ function renderUpdate(result: Outcome<NotesUpdateData>): string {
|
|
|
259
243
|
return renderOutcome(result, renderUpdateData);
|
|
260
244
|
}
|
|
261
245
|
|
|
262
|
-
/**
|
|
246
|
+
/** A shortened diff still says so in the receipt's own text, on both surfaces. */
|
|
247
|
+
export const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
|
|
248
|
+
|
|
249
|
+
/** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix and marked. */
|
|
263
250
|
function boundedUpdate(data: NotesUpdateData): Outcome<NotesUpdateData> {
|
|
264
251
|
if (fitsResult(success(data), renderUpdate)) return success(data);
|
|
265
|
-
|
|
266
|
-
const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...
|
|
267
|
-
const result = success({ ...
|
|
252
|
+
if (data.diff === "") return failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
|
|
253
|
+
const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}\n${DIFF_SHORTENED_MARKER}` }), renderUpdate));
|
|
254
|
+
const result = success({ ...data, diff: `${diff}\n${DIFF_SHORTENED_MARKER}` });
|
|
268
255
|
return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
|
|
269
256
|
}
|
|
270
257
|
|
|
271
258
|
export const notesUpdate = {
|
|
272
259
|
name: "notes_update", label: "Notes update",
|
|
273
|
-
description: `Edit body
|
|
260
|
+
description: `Edit a note's body, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true; frontmatter can't be edited. Returns a diff. ${ADDRESS_DESCRIPTION}`,
|
|
274
261
|
parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
|
|
275
262
|
async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string): Promise<Outcome<NotesUpdateData>> {
|
|
276
263
|
try {
|
|
@@ -281,19 +268,19 @@ export const notesUpdate = {
|
|
|
281
268
|
if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
|
|
282
269
|
return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
|
|
283
270
|
}
|
|
284
|
-
|
|
271
|
+
await store.rename(params.address, renameTo);
|
|
285
272
|
const from = noteIdentity(identity, params.address).address;
|
|
286
273
|
const to = noteIdentity(identity, renameTo);
|
|
287
|
-
return boundedUpdate({ ...to, rename_from: from,
|
|
274
|
+
return boundedUpdate({ ...to, rename_from: from, change_kind: "moved", diff: `rename ${from} -> ${to.address}` });
|
|
288
275
|
}
|
|
289
|
-
const {
|
|
290
|
-
return boundedUpdate({ ...noteIdentity(identity, params.address),
|
|
276
|
+
const { change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
|
|
277
|
+
return boundedUpdate({ ...noteIdentity(identity, params.address), change_kind: change.kind, diff: renderDiff(change) });
|
|
291
278
|
} catch (error) { return failureOf(error); }
|
|
292
279
|
},
|
|
293
280
|
render: renderUpdate,
|
|
294
281
|
} as const;
|
|
295
282
|
|
|
296
|
-
export const notesReadParameters = Type.Object({ address: Type.String(),
|
|
283
|
+
export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
297
284
|
|
|
298
285
|
function renderReadData(data: NotesReadData): string {
|
|
299
286
|
return `${renderIdentity(data)}\n${renderMetadata(data.metadata)}\n\n${renderTextWindow(data)}`;
|
|
@@ -301,7 +288,7 @@ function renderReadData(data: NotesReadData): string {
|
|
|
301
288
|
|
|
302
289
|
export const notesRead = {
|
|
303
290
|
name: "notes_read", label: "Notes read",
|
|
304
|
-
description: `Read note metadata and
|
|
291
|
+
description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
|
|
305
292
|
parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
|
|
306
293
|
async execute(params: Static<typeof notesReadParameters>, identity: NotesIdentity): Promise<Outcome<NotesReadData>> {
|
|
307
294
|
try {
|
|
@@ -311,55 +298,56 @@ export const notesRead = {
|
|
|
311
298
|
if (params.offset_chars !== undefined && params.offset_chars > totalChars) return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end of the body: the note has ${totalChars} body chars; the largest legal offset is ${totalChars} (an empty end-read)`);
|
|
312
299
|
const resolved = noteIdentity(identity, params.address);
|
|
313
300
|
const metadata = noteMetadata(note.meta);
|
|
314
|
-
return readTextWindow(note.body, params.offset_chars, params.
|
|
301
|
+
return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
|
|
315
302
|
} catch (error) { return failureOf(error); }
|
|
316
303
|
},
|
|
317
304
|
render: (result: Outcome<NotesReadData>): string => renderOutcome(result, renderReadData),
|
|
318
305
|
} as const;
|
|
319
306
|
|
|
320
|
-
export const notesListParameters = Type.Object({
|
|
307
|
+
export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
|
|
321
308
|
|
|
322
309
|
function renderListData(data: NotesListData): string {
|
|
323
310
|
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
324
311
|
for (const file of data.files) {
|
|
325
312
|
lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
|
|
326
313
|
}
|
|
327
|
-
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with
|
|
328
|
-
if (data.crumpled_excluded > 0) lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to list them`);
|
|
314
|
+
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
|
|
329
315
|
for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
|
|
330
316
|
return lines.join("\n");
|
|
331
317
|
}
|
|
332
318
|
|
|
333
319
|
export const notesList = {
|
|
334
320
|
name: "notes_list", label: "Notes list",
|
|
335
|
-
description: `List notes in
|
|
321
|
+
description: `List notes in this session and the four @ homes, newest first. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
|
|
336
322
|
parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
|
|
337
323
|
async execute(params: Static<typeof notesListParameters>, identity: NotesIdentity): Promise<Outcome<NotesListData>> {
|
|
338
324
|
try {
|
|
339
|
-
const { rows, status } = await createNotesStore(identity).listWithStatus({
|
|
325
|
+
const { rows, status } = await createNotesStore(identity).listWithStatus({ glob: params.glob ?? undefined, crumpled: params.crumpled });
|
|
340
326
|
return snapshot(rows.map(row => listedFile(row, identity)), params.limit, status, renderListData);
|
|
341
327
|
} catch (error) { return failureOf(error); }
|
|
342
328
|
},
|
|
343
329
|
render: (result: Outcome<NotesListData>): string => renderOutcome(result, renderListData),
|
|
344
330
|
} as const;
|
|
345
331
|
|
|
346
|
-
export const notesSearchParameters = Type.Object({ query: searchQuery(),
|
|
332
|
+
export const notesSearchParameters = Type.Object({ query: searchQuery(), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default all) Max matching lines per note." })), crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
|
|
347
333
|
|
|
348
334
|
function renderSearchData(data: NotesSearchData): string {
|
|
349
|
-
const lines = [`${data.files.length} ${data.files.length === 1 ? "
|
|
335
|
+
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
350
336
|
for (const file of data.files) {
|
|
351
|
-
lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.
|
|
352
|
-
for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}
|
|
337
|
+
lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
|
|
338
|
+
for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
|
|
353
339
|
}
|
|
354
|
-
if (data.more > 0) lines.push(`${data.more} more matching
|
|
355
|
-
if (data.crumpled_excluded > 0) lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to search them`);
|
|
340
|
+
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
|
|
356
341
|
for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
|
|
357
342
|
return lines.join("\n");
|
|
358
343
|
}
|
|
359
344
|
|
|
360
345
|
type SearchFile = NotesSearchData["files"][number];
|
|
361
346
|
|
|
362
|
-
/**
|
|
347
|
+
/** A shortened match line still ends with a marker, so its own text says it was cut. */
|
|
348
|
+
export const MATCH_SHORTENED_MARKER = " [truncated]";
|
|
349
|
+
|
|
350
|
+
/** Prefer whole match lines; shorten the first line only if no whole line fits, and mark it. */
|
|
363
351
|
function fitSearchFile(file: SearchFile, fits: (candidate: SearchFile) => boolean): SearchFile {
|
|
364
352
|
let low = 0;
|
|
365
353
|
let high = file.matches.length;
|
|
@@ -371,21 +359,20 @@ function fitSearchFile(file: SearchFile, fits: (candidate: SearchFile) => boolea
|
|
|
371
359
|
if (low > 0) return { ...file, matches: file.matches.slice(0, low) };
|
|
372
360
|
const first = file.matches[0];
|
|
373
361
|
if (!first) return file;
|
|
374
|
-
const withText = (text: string): SearchFile => ({ ...file, matches: [{ ...first, text
|
|
362
|
+
const withText = (text: string): SearchFile => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
375
363
|
return withText(prefixFit(first.text, text => fits(withText(text))));
|
|
376
364
|
}
|
|
377
365
|
|
|
378
366
|
export const notesSearch = {
|
|
379
367
|
name: "notes_search", label: "Notes search",
|
|
380
|
-
description: `Search note bodies for case-insensitive
|
|
368
|
+
description: `Search note bodies for literal text, case-insensitive. Returns matching lines with offsets for \`notes_read\`. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
|
|
381
369
|
parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
|
|
382
370
|
async execute(params: Static<typeof notesSearchParameters>, identity: NotesIdentity): Promise<Outcome<NotesSearchData>> {
|
|
383
371
|
try {
|
|
384
|
-
const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), {
|
|
372
|
+
const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
|
|
385
373
|
const files: NotesSearchData["files"] = rows.sort(byRecent).map(row => ({
|
|
386
374
|
...listedFile(row, identity),
|
|
387
|
-
|
|
388
|
-
matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, truncated: false, offset_chars: match.offsetChars })),
|
|
375
|
+
matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
|
|
389
376
|
}));
|
|
390
377
|
return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
|
|
391
378
|
} catch (error) { return failureOf(error); }
|
package/src/tools/result.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
/** Internal outcomes, compact wire results, and bounded read windows. */
|
|
2
2
|
import { Type, type Static, type TSchema } from "typebox";
|
|
3
|
-
import { DEFAULT_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
|
|
3
|
+
import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
|
|
4
4
|
|
|
5
|
-
/** `
|
|
5
|
+
/** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
|
|
6
6
|
export const OperationErrorSchema = Type.Object({
|
|
7
7
|
code: Type.String(),
|
|
8
8
|
message: Type.String(),
|
|
9
|
-
details: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
10
9
|
}, { additionalProperties: false });
|
|
11
10
|
export type OperationError = Static<typeof OperationErrorSchema>;
|
|
12
11
|
|
|
@@ -17,59 +16,36 @@ export function success<T>(data: T): Outcome<T> {
|
|
|
17
16
|
return { ok: true, data };
|
|
18
17
|
}
|
|
19
18
|
|
|
20
|
-
/** A code is an internal stable identifier and is never clipped; the dynamic message
|
|
19
|
+
/** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
|
|
21
20
|
export const ERROR_MESSAGE_MAX_CHARS = 2000;
|
|
22
|
-
export const ERROR_DETAILS_MAX_BYTES = 4096;
|
|
23
21
|
|
|
24
22
|
function boundedMessage(message: string): string {
|
|
25
23
|
const chars = Array.from(message);
|
|
26
24
|
return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const json = JSON.stringify(details);
|
|
32
|
-
const bytes = Buffer.byteLength(json, "utf8");
|
|
33
|
-
return bytes <= ERROR_DETAILS_MAX_BYTES ? JSON.parse(json) as Record<string, unknown> : { truncated: true, details_bytes: bytes };
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function failure(code: string, message: string, details?: Record<string, unknown>): Outcome<never> {
|
|
37
|
-
return {
|
|
38
|
-
ok: false,
|
|
39
|
-
error: {
|
|
40
|
-
code,
|
|
41
|
-
message: boundedMessage(message),
|
|
42
|
-
...(details === undefined ? {} : { details: boundedDetails(details) }),
|
|
43
|
-
},
|
|
44
|
-
};
|
|
27
|
+
export function failure(code: string, message: string): Outcome<never> {
|
|
28
|
+
return { ok: false, error: { code, message: boundedMessage(message) } };
|
|
45
29
|
}
|
|
46
30
|
|
|
47
31
|
/** Public results have no success envelope. `error` is reserved for a refusal message. */
|
|
48
|
-
export
|
|
32
|
+
export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
|
|
33
|
+
export type WireError = Static<typeof WireErrorSchema>;
|
|
49
34
|
export type WireResult<T> = T | WireError;
|
|
50
35
|
|
|
51
36
|
export function wireResult<T>(result: Outcome<T>): WireResult<T> {
|
|
52
37
|
if (result.ok) return result.data;
|
|
53
|
-
const { code, message
|
|
54
|
-
return { error: message, code
|
|
38
|
+
const { code, message } = result.error;
|
|
39
|
+
return { error: message, code };
|
|
55
40
|
}
|
|
56
41
|
|
|
57
42
|
export function resultSchema<S extends TSchema>(dataSchema: S) {
|
|
58
|
-
return Type.Union([
|
|
59
|
-
dataSchema,
|
|
60
|
-
Type.Object({
|
|
61
|
-
error: Type.String(),
|
|
62
|
-
code: Type.String(),
|
|
63
|
-
details: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
64
|
-
}, { additionalProperties: false }),
|
|
65
|
-
]);
|
|
43
|
+
return Type.Union([dataSchema, WireErrorSchema]);
|
|
66
44
|
}
|
|
67
45
|
|
|
68
46
|
/** A refusal reads as one short line; a success is the operation's own reading of its data. */
|
|
69
47
|
export function renderOutcome<T>(result: Outcome<T>, renderData: (data: T) => string): string {
|
|
70
|
-
|
|
71
|
-
const { code, message, details } = result.error;
|
|
72
|
-
return `error: ${code}: ${message}${details === undefined ? "" : ` ${JSON.stringify(details)}`}`;
|
|
48
|
+
return result.ok ? renderData(result.data) : `error: ${result.error.code}: ${result.error.message}`;
|
|
73
49
|
}
|
|
74
50
|
|
|
75
51
|
/** Bytes of the structured payload as delivered: compact JSON, not the model-facing text. A value with no JSON representation has no size to measure. */
|
|
@@ -88,13 +64,20 @@ export function fitsResult<T>(result: Outcome<T>, render: (result: Outcome<T>) =
|
|
|
88
64
|
/** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
|
|
89
65
|
export const TextWindowSchema = Type.Object({
|
|
90
66
|
text: Type.String(),
|
|
91
|
-
offset_chars: Type.Integer({ minimum: 0 }),
|
|
92
67
|
total_chars: Type.Integer({ minimum: 0 }),
|
|
93
|
-
next_offset_chars: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()], { description: "
|
|
94
|
-
limited_by: Type.Union([Type.Literal("limit"), Type.Literal("bytes"), Type.Null()]),
|
|
68
|
+
next_offset_chars: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()], { description: "Pass as `offset_chars` to continue; null at the end." }),
|
|
95
69
|
}, { additionalProperties: false });
|
|
96
70
|
export type TextWindow = Static<typeof TextWindowSchema>;
|
|
97
71
|
|
|
72
|
+
/**
|
|
73
|
+
* The request both read operations share: where to start and how much to deliver. Optional in full,
|
|
74
|
+
* because `readTextWindow` already owns the defaults.
|
|
75
|
+
*/
|
|
76
|
+
export const TextWindowRequestSchema = {
|
|
77
|
+
offset_chars: Type.Optional(Type.Integer({ description: "(optional, default 0) Start offset in chars; negative counts from the end." })),
|
|
78
|
+
max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${DEFAULT_READ_WINDOW_CHARS}) Max chars to return.` })),
|
|
79
|
+
};
|
|
80
|
+
|
|
98
81
|
/**
|
|
99
82
|
* Read one code-point window of `text` and build the operation's data around it. `offset` and
|
|
100
83
|
* `limit` are the integers the parameter schema already admitted; a negative `offset` resolves to
|
|
@@ -117,13 +100,10 @@ export function readTextWindow<T>(
|
|
|
117
100
|
const range = Math.min(requestedChars, chars.length - start);
|
|
118
101
|
const window = (delivered: number): TextWindow => {
|
|
119
102
|
const end = start + delivered;
|
|
120
|
-
const withheld = end < chars.length;
|
|
121
103
|
return {
|
|
122
104
|
text: chars.slice(start, end).join(""),
|
|
123
|
-
offset_chars: start,
|
|
124
105
|
total_chars: chars.length,
|
|
125
|
-
next_offset_chars:
|
|
126
|
-
limited_by: !withheld ? null : delivered === range ? "limit" : "bytes",
|
|
106
|
+
next_offset_chars: end < chars.length ? end : null,
|
|
127
107
|
};
|
|
128
108
|
};
|
|
129
109
|
const fits = (delivered: number): boolean => fitsResult(success(makeData(window(delivered))), render);
|
|
@@ -136,19 +116,14 @@ export function readTextWindow<T>(
|
|
|
136
116
|
if (fits(mid)) low = mid;
|
|
137
117
|
else high = mid - 1;
|
|
138
118
|
}
|
|
139
|
-
if (low === 0)
|
|
140
|
-
return failure("output_too_large", "The response metadata leaves no room for a progressing read window.", { total_chars: chars.length, offset_chars: start, budget_bytes: TOOL_OUTPUT_MAX_BYTES });
|
|
141
|
-
}
|
|
119
|
+
if (low === 0) return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
|
|
142
120
|
return success(makeData(window(low)));
|
|
143
121
|
}
|
|
144
122
|
|
|
145
123
|
/** The continuation line never becomes part of `window.text`, and a complete window has none. */
|
|
146
124
|
export function renderTextWindow(window: TextWindow): string {
|
|
147
125
|
const next = window.next_offset_chars;
|
|
148
|
-
|
|
149
|
-
const resume = `Use offset_chars=${next} to continue.`;
|
|
150
|
-
if (window.limited_by === "limit") return `${window.text}\n\n[${window.total_chars - next} more characters. ${resume}]`;
|
|
151
|
-
return `${window.text}\n\n[Showing chars [${window.offset_chars}, ${next}) of ${window.total_chars} (${TOOL_OUTPUT_MAX_BYTES / 1024}KB limit). ${resume}]`;
|
|
126
|
+
return next === null ? window.text : `${window.text}\n\n[truncated; continue at offset_chars=${next}]`;
|
|
152
127
|
}
|
|
153
128
|
|
|
154
129
|
/** One outcome in, model-facing text out. */
|
package/src/tools/schema.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import { HistoryRoleSchema } from "../history/history.js";
|
|
3
|
-
export const nullableString = () => Type.Optional(Type.Union([Type.String(), Type.Null()]));
|
|
3
|
+
export const nullableString = (description?: string) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
|
|
4
4
|
export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
|
|
5
|
-
export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "
|
|
5
|
+
export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
|
|
6
6
|
|
|
7
7
|
/** Search query parameter: one literal, or several literals combined with OR. */
|
|
8
|
-
export const searchQuery = () => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })]);
|
|
8
|
+
export const searchQuery = (description?: string) => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })], description === undefined ? {} : { description });
|
|
9
9
|
|
|
10
10
|
/** Expected search-query refusal, distinct from any other Error an operation may raise. */
|
|
11
11
|
export class InvalidQueryError extends Error {
|