notesoup 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +94 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +17 -0
- package/dist/src/boot/text.js +48 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +156 -0
- package/dist/src/history/history.js +212 -0
- package/dist/src/history/query.d.ts +63 -0
- package/dist/src/history/query.js +201 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +103 -0
- package/dist/src/notes/store.js +474 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +9 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +7 -0
- package/dist/src/pi/tool-names.js +7 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +58 -0
- package/dist/src/tools/history.js +210 -0
- package/dist/src/tools/notes.d.ts +250 -0
- package/dist/src/tools/notes.js +360 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +82 -0
- package/dist/src/tools/result.js +104 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +367 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +633 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +274 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +515 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +530 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +78 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9265 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +240 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +58 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +286 -0
- package/src/history/query.ts +222 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +494 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +11 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +9 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +234 -0
- package/src/tools/notes.ts +381 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +144 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import type { NotesIdentity } from "../notes/identity.js";
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
import { localIso } from "../notes/frontmatter.js";
|
|
4
|
+
import { isFilesystemError } from "../notes/fs-error.js";
|
|
5
|
+
import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow, type Scope } from "../notes/index.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
|
+
import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
|
|
9
|
+
|
|
10
|
+
const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
|
|
11
|
+
const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
|
|
12
|
+
description: "(optional, default self) Who wrote it: user, self, or external.",
|
|
13
|
+
}));
|
|
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.";
|
|
19
|
+
|
|
20
|
+
/** The one receipt field a caller cannot derive from the address itself. */
|
|
21
|
+
function projectKeyField(scope: Scope, projectKey: string): { project_key?: string } {
|
|
22
|
+
return scope === "project" ? { project_key: projectKey } : {};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
|
|
27
|
+
* Convert expected refusals; unexpected errors propagate unchanged.
|
|
28
|
+
*/
|
|
29
|
+
function failureOf(error: unknown): Outcome<never> {
|
|
30
|
+
if (error instanceof NoteError) return failure(error.code, error.message);
|
|
31
|
+
// Address, glob, and query guards raise declared types; nothing else is converted.
|
|
32
|
+
if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
|
|
33
|
+
if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function byRecent<T extends { address: string; meta: { updatedAt: number } }>(a: T, b: T): number {
|
|
38
|
+
return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
|
|
42
|
+
const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
|
|
43
|
+
/** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
|
|
44
|
+
export const MAX_METADATA_ENTRY_BYTES = 1024;
|
|
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]";
|
|
48
|
+
|
|
49
|
+
/** Include the key: hand-written frontmatter can have arbitrarily long keys. */
|
|
50
|
+
function extraEntryBytes(key: string, value: unknown): number {
|
|
51
|
+
return structuredBytes(key) + 1 + structuredBytes(value);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const NoteMetadataSchema = Type.Object({
|
|
55
|
+
origin: Type.Union([...ORIGIN_VALUES]),
|
|
56
|
+
created_at: Type.String(),
|
|
57
|
+
updated_at: Type.String(),
|
|
58
|
+
crumpled_at: Type.Optional(Type.String()),
|
|
59
|
+
project: Type.Optional(Type.String()),
|
|
60
|
+
extra: Type.Record(Type.String(), Type.Unknown()),
|
|
61
|
+
}, { additionalProperties: false });
|
|
62
|
+
export type NoteMetadata = Static<typeof NoteMetadataSchema>;
|
|
63
|
+
|
|
64
|
+
/** Normalize known metadata and bound extras, naming an oversized value instead of hiding it. */
|
|
65
|
+
function noteMetadata(meta: NoteMeta): NoteMetadata {
|
|
66
|
+
const extra: Record<string, unknown> = {};
|
|
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
|
+
};
|
|
72
|
+
for (const [key, value] of Object.entries(meta)) {
|
|
73
|
+
if (NORMALIZED_META_KEYS.has(key) || value === undefined) continue;
|
|
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);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
verbatimBytes += entryBytes;
|
|
82
|
+
put(key, value);
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
origin: meta.origin,
|
|
86
|
+
created_at: localIso(meta.createdAt),
|
|
87
|
+
updated_at: localIso(meta.updatedAt),
|
|
88
|
+
...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
|
|
89
|
+
...(typeof meta.project === "string" ? { project: meta.project } : {}),
|
|
90
|
+
extra,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function renderMetadata(metadata: NoteMetadata): string {
|
|
95
|
+
const fields = [
|
|
96
|
+
`origin ${metadata.origin}`,
|
|
97
|
+
`created ${metadata.created_at}`,
|
|
98
|
+
`updated ${metadata.updated_at}`,
|
|
99
|
+
...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
|
|
100
|
+
...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
|
|
101
|
+
];
|
|
102
|
+
const extra = Object.keys(metadata.extra);
|
|
103
|
+
if (extra.length > 0) fields.push(`extra ${JSON.stringify(metadata.extra)}`);
|
|
104
|
+
return fields.join(" | ");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Address plus project key in one line; the project key never replaces the address. */
|
|
108
|
+
function renderIdentity(identity: { address: string; project_key?: string }): string {
|
|
109
|
+
return identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const ListedFileSchema = Type.Object({
|
|
113
|
+
address: Type.String(),
|
|
114
|
+
project_key: Type.Optional(Type.String()),
|
|
115
|
+
updated_at: Type.String(),
|
|
116
|
+
crumpled_at: Type.Optional(Type.String()),
|
|
117
|
+
}, { additionalProperties: false });
|
|
118
|
+
|
|
119
|
+
const MatchSchema = Type.Object({
|
|
120
|
+
line: Type.Integer(),
|
|
121
|
+
text: Type.String(),
|
|
122
|
+
offset_chars: Type.Integer(),
|
|
123
|
+
}, { additionalProperties: false });
|
|
124
|
+
|
|
125
|
+
const SearchedFileSchema = Type.Object({
|
|
126
|
+
...ListedFileSchema.properties,
|
|
127
|
+
matches: Type.Array(MatchSchema),
|
|
128
|
+
}, { additionalProperties: false });
|
|
129
|
+
|
|
130
|
+
const SnapshotSchema = {
|
|
131
|
+
more: Type.Integer({ description: "How many more were left out." }),
|
|
132
|
+
homes_unavailable: Type.Array(Type.String()),
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
export const NotesWriteDataSchema = Type.Object({
|
|
136
|
+
address: Type.String(),
|
|
137
|
+
project_key: Type.Optional(Type.String()),
|
|
138
|
+
outcome: Type.Union([Type.Literal("created"), Type.Literal("overwrote"), Type.Literal("uncrumpled")]),
|
|
139
|
+
}, { additionalProperties: false });
|
|
140
|
+
export type NotesWriteData = Static<typeof NotesWriteDataSchema>;
|
|
141
|
+
|
|
142
|
+
export const NotesUpdateDataSchema = Type.Object({
|
|
143
|
+
address: Type.String(),
|
|
144
|
+
project_key: Type.Optional(Type.String()),
|
|
145
|
+
change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("moved")]),
|
|
146
|
+
diff: Type.String(),
|
|
147
|
+
rename_from: Type.Optional(Type.String()),
|
|
148
|
+
}, { additionalProperties: false });
|
|
149
|
+
export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
|
|
150
|
+
|
|
151
|
+
export const NotesReadDataSchema = Type.Object({
|
|
152
|
+
address: Type.String(),
|
|
153
|
+
project_key: Type.Optional(Type.String()),
|
|
154
|
+
metadata: NoteMetadataSchema,
|
|
155
|
+
...TextWindowSchema.properties,
|
|
156
|
+
}, { additionalProperties: false });
|
|
157
|
+
export type NotesReadData = Static<typeof NotesReadDataSchema>;
|
|
158
|
+
|
|
159
|
+
export const NotesListDataSchema = Type.Object({
|
|
160
|
+
files: Type.Array(ListedFileSchema),
|
|
161
|
+
...SnapshotSchema,
|
|
162
|
+
}, { additionalProperties: false });
|
|
163
|
+
export type NotesListData = Static<typeof NotesListDataSchema>;
|
|
164
|
+
|
|
165
|
+
export const NotesSearchDataSchema = Type.Object({
|
|
166
|
+
files: Type.Array(SearchedFileSchema),
|
|
167
|
+
...SnapshotSchema,
|
|
168
|
+
}, { additionalProperties: false });
|
|
169
|
+
export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
|
|
170
|
+
|
|
171
|
+
type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
|
|
172
|
+
|
|
173
|
+
/** Keep identities intact. Only search previews may shrink to make the first row fit. */
|
|
174
|
+
function snapshot<T>(
|
|
175
|
+
rows: T[],
|
|
176
|
+
limit: number | undefined,
|
|
177
|
+
status: NoteQueryStatus,
|
|
178
|
+
renderData: (data: Snapshot<T>) => string,
|
|
179
|
+
shrink?: (item: T, fits: (candidate: T) => boolean) => T,
|
|
180
|
+
): Outcome<Snapshot<T>> {
|
|
181
|
+
const files: T[] = [];
|
|
182
|
+
const data = (selected: T[]): Snapshot<T> => ({ files: selected, more: rows.length - selected.length, homes_unavailable: status.homesUnavailable });
|
|
183
|
+
const render = (outcome: Outcome<Snapshot<T>>) => renderOutcome(outcome, renderData);
|
|
184
|
+
const fits = (item: T) => fitsResult(success(data([...files, item])), render);
|
|
185
|
+
for (const item of rows.slice(0, limit)) {
|
|
186
|
+
if (fits(item)) {
|
|
187
|
+
files.push(item);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (files.length === 0 && shrink) {
|
|
191
|
+
const reduced = shrink(item, fits);
|
|
192
|
+
if (fits(reduced)) files.push(reduced);
|
|
193
|
+
}
|
|
194
|
+
if (files.length === 0) return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
const outcome = success(data(files));
|
|
198
|
+
return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function listedFile(row: Pick<NoteRow, "address" | "scope" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
|
|
202
|
+
return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
|
|
206
|
+
|
|
207
|
+
function renderWriteData(data: NotesWriteData): string {
|
|
208
|
+
return `${data.outcome} ${renderIdentity(data)}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export const notesWrite = {
|
|
212
|
+
name: "notes_write", label: "Notes write",
|
|
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}`,
|
|
214
|
+
parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
|
|
215
|
+
async execute(params: Static<typeof notesWriteParameters>, identity: NotesIdentity): Promise<Outcome<NotesWriteData>> {
|
|
216
|
+
try {
|
|
217
|
+
const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin ?? "self" });
|
|
218
|
+
return success({ ...noteIdentity(identity, params.address), outcome });
|
|
219
|
+
} catch (error) { return failureOf(error); }
|
|
220
|
+
},
|
|
221
|
+
render: (result: Outcome<NotesWriteData>): string => renderOutcome(result, renderWriteData),
|
|
222
|
+
} as const;
|
|
223
|
+
|
|
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 });
|
|
232
|
+
|
|
233
|
+
function renderUpdateData(data: NotesUpdateData): string {
|
|
234
|
+
const head = data.rename_from === undefined
|
|
235
|
+
? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}`
|
|
236
|
+
: `moved ${data.rename_from} -> ${data.address}`;
|
|
237
|
+
const lines = [head];
|
|
238
|
+
if (data.diff.length > 0) lines.push("diff:", data.diff);
|
|
239
|
+
return lines.join("\n");
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function renderUpdate(result: Outcome<NotesUpdateData>): string {
|
|
243
|
+
return renderOutcome(result, renderUpdateData);
|
|
244
|
+
}
|
|
245
|
+
|
|
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. */
|
|
250
|
+
function boundedUpdate(data: NotesUpdateData): Outcome<NotesUpdateData> {
|
|
251
|
+
if (fitsResult(success(data), renderUpdate)) return success(data);
|
|
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}` });
|
|
255
|
+
return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export const notesUpdate = {
|
|
259
|
+
name: "notes_update", label: "Notes update",
|
|
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}`,
|
|
261
|
+
parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
|
|
262
|
+
async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string): Promise<Outcome<NotesUpdateData>> {
|
|
263
|
+
try {
|
|
264
|
+
const store = createNotesStore(identity);
|
|
265
|
+
// Empty filler is not a request: models that pass every parameter get the edit path.
|
|
266
|
+
const renameTo = params.rename_to === "" ? undefined : params.rename_to;
|
|
267
|
+
if (renameTo !== undefined) {
|
|
268
|
+
if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
|
|
269
|
+
return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
|
|
270
|
+
}
|
|
271
|
+
await store.rename(params.address, renameTo);
|
|
272
|
+
const from = noteIdentity(identity, params.address).address;
|
|
273
|
+
const to = noteIdentity(identity, renameTo);
|
|
274
|
+
return boundedUpdate({ ...to, rename_from: from, change_kind: "moved", diff: `rename ${from} -> ${to.address}` });
|
|
275
|
+
}
|
|
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) });
|
|
278
|
+
} catch (error) { return failureOf(error); }
|
|
279
|
+
},
|
|
280
|
+
render: renderUpdate,
|
|
281
|
+
} as const;
|
|
282
|
+
|
|
283
|
+
export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
284
|
+
|
|
285
|
+
function renderReadData(data: NotesReadData): string {
|
|
286
|
+
return `${renderIdentity(data)}\n${renderMetadata(data.metadata)}\n\n${renderTextWindow(data)}`;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export const notesRead = {
|
|
290
|
+
name: "notes_read", label: "Notes read",
|
|
291
|
+
description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
|
|
292
|
+
parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
|
|
293
|
+
async execute(params: Static<typeof notesReadParameters>, identity: NotesIdentity): Promise<Outcome<NotesReadData>> {
|
|
294
|
+
try {
|
|
295
|
+
const note = await createNotesStore(identity).read(params.address);
|
|
296
|
+
if (!note) return failure("not_found", "note not found");
|
|
297
|
+
const totalChars = Array.from(note.body).length;
|
|
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)`);
|
|
299
|
+
const resolved = noteIdentity(identity, params.address);
|
|
300
|
+
const metadata = noteMetadata(note.meta);
|
|
301
|
+
return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
|
|
302
|
+
} catch (error) { return failureOf(error); }
|
|
303
|
+
},
|
|
304
|
+
render: (result: Outcome<NotesReadData>): string => renderOutcome(result, renderReadData),
|
|
305
|
+
} as const;
|
|
306
|
+
|
|
307
|
+
export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
|
|
308
|
+
|
|
309
|
+
function renderListData(data: NotesListData): string {
|
|
310
|
+
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
311
|
+
for (const file of data.files) {
|
|
312
|
+
lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
|
|
313
|
+
}
|
|
314
|
+
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
|
|
315
|
+
for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
|
|
316
|
+
return lines.join("\n");
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export const notesList = {
|
|
320
|
+
name: "notes_list", label: "Notes list",
|
|
321
|
+
description: `List notes in this session and the four @ homes, newest first. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
|
|
322
|
+
parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
|
|
323
|
+
async execute(params: Static<typeof notesListParameters>, identity: NotesIdentity): Promise<Outcome<NotesListData>> {
|
|
324
|
+
try {
|
|
325
|
+
const { rows, status } = await createNotesStore(identity).listWithStatus({ glob: params.glob ?? undefined, crumpled: params.crumpled });
|
|
326
|
+
return snapshot(rows.map(row => listedFile(row, identity)), params.limit, status, renderListData);
|
|
327
|
+
} catch (error) { return failureOf(error); }
|
|
328
|
+
},
|
|
329
|
+
render: (result: Outcome<NotesListData>): string => renderOutcome(result, renderListData),
|
|
330
|
+
} as const;
|
|
331
|
+
|
|
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 });
|
|
333
|
+
|
|
334
|
+
function renderSearchData(data: NotesSearchData): string {
|
|
335
|
+
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
336
|
+
for (const file of data.files) {
|
|
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}`);
|
|
339
|
+
}
|
|
340
|
+
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
|
|
341
|
+
for (const home of data.homes_unavailable) lines.push(`${home} could not be read`);
|
|
342
|
+
return lines.join("\n");
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
type SearchFile = NotesSearchData["files"][number];
|
|
346
|
+
|
|
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. */
|
|
351
|
+
function fitSearchFile(file: SearchFile, fits: (candidate: SearchFile) => boolean): SearchFile {
|
|
352
|
+
let low = 0;
|
|
353
|
+
let high = file.matches.length;
|
|
354
|
+
while (low < high) {
|
|
355
|
+
const mid = Math.ceil((low + high) / 2);
|
|
356
|
+
if (fits({ ...file, matches: file.matches.slice(0, mid) })) low = mid;
|
|
357
|
+
else high = mid - 1;
|
|
358
|
+
}
|
|
359
|
+
if (low > 0) return { ...file, matches: file.matches.slice(0, low) };
|
|
360
|
+
const first = file.matches[0];
|
|
361
|
+
if (!first) return file;
|
|
362
|
+
const withText = (text: string): SearchFile => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
|
|
363
|
+
return withText(prefixFit(first.text, text => fits(withText(text))));
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export const notesSearch = {
|
|
367
|
+
name: "notes_search", label: "Notes search",
|
|
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}`,
|
|
369
|
+
parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
|
|
370
|
+
async execute(params: Static<typeof notesSearchParameters>, identity: NotesIdentity): Promise<Outcome<NotesSearchData>> {
|
|
371
|
+
try {
|
|
372
|
+
const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
|
|
373
|
+
const files: NotesSearchData["files"] = rows.sort(byRecent).map(row => ({
|
|
374
|
+
...listedFile(row, identity),
|
|
375
|
+
matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
|
|
376
|
+
}));
|
|
377
|
+
return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
|
|
378
|
+
} catch (error) { return failureOf(error); }
|
|
379
|
+
},
|
|
380
|
+
render: (result: Outcome<NotesSearchData>): string => renderOutcome(result, renderSearchData),
|
|
381
|
+
} as const;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
|
|
2
|
+
export { earliestMatchOffsetChars } from "../text-match.js";
|
|
3
|
+
|
|
4
|
+
export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
|
|
5
|
+
export const DEFAULT_READ_WINDOW_CHARS = 12000;
|
|
6
|
+
export const MAX_READ_WINDOW_CHARS = 50000;
|
|
7
|
+
export const HISTORY_PREVIEW_CHARS = 1200;
|
|
8
|
+
|
|
9
|
+
function json(value: unknown): string {
|
|
10
|
+
return JSON.stringify(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
|
|
14
|
+
export function withinTextBudget(text: string, budget = TOOL_OUTPUT_MAX_BYTES): boolean {
|
|
15
|
+
return Buffer.byteLength(text, "utf8") <= budget;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
|
|
19
|
+
export function prefixFit(text: string, fits: (content: string) => boolean): string {
|
|
20
|
+
if (fits(text)) return text;
|
|
21
|
+
const chars = Array.from(text);
|
|
22
|
+
// Serialized size is non-decreasing in the kept count, so the largest fitting prefix is
|
|
23
|
+
// found by a monotone binary search instead of a quadratic shrink loop.
|
|
24
|
+
let low = 0;
|
|
25
|
+
let high = chars.length;
|
|
26
|
+
while (low < high) {
|
|
27
|
+
const mid = Math.ceil((low + high) / 2);
|
|
28
|
+
if (fits(chars.slice(0, mid).join(""))) low = mid;
|
|
29
|
+
else high = mid - 1;
|
|
30
|
+
}
|
|
31
|
+
return chars.slice(0, low).join("");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Encode a structured result through the common tool result boundary. `details` is slim
|
|
36
|
+
* metadata for logs/UI (pi convention: never a second copy of the payload) and stays
|
|
37
|
+
* undefined unless the tool has metadata worth persisting.
|
|
38
|
+
*/
|
|
39
|
+
export function output(value: unknown, details?: unknown, terminate = false) {
|
|
40
|
+
return { content: [{ type: "text" as const, text: json(value) }], details, terminate };
|
|
41
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/** Internal outcomes, compact wire results, and bounded read windows. */
|
|
2
|
+
import { Type, type Static, type TSchema } from "typebox";
|
|
3
|
+
import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
|
|
4
|
+
|
|
5
|
+
/** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
|
|
6
|
+
export const OperationErrorSchema = Type.Object({
|
|
7
|
+
code: Type.String(),
|
|
8
|
+
message: Type.String(),
|
|
9
|
+
}, { additionalProperties: false });
|
|
10
|
+
export type OperationError = Static<typeof OperationErrorSchema>;
|
|
11
|
+
|
|
12
|
+
/** `data` exists without `error`, never both, never neither. */
|
|
13
|
+
export type Outcome<T> = { ok: true; data: T } | { ok: false; error: OperationError };
|
|
14
|
+
|
|
15
|
+
export function success<T>(data: T): Outcome<T> {
|
|
16
|
+
return { ok: true, data };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
|
|
20
|
+
export const ERROR_MESSAGE_MAX_CHARS = 2000;
|
|
21
|
+
|
|
22
|
+
function boundedMessage(message: string): string {
|
|
23
|
+
const chars = Array.from(message);
|
|
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]`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function failure(code: string, message: string): Outcome<never> {
|
|
28
|
+
return { ok: false, error: { code, message: boundedMessage(message) } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Public results have no success envelope. `error` is reserved for a refusal message. */
|
|
32
|
+
export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
|
|
33
|
+
export type WireError = Static<typeof WireErrorSchema>;
|
|
34
|
+
export type WireResult<T> = T | WireError;
|
|
35
|
+
|
|
36
|
+
export function wireResult<T>(result: Outcome<T>): WireResult<T> {
|
|
37
|
+
if (result.ok) return result.data;
|
|
38
|
+
const { code, message } = result.error;
|
|
39
|
+
return { error: message, code };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function resultSchema<S extends TSchema>(dataSchema: S) {
|
|
43
|
+
return Type.Union([dataSchema, WireErrorSchema]);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A refusal reads as one short line; a success is the operation's own reading of its data. */
|
|
47
|
+
export function renderOutcome<T>(result: Outcome<T>, renderData: (data: T) => string): string {
|
|
48
|
+
return result.ok ? renderData(result.data) : `error: ${result.error.code}: ${result.error.message}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
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. */
|
|
52
|
+
export function structuredBytes(value: unknown): number {
|
|
53
|
+
return Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The one bound: the rendered text and the structured payload must both fit, and the rendered
|
|
58
|
+
* measure covers everything the renderer puts around the payload, headers and footers included.
|
|
59
|
+
*/
|
|
60
|
+
export function fitsResult<T>(result: Outcome<T>, render: (result: Outcome<T>) => string): boolean {
|
|
61
|
+
return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
|
|
65
|
+
export const TextWindowSchema = Type.Object({
|
|
66
|
+
text: Type.String(),
|
|
67
|
+
total_chars: Type.Integer({ minimum: 0 }),
|
|
68
|
+
next_offset_chars: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()], { description: "Pass as `offset_chars` to continue; null at the end." }),
|
|
69
|
+
}, { additionalProperties: false });
|
|
70
|
+
export type TextWindow = Static<typeof TextWindowSchema>;
|
|
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
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Read one code-point window of `text` and build the operation's data around it. `offset` and
|
|
83
|
+
* `limit` are the integers the parameter schema already admitted; a negative `offset` resolves to
|
|
84
|
+
* `max(0, total + offset)`, and the caller refuses an offset past the end.
|
|
85
|
+
*
|
|
86
|
+
* An envelope that cannot fit even empty is refused instead of returned: a zero-length window
|
|
87
|
+
* would resume at the offset it started from, so paging could never make progress.
|
|
88
|
+
*/
|
|
89
|
+
export function readTextWindow<T>(
|
|
90
|
+
text: string,
|
|
91
|
+
offset: number | undefined,
|
|
92
|
+
limit: number | undefined,
|
|
93
|
+
makeData: (window: TextWindow) => T,
|
|
94
|
+
render: (result: Outcome<T>) => string,
|
|
95
|
+
): Outcome<T> {
|
|
96
|
+
const chars = Array.from(text);
|
|
97
|
+
const requested = offset ?? 0;
|
|
98
|
+
const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
|
|
99
|
+
const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
|
|
100
|
+
const range = Math.min(requestedChars, chars.length - start);
|
|
101
|
+
const window = (delivered: number): TextWindow => {
|
|
102
|
+
const end = start + delivered;
|
|
103
|
+
return {
|
|
104
|
+
text: chars.slice(start, end).join(""),
|
|
105
|
+
total_chars: chars.length,
|
|
106
|
+
next_offset_chars: end < chars.length ? end : null,
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
const fits = (delivered: number): boolean => fitsResult(success(makeData(window(delivered))), render);
|
|
110
|
+
// Test the full range first: its footer can disappear at the end of the document.
|
|
111
|
+
if (fits(range)) return success(makeData(window(range)));
|
|
112
|
+
let low = 0;
|
|
113
|
+
let high = range;
|
|
114
|
+
while (low < high) {
|
|
115
|
+
const mid = Math.ceil((low + high) / 2);
|
|
116
|
+
if (fits(mid)) low = mid;
|
|
117
|
+
else high = mid - 1;
|
|
118
|
+
}
|
|
119
|
+
if (low === 0) return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
|
|
120
|
+
return success(makeData(window(low)));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The continuation line never becomes part of `window.text`, and a complete window has none. */
|
|
124
|
+
export function renderTextWindow(window: TextWindow): string {
|
|
125
|
+
const next = window.next_offset_chars;
|
|
126
|
+
return next === null ? window.text : `${window.text}\n\n[truncated; continue at offset_chars=${next}]`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One outcome in, model-facing text out. */
|
|
130
|
+
export type Renderer<TData> = (result: Outcome<TData>) => string;
|
|
131
|
+
|
|
132
|
+
/** What both host adapters register: parameters in, canonical outcome out, and its text. */
|
|
133
|
+
export type Operation<TParams extends TSchema, TData, TRest extends readonly unknown[]> = {
|
|
134
|
+
readonly name: string;
|
|
135
|
+
readonly label: string;
|
|
136
|
+
readonly description: string;
|
|
137
|
+
readonly parameters: TParams;
|
|
138
|
+
/** Absent leaves concurrency to the host default. */
|
|
139
|
+
readonly executionMode?: "sequential" | "parallel";
|
|
140
|
+
/** Schema of wireResult(outcome), not the internal outcome envelope. */
|
|
141
|
+
readonly outputSchema: TSchema;
|
|
142
|
+
readonly execute: (params: Static<TParams>, ...rest: TRest) => Promise<Outcome<TData>>;
|
|
143
|
+
readonly render: Renderer<TData>;
|
|
144
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { HistoryRoleSchema } from "../history/history.js";
|
|
3
|
+
export const nullableString = (description?: string) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
|
|
4
|
+
export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
|
|
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
|
+
|
|
7
|
+
/** Search query parameter: one literal, or several literals combined with OR. */
|
|
8
|
+
export const searchQuery = (description?: string) => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })], description === undefined ? {} : { description });
|
|
9
|
+
|
|
10
|
+
/** Expected search-query refusal, distinct from any other Error an operation may raise. */
|
|
11
|
+
export class InvalidQueryError extends Error {
|
|
12
|
+
constructor(message: string) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "InvalidQueryError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Normalize a search `query` parameter into the literal needles to match.
|
|
20
|
+
* A bare string is a one-element list, so single-query behavior is unchanged.
|
|
21
|
+
* An empty list, a non-string element, or an empty string is refused rather than silently
|
|
22
|
+
* searching for nothing: those are argument errors, not empty result sets. An empty string
|
|
23
|
+
* matches every line and every item, so it can never be what the caller meant.
|
|
24
|
+
*/
|
|
25
|
+
export function searchQueries(query: unknown): string[] {
|
|
26
|
+
const candidates = typeof query === "string" ? [query] : query;
|
|
27
|
+
if (!Array.isArray(candidates) || candidates.length === 0) throw new InvalidQueryError("query must be a string or a non-empty array of strings");
|
|
28
|
+
if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("query array elements must be strings");
|
|
29
|
+
if (candidates.some((candidate) => candidate === "")) throw new InvalidQueryError("query strings must be non-empty: an empty query matches everything");
|
|
30
|
+
return candidates as string[];
|
|
31
|
+
}
|