notesoup 0.59.0 → 0.59.2
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/dist/plugins/claude/src/helper.js +2 -2
- package/dist/plugins/dsh/tools.js +0 -3
- package/dist/src/boot/text.d.ts +1 -1
- package/dist/src/boot/text.js +6 -10
- package/dist/src/history/claude.d.ts +3 -1
- package/dist/src/history/claude.js +40 -4
- package/dist/src/history/prefilter.d.ts +1 -1
- package/dist/src/history/prefilter.js +14 -9
- package/dist/src/notes/address.d.ts +1 -1
- package/dist/src/notes/address.js +1 -1
- package/dist/src/notes/policy.js +1 -1
- package/dist/src/tools/dream.d.ts +3 -3
- package/dist/src/tools/dream.js +5 -5
- package/dist/src/tools/history.js +12 -13
- package/dist/src/tools/notes.d.ts +7 -5
- package/dist/src/tools/notes.js +35 -34
- package/dist/src/tools/result.js +2 -2
- package/dist/src/tools/schema.js +2 -2
- package/dist/test/claude-history.test.js +22 -0
- package/dist/test/claude-mod.test.js +13 -1
- package/dist/test/dsh.test.js +13 -1
- package/dist/test/history-prefilter.test.js +5 -0
- package/dist/test/note-policy.test.js +6 -1
- package/dist/test/notes.integration.test.js +28 -0
- package/docs/claude-code-mod.md +3 -1
- package/docs/history-sessions.md +1 -1
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +111 -81
- package/plugins/claude/hooks/register.ts +14 -10
- package/plugins/claude/src/helper.ts +2 -2
- package/plugins/codex/dist/codex/notesoup.js +74 -69
- package/plugins/dsh/tools.ts +0 -2
- package/plugins/paseo/README.md +16 -0
- package/plugins/paseo/client/brain-empty-card.tsx +5 -3
- package/plugins/paseo/client/markdown-core.tsx +189 -0
- package/plugins/paseo/client/markdown.tsx +38 -135
- package/plugins/paseo/client/notes-op-card.tsx +15 -12
- package/plugins/paseo/client/paper-card.tsx +1 -3
- package/plugins/paseo/client/sticky-card.tsx +2 -1
- package/plugins/paseo/client/typography.ts +24 -0
- package/plugins/paseo/test/markdown-core.test.ts +75 -0
- package/src/boot/text.ts +6 -10
- package/src/history/claude.ts +31 -4
- package/src/history/prefilter.ts +13 -9
- package/src/notes/address.ts +1 -1
- package/src/notes/policy.ts +1 -1
- package/src/tools/dream.ts +5 -5
- package/src/tools/history.ts +12 -14
- package/src/tools/notes.ts +35 -33
- package/src/tools/result.ts +2 -2
- package/src/tools/schema.ts +2 -2
package/src/history/claude.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
/** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
|
|
2
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
3
4
|
import { isDeepStrictEqual } from "node:util";
|
|
4
5
|
import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
|
|
5
6
|
|
|
7
|
+
class UnpersistedClaudeHead extends Error {
|
|
8
|
+
constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
|
|
9
|
+
}
|
|
10
|
+
|
|
6
11
|
type Row = Record<string, unknown>;
|
|
7
12
|
type WindowPosition = { ordinal: number } | { unknownAncestor: string };
|
|
8
13
|
type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; position?: WindowPosition };
|
|
@@ -180,7 +185,7 @@ function claudeHistoryFromRows(rows: Row[], source: Omit<ClaudeHistorySource, "t
|
|
|
180
185
|
return version.position!;
|
|
181
186
|
}
|
|
182
187
|
if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
|
|
183
|
-
if (!nodes.has(source.headUuid)) throw new
|
|
188
|
+
if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
|
|
184
189
|
|
|
185
190
|
// The inference tree uses the latest rewritten parents. At a compact boundary the logical
|
|
186
191
|
// parent and preserved segments use ORIGINAL ancestry: the old context is still history.
|
|
@@ -299,7 +304,29 @@ export function offlineClaudeHistoryFromJsonl(text: string, sessionId: string):
|
|
|
299
304
|
return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
|
|
300
305
|
}
|
|
301
306
|
|
|
302
|
-
export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
|
|
307
|
+
export async function readClaudeHistory(source: ClaudeHistorySource, { waitForHead = false } = {}): Promise<ClaudeHistoryProjection> {
|
|
303
308
|
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
|
|
304
|
-
|
|
309
|
+
const snapshot = { ...source };
|
|
310
|
+
const read = async () => claudeHistoryFromJsonl(await readFile(snapshot.transcriptPath, "utf8"), snapshot);
|
|
311
|
+
if (!waitForHead || !snapshot.headUuid) return read();
|
|
312
|
+
const revision = async () => {
|
|
313
|
+
const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot.transcriptPath, { bigint: true });
|
|
314
|
+
return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
|
|
315
|
+
};
|
|
316
|
+
let seen = await revision();
|
|
317
|
+
try { return await read(); }
|
|
318
|
+
catch (error) {
|
|
319
|
+
if (!(error instanceof UnpersistedClaudeHead)) throw error;
|
|
320
|
+
// A kept append can reach the tool before its disk write. Only retry that same
|
|
321
|
+
// head, and only reparse on file changes. Never fall back to an offline leaf.
|
|
322
|
+
for (const delay of [50, 100, 200, 300, 350]) {
|
|
323
|
+
await sleep(delay);
|
|
324
|
+
const current = await revision();
|
|
325
|
+
if (current === seen) continue;
|
|
326
|
+
seen = current;
|
|
327
|
+
try { return await read(); }
|
|
328
|
+
catch (retry) { if (!(retry instanceof UnpersistedClaudeHead)) throw retry; }
|
|
329
|
+
}
|
|
330
|
+
throw error;
|
|
331
|
+
}
|
|
305
332
|
}
|
package/src/history/prefilter.ts
CHANGED
|
@@ -13,7 +13,7 @@ const PRESENTATION = `Codex unknown arguments not recorded output nested calls c
|
|
|
13
13
|
FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
|
|
14
14
|
the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
|
|
15
15
|
const HISTORY_BASE = '"history_base"';
|
|
16
|
-
export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
|
|
16
|
+
export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean, stopOnHit?: boolean) => Promise<boolean>;
|
|
17
17
|
|
|
18
18
|
/** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
|
|
19
19
|
export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter {
|
|
@@ -27,7 +27,7 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
|
|
|
27
27
|
}));
|
|
28
28
|
// No safe tokens (or generated text alone) cannot prove a miss.
|
|
29
29
|
const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
|
|
30
|
-
return async (chunks, codex = false) => {
|
|
30
|
+
return async (chunks, codex = false, stopOnHit = false) => {
|
|
31
31
|
const decoder = new StringDecoder("utf8");
|
|
32
32
|
const seen = alternatives.map((tokens) => tokens.map(() => false));
|
|
33
33
|
let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
|
|
@@ -55,7 +55,10 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
|
|
|
55
55
|
rawTail = raw.slice(-overlap);
|
|
56
56
|
normalizedTail = normalized.slice(-overlap);
|
|
57
57
|
};
|
|
58
|
-
for await (const chunk of chunks)
|
|
58
|
+
for await (const chunk of chunks) {
|
|
59
|
+
if (!possible) scan(decoder.write(chunk));
|
|
60
|
+
if (possible && stopOnHit) return true;
|
|
61
|
+
}
|
|
59
62
|
if (!possible) scan(decoder.end(), true);
|
|
60
63
|
return possible;
|
|
61
64
|
};
|
|
@@ -63,12 +66,13 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
|
|
|
63
66
|
|
|
64
67
|
/** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
|
|
65
68
|
export async function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity): Promise<boolean> {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
69
|
+
// Plain Pi/Claude files will be read and validated by the strict decoder on a possible
|
|
70
|
+
// hit. Don't drain a potentially huge file just to read it from the beginning again.
|
|
71
|
+
if (!codex) return prefilter(createReadStream(path), false, true);
|
|
72
|
+
const info = await stat(path);
|
|
73
|
+
if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
74
|
+
// Native Codex compression is zstd; scan through EOF to enforce the decoded size limit.
|
|
75
|
+
const compressed = path.endsWith(".jsonl.zst");
|
|
72
76
|
if (compressed && typeof zlib.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
|
|
73
77
|
const input = createReadStream(path);
|
|
74
78
|
const consume = async (chunks: AsyncIterable<Buffer>) => {
|
package/src/notes/address.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { assertVirtualPath, isSessionId, SLUG_PATTERN, type Scope } from "./path
|
|
|
4
4
|
|
|
5
5
|
export type NoteAddress = { scope: Scope; path: string; who?: string };
|
|
6
6
|
|
|
7
|
-
export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path
|
|
7
|
+
export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path>, @sessions/<id>/<path>, @agents/<name>/<path>, and @models/<name>/<path> read named notebooks.";
|
|
8
8
|
|
|
9
9
|
/** The one namespace-head vocabulary: the scope each public `@head` names, and the directory family a head with `dir` lists. */
|
|
10
10
|
export const NAMESPACE_HEADS: ReadonlyMap<string, { readonly scope: Scope; readonly dir?: "sessions" | "project" | "agents" | "models" }> = new Map([
|
package/src/notes/policy.ts
CHANGED
|
@@ -34,7 +34,7 @@ export function pinnedPageOrder(path: string): number {
|
|
|
34
34
|
|
|
35
35
|
export function noteBudgetWarnings(body: string, policy: NotePolicy): string[] {
|
|
36
36
|
const count = Array.from(body).length;
|
|
37
|
-
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}
|
|
37
|
+
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} — boil it down.`] : [];
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
export function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void {
|
package/src/tools/dream.ts
CHANGED
|
@@ -53,7 +53,7 @@ export function dreamingIdentity(identity: NotesIdentity, state: DreamState): No
|
|
|
53
53
|
const NOT_DREAMING = "No dream is open; call dream_begin first.";
|
|
54
54
|
|
|
55
55
|
export const dreamBeginParameters = Type.Object({
|
|
56
|
-
project: Type.Optional(Type.String({ description: "
|
|
56
|
+
project: Type.Optional(Type.String({ description: "Which project's pages; leave it out for this one." })),
|
|
57
57
|
}, { additionalProperties: false });
|
|
58
58
|
|
|
59
59
|
export const DreamBeginDataSchema = Type.Object({
|
|
@@ -69,7 +69,7 @@ function renderBeginData(data: DreamBeginData): string {
|
|
|
69
69
|
|
|
70
70
|
export const dreamBegin = {
|
|
71
71
|
name: "dream_begin", label: "Dream begin",
|
|
72
|
-
description: "
|
|
72
|
+
description: "Spread one project's pages across the table — its project shelf, every session page born there, crumpled balls included. Until `dream_end` your pen works on all of them; other sessions' pages can be rewritten, not added to.",
|
|
73
73
|
parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
|
|
74
74
|
async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
|
|
75
75
|
if (state.project !== undefined || state.pending !== undefined) {
|
|
@@ -123,13 +123,13 @@ export const dreamBegin = {
|
|
|
123
123
|
render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
|
|
124
124
|
} as const;
|
|
125
125
|
|
|
126
|
-
export const dreamForgetParameters = Type.Object({ address: Type.String() }, { additionalProperties: false });
|
|
126
|
+
export const dreamForgetParameters = Type.Object({ address: Type.String({ description: "Which crumpled page goes in the bin." }) }, { additionalProperties: false });
|
|
127
127
|
export const DreamForgetDataSchema = Type.Object({ ...NoteIdentitySchema }, { additionalProperties: false });
|
|
128
128
|
export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
|
|
129
129
|
|
|
130
130
|
export const dreamForget = {
|
|
131
131
|
name: "dream_forget", label: "Dream forget",
|
|
132
|
-
description: "
|
|
132
|
+
description: "Throw a crumpled page in the bin for good. Only crumpled pages go.",
|
|
133
133
|
parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
|
|
134
134
|
async execute(params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamForgetData>> {
|
|
135
135
|
if (state.project === undefined) return failure("not_dreaming", NOT_DREAMING);
|
|
@@ -148,7 +148,7 @@ export type DreamEndData = Static<typeof DreamEndDataSchema>;
|
|
|
148
148
|
|
|
149
149
|
export const dreamEnd = {
|
|
150
150
|
name: "dream_end", label: "Dream end",
|
|
151
|
-
description: "
|
|
151
|
+
description: "Stack the pages, file them, close the drawer.",
|
|
152
152
|
parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
|
|
153
153
|
async execute(_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamEndData>> {
|
|
154
154
|
const project = state.project;
|
package/src/tools/history.ts
CHANGED
|
@@ -92,25 +92,23 @@ function pageOutcome(result: HistoryPageResult): Outcome<HistoryPage> {
|
|
|
92
92
|
|
|
93
93
|
/* ------------------------------------------------------------------ history_list */
|
|
94
94
|
|
|
95
|
-
const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
|
|
96
|
-
|
|
97
95
|
export const historyListParameters = Type.Object({
|
|
98
|
-
session:
|
|
99
|
-
query: Type.Optional(searchQuery("
|
|
96
|
+
session: Type.Optional(Type.String({ minLength: 1, description: "Whose record: a session ID or prefix (pi:, claude:, codex:, dsh: allowed). Leave it out for this one. `*` means every recent session." })),
|
|
97
|
+
query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
|
|
100
98
|
roles: historyRoles(),
|
|
101
|
-
before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
102
|
-
after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "
|
|
103
|
-
since: Type.Optional(Type.String({ minLength: 1, description: "
|
|
104
|
-
until: Type.Optional(Type.String({ minLength: 1, description: "
|
|
105
|
-
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "
|
|
106
|
-
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "
|
|
107
|
-
max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description:
|
|
99
|
+
before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "Only entries before this seq." })),
|
|
100
|
+
after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
|
|
101
|
+
since: Type.Optional(Type.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
|
|
102
|
+
until: Type.Optional(Type.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
|
|
103
|
+
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "Which end `limit` counts from: newest or oldest. Entries still read oldest first." })),
|
|
104
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
|
|
105
|
+
max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." })),
|
|
108
106
|
}, { additionalProperties: false });
|
|
109
107
|
|
|
110
108
|
export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]> = {
|
|
111
109
|
name: "history_list",
|
|
112
110
|
label: "History list items",
|
|
113
|
-
description: "
|
|
111
|
+
description: "Flip back through the record, a page at a time. Another session: its ID. `*` pulls every recent session off the shelf; add `query` to search them.",
|
|
114
112
|
parameters: historyListParameters,
|
|
115
113
|
outputSchema: resultSchema(HistoryPageSchema),
|
|
116
114
|
async execute(params, context, wrapText = plainText) {
|
|
@@ -162,12 +160,12 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
162
160
|
|
|
163
161
|
/* ------------------------------------------------------------------ history_read */
|
|
164
162
|
|
|
165
|
-
export const historyReadParameters = Type.Object({ session:
|
|
163
|
+
export const historyReadParameters = Type.Object({ session: Type.Optional(Type.String({ minLength: 1, description: "Whose record: a session ID or prefix. Leave it out for this one." })), seq: Type.Integer({ minimum: 1, description: "Which entry, by its seq from `history_list`; bring its session along if it had one." }), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
166
164
|
|
|
167
165
|
export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryContext, HistoryTextWrapper?]> = {
|
|
168
166
|
name: "history_read",
|
|
169
167
|
label: "History read item",
|
|
170
|
-
description: "
|
|
168
|
+
description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
|
|
171
169
|
parameters: historyReadParameters,
|
|
172
170
|
outputSchema: resultSchema(HistoryReadDataSchema),
|
|
173
171
|
async execute(params, context, wrapText = plainText) {
|
package/src/tools/notes.ts
CHANGED
|
@@ -15,12 +15,12 @@ import { notesIdentityForCall, type NotesToolContext } from "./notes-context.js"
|
|
|
15
15
|
|
|
16
16
|
const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
|
|
17
17
|
const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
|
|
18
|
-
description: "
|
|
18
|
+
description: "Whose handwriting: user, self, or external. Leave it out to keep what's there.",
|
|
19
19
|
}));
|
|
20
20
|
const POLICY_PARAMETERS = {
|
|
21
|
-
pinned: Type.Optional(Type.Boolean({ description: "
|
|
22
|
-
budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "
|
|
23
|
-
readonly: Type.Optional(Type.Boolean({ description: "
|
|
21
|
+
pinned: Type.Optional(Type.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET and MAP included." })),
|
|
22
|
+
budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "How much paper the page gets. Writing past it still saves, with a warning. A page over budget gets boiled down: stale lines out, repeats merged, the rest said shorter. More paper is for a page already boiled down that still needs the room." })),
|
|
23
|
+
readonly: Type.Optional(Type.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off — same call is fine." })),
|
|
24
24
|
};
|
|
25
25
|
const PolicySchema = {
|
|
26
26
|
pinned: Type.Boolean(), budget: Type.Integer(), readonly: Type.Boolean(),
|
|
@@ -36,13 +36,12 @@ function withWarnings(text: string, data: { warnings: string[] }): string {
|
|
|
36
36
|
return [text, ...data.warnings].join("\n");
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "
|
|
40
|
-
const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "
|
|
41
|
-
const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
42
|
-
const GLOB_PARAMETER = nullableString("
|
|
43
|
-
const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "
|
|
44
|
-
const
|
|
45
|
-
const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable notebooks; `@projects/<name>/<path>` and `@sessions/<id>/<path>` read named project and session notes (read-only). Not file paths: never pass them to file tools.";
|
|
39
|
+
const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "`true` balls the page up: gone from list and search, still readable. `false` smooths it flat again." }));
|
|
40
|
+
const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "Only the crumpled balls." }));
|
|
41
|
+
const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "How many pages at most." }));
|
|
42
|
+
const GLOB_PARAMETER = nullableString("Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf · `MAP.md` that page in every notebook · `**` everything · `@sessions/*/**` every session.");
|
|
43
|
+
const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
|
|
44
|
+
const ADDRESS_PARAMETER = Type.String({ description: "Which drawer the page sits in. `plan.md` — this session's desk, cleared when it ends. `@project/` this project's shelf · `@human/` your human's file · `@self/` your own notebook · `@model/` your brain's. `@projects/<name>/`, `@sessions/<id>/`, `@agents/<name>/`, `@models/<name>/` — someone else's shelf: read only. Paper, not files: hand one to read/write/edit/bash and a real `@project` folder is born." });
|
|
46
45
|
|
|
47
46
|
/**
|
|
48
47
|
* Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
|
|
@@ -158,7 +157,7 @@ const MatchSchema = Type.Object({
|
|
|
158
157
|
|
|
159
158
|
const SearchedFileSchema = Type.Object({
|
|
160
159
|
...ListedFileSchema.properties,
|
|
161
|
-
matches: Type.Array(MatchSchema),
|
|
160
|
+
matches: Type.Array(MatchSchema), more_matches: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
162
161
|
}, { additionalProperties: false });
|
|
163
162
|
|
|
164
163
|
export const SnapshotSchema = {
|
|
@@ -238,7 +237,7 @@ export function listedFile(row: Pick<NoteRow, "address" | "meta"> & { body?: str
|
|
|
238
237
|
return { ...noteIdentity(identity, row.address), ...policy, warnings: row.warnings ?? (row.body === undefined ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
|
|
239
238
|
}
|
|
240
239
|
|
|
241
|
-
export const notesWriteParameters = Type.Object({ address:
|
|
240
|
+
export const notesWriteParameters = Type.Object({ address: ADDRESS_PARAMETER, content: Type.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
242
241
|
|
|
243
242
|
function renderWriteData(data: NotesWriteData): string {
|
|
244
243
|
return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
|
|
@@ -246,7 +245,7 @@ function renderWriteData(data: NotesWriteData): string {
|
|
|
246
245
|
|
|
247
246
|
export const notesWrite = {
|
|
248
247
|
name: "notes_write", label: "Notes write",
|
|
249
|
-
description:
|
|
248
|
+
description: "Take a fresh page and write it — or rip out the old one and write it again. Title it for what's inside and when you'll reach for it.",
|
|
250
249
|
parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
|
|
251
250
|
async execute(params: Static<typeof notesWriteParameters>, context: NotesToolContext): Promise<Outcome<NotesWriteData>> {
|
|
252
251
|
try {
|
|
@@ -259,13 +258,13 @@ export const notesWrite = {
|
|
|
259
258
|
} as const;
|
|
260
259
|
|
|
261
260
|
export const notesUpdateParameters = Type.Object({
|
|
262
|
-
address:
|
|
263
|
-
edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
|
|
261
|
+
address: ADDRESS_PARAMETER,
|
|
262
|
+
edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String({ description: "The passage as it stands on the page." }), newText: Type.String({ description: "What goes in its place." }) }, { additionalProperties: false }), { description: "Pen strokes, in order. Each `oldText` is the exact passage — same case, found once — and `newText` is what goes in its place." })),
|
|
264
263
|
origin: ORIGIN,
|
|
265
264
|
...POLICY_PARAMETERS,
|
|
266
265
|
crumpled: CRUMPLED_PARAMETER,
|
|
267
|
-
replace_all: Type.Optional(Type.Boolean({ description: "
|
|
268
|
-
rename_to: Type.Optional(Type.String({ description: "
|
|
266
|
+
replace_all: Type.Optional(Type.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
|
|
267
|
+
rename_to: Type.Optional(Type.String({ description: "Move the page to another address. Never lands on top of a live page; nothing pointing at it follows." })),
|
|
269
268
|
cwd: CWD_PARAMETER,
|
|
270
269
|
}, { additionalProperties: false });
|
|
271
270
|
|
|
@@ -278,7 +277,7 @@ function renderUpdateData(data: NotesUpdateData): string {
|
|
|
278
277
|
|
|
279
278
|
export const notesUpdate = {
|
|
280
279
|
name: "notes_update", label: "Notes update",
|
|
281
|
-
description:
|
|
280
|
+
description: "Work on a page you already have: cross out and rewrite lines, move it, pin it, lock it, give it more paper, crumple it. Keep every page true to now: wrong, stale, or no-longer-mattering lines get rewritten or struck where they stand. The page stays one page.",
|
|
282
281
|
parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
|
|
283
282
|
async execute(params: Static<typeof notesUpdateParameters>, context: NotesToolContext, onChange?: (change: NoteChange) => void): Promise<Outcome<NotesUpdateData>> {
|
|
284
283
|
try {
|
|
@@ -296,7 +295,7 @@ export const notesUpdate = {
|
|
|
296
295
|
render: (result: Outcome<NotesUpdateData>): string => renderOutcome(result, renderUpdateData),
|
|
297
296
|
} as const;
|
|
298
297
|
|
|
299
|
-
export const notesReadParameters = Type.Object({ address:
|
|
298
|
+
export const notesReadParameters = Type.Object({ address: ADDRESS_PARAMETER, ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
300
299
|
|
|
301
300
|
function renderReadData(data: NotesReadData): string {
|
|
302
301
|
return withWarnings(`${renderIdentity(data)}\n${renderMetadata(data.metadata)}`, data) + `\n\n${renderTextWindow(data)}`;
|
|
@@ -304,7 +303,7 @@ function renderReadData(data: NotesReadData): string {
|
|
|
304
303
|
|
|
305
304
|
export const notesRead = {
|
|
306
305
|
name: "notes_read", label: "Notes read",
|
|
307
|
-
description:
|
|
306
|
+
description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
|
|
308
307
|
parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
|
|
309
308
|
async execute(params: Static<typeof notesReadParameters>, context: NotesToolContext): Promise<Outcome<NotesReadData>> {
|
|
310
309
|
try {
|
|
@@ -337,7 +336,7 @@ export function renderListData(data: Snapshot<NotesListData["files"][number] & {
|
|
|
337
336
|
|
|
338
337
|
export const notesList = {
|
|
339
338
|
name: "notes_list", label: "Notes list",
|
|
340
|
-
description:
|
|
339
|
+
description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile — narrow `glob`.",
|
|
341
340
|
parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
|
|
342
341
|
async execute(params: Static<typeof notesListParameters>, context: NotesToolContext): Promise<Outcome<NotesListData>> {
|
|
343
342
|
try {
|
|
@@ -349,12 +348,12 @@ export const notesList = {
|
|
|
349
348
|
render: (result: Outcome<NotesListData>): string => renderOutcome(result, renderListData),
|
|
350
349
|
} as const;
|
|
351
350
|
|
|
352
|
-
export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
351
|
+
export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "How many hit lines per page at most." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
353
352
|
|
|
354
353
|
function renderSearchData(data: NotesSearchData): string {
|
|
355
354
|
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
356
355
|
for (const file of data.files) {
|
|
357
|
-
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
|
|
356
|
+
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
|
|
358
357
|
lines.push(...file.warnings.map(warning => ` ${warning}`));
|
|
359
358
|
for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
|
|
360
359
|
}
|
|
@@ -364,6 +363,10 @@ function renderSearchData(data: NotesSearchData): string {
|
|
|
364
363
|
}
|
|
365
364
|
|
|
366
365
|
type SearchFile = NotesSearchData["files"][number];
|
|
366
|
+
function keepMatches(file: SearchFile, count = file.matches.length): SearchFile {
|
|
367
|
+
const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
|
|
368
|
+
return { ...file, matches: file.matches.slice(0, count), ...(more ? { more_matches: more } : {}) };
|
|
369
|
+
}
|
|
367
370
|
|
|
368
371
|
/** A shortened match line still ends with a marker, so its own text says it was cut. */
|
|
369
372
|
export const MATCH_SHORTENED_MARKER = " [truncated]";
|
|
@@ -374,28 +377,27 @@ function fitSearchFile(file: SearchFile, fits: (candidate: SearchFile) => boolea
|
|
|
374
377
|
let high = file.matches.length;
|
|
375
378
|
while (low < high) {
|
|
376
379
|
const mid = Math.ceil((low + high) / 2);
|
|
377
|
-
if (fits(
|
|
380
|
+
if (fits(keepMatches(file, mid))) low = mid;
|
|
378
381
|
else high = mid - 1;
|
|
379
382
|
}
|
|
380
|
-
if (low > 0
|
|
381
|
-
const first = file.matches[0]
|
|
382
|
-
|
|
383
|
-
const withText = (text: string): SearchFile => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
383
|
+
if (low > 0 || file.matches.length === 0) return keepMatches(file, low);
|
|
384
|
+
const first = file.matches[0]!;
|
|
385
|
+
const withText = (text: string): SearchFile => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
384
386
|
return withText(prefixFit(first.text, text => fits(withText(text))));
|
|
385
387
|
}
|
|
386
388
|
|
|
387
389
|
export const notesSearch = {
|
|
388
390
|
name: "notes_search", label: "Notes search",
|
|
389
|
-
description:
|
|
391
|
+
description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile — narrow `glob`.",
|
|
390
392
|
parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
|
|
391
393
|
async execute(params: Static<typeof notesSearchParameters>, context: NotesToolContext): Promise<Outcome<NotesSearchData>> {
|
|
392
394
|
try {
|
|
393
395
|
const identity = notesIdentityForCall(context, params.cwd);
|
|
394
396
|
const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
|
|
395
|
-
const files
|
|
397
|
+
const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => keepMatches({
|
|
396
398
|
...listedFile(row, identity),
|
|
397
|
-
matches: row.matches.
|
|
398
|
-
}));
|
|
399
|
+
matches: row.matches.map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
|
|
400
|
+
}, params.max_matches_per_file));
|
|
399
401
|
return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
|
|
400
402
|
} catch (error) { return failureOf(error); }
|
|
401
403
|
},
|
package/src/tools/result.ts
CHANGED
|
@@ -50,8 +50,8 @@ export type TextWindow = Static<typeof TextWindowSchema>;
|
|
|
50
50
|
* because `readTextWindow` already owns the defaults.
|
|
51
51
|
*/
|
|
52
52
|
export const TextWindowRequestSchema = {
|
|
53
|
-
offset_chars: Type.Optional(Type.Integer({ description: "
|
|
54
|
-
max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description:
|
|
53
|
+
offset_chars: Type.Optional(Type.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
|
|
54
|
+
max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." })),
|
|
55
55
|
};
|
|
56
56
|
|
|
57
57
|
/**
|
package/src/tools/schema.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { Type, type TSchema } from "typebox";
|
|
|
2
2
|
import { Errors } from "typebox/value";
|
|
3
3
|
import { HistoryRoleSchema } from "../history/history.js";
|
|
4
4
|
export const nullableString = (description?: string) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
|
|
5
|
-
export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "
|
|
5
|
+
export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "Only these voices: user, assistant, tool, context. Without roles or query, tool and context runs fold into one line." }));
|
|
6
6
|
|
|
7
7
|
/** First parameter violation; skip false subschemas so additionalProperties can name the field. */
|
|
8
8
|
export function paramProblem(schema: TSchema, params: unknown): string {
|
|
@@ -14,4 +14,4 @@ export function paramProblem(schema: TSchema, params: unknown): string {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
/** Search query parameter: one literal, or several literals combined with OR. */
|
|
17
|
-
export const searchQuery = (description = "
|
|
17
|
+
export const searchQuery = (description = "Text to look for, or a list (any match). Leave it out to just list the pages.") => Type.Union([Type.String(), Type.Array(Type.String())], { description });
|