toolsplice 0.0.0-stage → 0.0.1
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 +372 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +923 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +22 -0
- package/dist/contract-caller.js +307 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +5 -0
- package/dist/contract-schema.js +126 -0
- package/dist/contracts.d.ts +71 -0
- package/dist/contracts.js +366 -0
- package/dist/core.d.ts +14 -0
- package/dist/core.js +16 -0
- package/dist/doctor.d.ts +22 -0
- package/dist/doctor.js +91 -0
- package/dist/drift.d.ts +23 -0
- package/dist/drift.js +111 -0
- package/dist/execution.d.ts +38 -0
- package/dist/execution.js +66 -0
- package/dist/extract.d.ts +34 -0
- package/dist/extract.js +73 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +19 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/pattern.d.ts +2 -0
- package/dist/pattern.js +32 -0
- package/dist/postgres.d.ts +41 -0
- package/dist/postgres.js +264 -0
- package/dist/probe.d.ts +29 -0
- package/dist/probe.js +134 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -0
- package/dist/runtime.d.ts +6 -0
- package/dist/runtime.js +26 -0
- package/dist/schema.d.ts +17 -0
- package/dist/schema.js +299 -0
- package/dist/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/splice-diagnostics.d.ts +40 -0
- package/dist/splice-diagnostics.js +80 -0
- package/dist/splice-project.d.ts +119 -0
- package/dist/splice-project.js +296 -0
- package/dist/splice-recording.d.ts +105 -0
- package/dist/splice-recording.js +464 -0
- package/dist/splice.d.ts +84 -0
- package/dist/splice.js +1065 -0
- package/dist/storage.d.ts +17 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +151 -0
- package/dist/store.js +735 -0
- package/dist/v2.d.ts +49 -0
- package/dist/v2.js +396 -0
- package/dist/validate-output.d.ts +3 -0
- package/dist/validate-output.js +73 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/workflow-json.d.ts +8 -0
- package/dist/workflow-json.js +74 -0
- package/docs/PROJECTS-AND-UPGRADES.md +115 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +176 -0
- package/package.json +95 -4
package/dist/store.js
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
// Persists what we've learned about each server's tools as one JSON file per server.
|
|
2
|
+
import { closeSync, constants, fsyncSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, unlinkSync, writeFileSync, watch } from "node:fs";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { toJsonSchema } from "./schema.js";
|
|
6
|
+
import { DEFAULT_OPTIONS, emptyShape, hasEmbeddedJson, mergeInto, observe } from "./shape.js";
|
|
7
|
+
const MAX_SAMPLES = 3;
|
|
8
|
+
const MAX_SAMPLE_LENGTH = 240;
|
|
9
|
+
export function newServer(name, version) {
|
|
10
|
+
return { name, version, tools: {} };
|
|
11
|
+
}
|
|
12
|
+
export function newTool(name) {
|
|
13
|
+
return {
|
|
14
|
+
name,
|
|
15
|
+
calls: 0,
|
|
16
|
+
kinds: { structured: 0, "json-text": 0, text: 0, error: 0, empty: 0 },
|
|
17
|
+
shape: emptyShape(),
|
|
18
|
+
textSamples: [],
|
|
19
|
+
errorSamples: [],
|
|
20
|
+
prefixes: [],
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
// Tool names are untrusted keys, including "__proto__" and "constructor".
|
|
24
|
+
function getTool(server, name) {
|
|
25
|
+
if (Object.hasOwn(server.tools, name))
|
|
26
|
+
return server.tools[name];
|
|
27
|
+
const tool = newTool(name);
|
|
28
|
+
Object.defineProperty(server.tools, name, { value: tool, enumerable: true, writable: true, configurable: true });
|
|
29
|
+
return tool;
|
|
30
|
+
}
|
|
31
|
+
export function recordToolList(server, tools) {
|
|
32
|
+
for (const t of tools) {
|
|
33
|
+
const rec = getTool(server, t.name);
|
|
34
|
+
rec.description = t.description;
|
|
35
|
+
rec.inputSchema = t.inputSchema;
|
|
36
|
+
rec.outputSchema = t.outputSchema;
|
|
37
|
+
rec.annotations = t.annotations;
|
|
38
|
+
}
|
|
39
|
+
server.updatedAt = new Date().toISOString();
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Reapply privacy to retained learning across every tool, including tools absent from a new list.
|
|
43
|
+
* Mutates learned shapes and text/error/prefix samples only. Server-declared schemas (including
|
|
44
|
+
* their examples/defaults), descriptions, annotations, and other metadata are outside this scope.
|
|
45
|
+
* Call inside transact on load/list to persist a policy change before any tool calls occur.
|
|
46
|
+
*/
|
|
47
|
+
export function applyExamplePolicy(server, options = DEFAULT_OPTIONS) {
|
|
48
|
+
for (const tool of Object.values(server.tools))
|
|
49
|
+
applyToolExamplePolicy(tool, options);
|
|
50
|
+
}
|
|
51
|
+
function applyToolExamplePolicy(tool, options) {
|
|
52
|
+
// A zero-observation merge invokes inference's retained-field sanitizer without changing counts.
|
|
53
|
+
mergeInto(tool.shape, emptyShape(), options);
|
|
54
|
+
for (const key of ["textSamples", "errorSamples", "prefixes"]) {
|
|
55
|
+
const previous = tool[key];
|
|
56
|
+
tool[key] = [];
|
|
57
|
+
for (const sample of previous)
|
|
58
|
+
pushSample(tool[key], sample, options);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export function recordCall(server, toolName, result, options = DEFAULT_OPTIONS) {
|
|
62
|
+
const rec = getTool(server, toolName);
|
|
63
|
+
applyToolExamplePolicy(rec, options);
|
|
64
|
+
rec.calls++;
|
|
65
|
+
rec.kinds[result.kind]++;
|
|
66
|
+
switch (result.kind) {
|
|
67
|
+
case "structured":
|
|
68
|
+
observe(rec.shape, result.value, options);
|
|
69
|
+
break;
|
|
70
|
+
case "json-text":
|
|
71
|
+
observe(rec.shape, result.value, options);
|
|
72
|
+
if (result.prefix)
|
|
73
|
+
pushSample(rec.prefixes, result.prefix, options);
|
|
74
|
+
break;
|
|
75
|
+
case "text":
|
|
76
|
+
pushSample(rec.textSamples, result.text, options);
|
|
77
|
+
break;
|
|
78
|
+
case "error":
|
|
79
|
+
pushSample(rec.errorSamples, result.text, options);
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
rec.updatedAt = server.updatedAt = new Date().toISOString();
|
|
83
|
+
return rec;
|
|
84
|
+
}
|
|
85
|
+
function pushSample(list, text, options) {
|
|
86
|
+
if (options.examples === "none" || list.length >= MAX_SAMPLES)
|
|
87
|
+
return;
|
|
88
|
+
let sample = text;
|
|
89
|
+
if (options.examples === "safe") {
|
|
90
|
+
// Short status messages ("No results found.") are what matter; long text is usually data.
|
|
91
|
+
if (text.length > 120)
|
|
92
|
+
return;
|
|
93
|
+
sample = scrub(text);
|
|
94
|
+
}
|
|
95
|
+
else if (text.length > MAX_SAMPLE_LENGTH)
|
|
96
|
+
sample = text.slice(0, MAX_SAMPLE_LENGTH) + "…";
|
|
97
|
+
if (!list.includes(sample))
|
|
98
|
+
list.push(sample);
|
|
99
|
+
}
|
|
100
|
+
/** Masks things that look like paths, emails, ids and tokens in a short message. */
|
|
101
|
+
export function scrub(text) {
|
|
102
|
+
return text
|
|
103
|
+
.replace(/[^\s@]+@[^\s@]+\.[^\s@]+/g, "<email>")
|
|
104
|
+
.replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, "<url>")
|
|
105
|
+
.replace(/(?:~|\.{0,2})?\/[^\s"'`]+/g, "<path>")
|
|
106
|
+
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "<uuid>")
|
|
107
|
+
.replace(/[A-Za-z0-9+_=-]{20,}/g, "<token>")
|
|
108
|
+
.replace(/\d{6,}/g, "<number>");
|
|
109
|
+
}
|
|
110
|
+
/** The best available description of what a tool returns. */
|
|
111
|
+
export function toolOutput(tool) {
|
|
112
|
+
const k = tool.kinds;
|
|
113
|
+
const learned = tool.shape.count > 0;
|
|
114
|
+
const alsoText = learned && k.text > 0;
|
|
115
|
+
const alsoEmpty = k.empty > 0;
|
|
116
|
+
const textSample = tool.textSamples[0];
|
|
117
|
+
// A declared schema wins unless what we learned says more, e.g. `{ content: string }` whose
|
|
118
|
+
// string turns out to hold a JSON document.
|
|
119
|
+
const learnedSaysMore = learned && hasEmbeddedJson(tool.shape);
|
|
120
|
+
if (tool.outputSchema && (k.structured > 0 || !learned) && !learnedSaysMore) {
|
|
121
|
+
if (k.structured === 0 && k.text + k["json-text"] > 0) {
|
|
122
|
+
return {
|
|
123
|
+
source: "declared",
|
|
124
|
+
encoding: "text",
|
|
125
|
+
samples: 0,
|
|
126
|
+
alsoText: false, alsoEmpty,
|
|
127
|
+
textSample,
|
|
128
|
+
warning: `Server declares an outputSchema but returned no structuredContent in ${k.text + k["json-text"]} call(s).`,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const schema = learned ? withLearnedExamples(tool.outputSchema, toJsonSchema(tool.shape)) : tool.outputSchema;
|
|
132
|
+
return { schema, source: "declared", encoding: "structured", samples: k.structured, alsoText, alsoEmpty, textSample };
|
|
133
|
+
}
|
|
134
|
+
if (learned) {
|
|
135
|
+
const warning = !tool.outputSchema
|
|
136
|
+
? undefined
|
|
137
|
+
: k.structured > 0
|
|
138
|
+
? "Server's declared outputSchema hides JSON inside a string; type learned from responses."
|
|
139
|
+
: `Server declares an outputSchema but returned no structuredContent in ${k["json-text"]} call(s); type learned from text.`;
|
|
140
|
+
return {
|
|
141
|
+
schema: toJsonSchema(tool.shape),
|
|
142
|
+
source: "learned",
|
|
143
|
+
encoding: k.structured >= k["json-text"] ? "structured" : "json-text",
|
|
144
|
+
samples: tool.shape.count,
|
|
145
|
+
alsoText, alsoEmpty,
|
|
146
|
+
textSample,
|
|
147
|
+
prefix: tool.prefixes[0],
|
|
148
|
+
warning,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if (k.text > 0)
|
|
152
|
+
return { source: "learned", encoding: "text", samples: k.text, alsoText: false, alsoEmpty, textSample };
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Copies learned examples and observed values onto the matching properties of a declared schema.
|
|
157
|
+
* A declared `{ content: string }` says nothing about what the string looks like; an example does.
|
|
158
|
+
*/
|
|
159
|
+
export function withLearnedExamples(declared, learned) {
|
|
160
|
+
const out = { ...declared };
|
|
161
|
+
for (const key of ["examples", "x-observed-values"]) {
|
|
162
|
+
if (learned[key] !== undefined && out[key] === undefined && out.enum === undefined)
|
|
163
|
+
out[key] = learned[key];
|
|
164
|
+
}
|
|
165
|
+
const props = declared.properties;
|
|
166
|
+
const learnedProps = learned.properties;
|
|
167
|
+
if (props && learnedProps) {
|
|
168
|
+
out.properties = Object.fromEntries(Object.entries(props).map(([k, v]) => [k, learnedProps[k] && typeof v === "object" ? withLearnedExamples(v, learnedProps[k]) : v]));
|
|
169
|
+
}
|
|
170
|
+
const items = declared.items;
|
|
171
|
+
if (items && typeof items === "object" && learned.items && typeof learned.items === "object") {
|
|
172
|
+
out.items = withLearnedExamples(items, learned.items);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
export class ShapeStoreError extends Error {
|
|
177
|
+
code;
|
|
178
|
+
constructor(code, message, cause) {
|
|
179
|
+
super(message, { cause });
|
|
180
|
+
this.code = code;
|
|
181
|
+
this.name = "ShapeStoreError";
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Explicit reads and writes throw on failure; a proxy should catch recording failures.
|
|
186
|
+
* Saves are atomic and reject stale snapshots instead of silently losing another writer's data.
|
|
187
|
+
* Locks are nonblocking: after a crashed writer, inspect/remove its .lock file before retrying.
|
|
188
|
+
* PID/inode checks cannot make stale-lock unlink atomic, so locks are never auto-reclaimed.
|
|
189
|
+
* SIGKILL can leave one private .tmp per in-flight write; repeated manual recovery/crashes can
|
|
190
|
+
* accumulate orphans. Inspect/clean these only after stopping writers.
|
|
191
|
+
*/
|
|
192
|
+
export class ShapeStore {
|
|
193
|
+
dir;
|
|
194
|
+
options;
|
|
195
|
+
cache = new Map();
|
|
196
|
+
snapshots = new Map();
|
|
197
|
+
constructor(dir, options = {}) {
|
|
198
|
+
this.dir = dir;
|
|
199
|
+
this.options = options;
|
|
200
|
+
}
|
|
201
|
+
/** Read disk without consulting an old session's cache, including external forget. */
|
|
202
|
+
refresh(name) {
|
|
203
|
+
const fresh = new ShapeStore(this.dir, this.options);
|
|
204
|
+
return fresh.has(name) ? fresh.load(name) : undefined;
|
|
205
|
+
}
|
|
206
|
+
watch(_name, onChange, onError) {
|
|
207
|
+
const watcher = watch(this.dir, { persistent: false }, (_event, filename) => {
|
|
208
|
+
if (!filename || String(filename).endsWith(".json"))
|
|
209
|
+
onChange();
|
|
210
|
+
});
|
|
211
|
+
watcher.on("error", () => { watcher.close(); onError?.(); });
|
|
212
|
+
return () => watcher.close();
|
|
213
|
+
}
|
|
214
|
+
load(name, version) {
|
|
215
|
+
const cached = this.cache.get(name);
|
|
216
|
+
if (cached) {
|
|
217
|
+
if (version !== undefined)
|
|
218
|
+
cached.version = version;
|
|
219
|
+
return cached;
|
|
220
|
+
}
|
|
221
|
+
const snapshot = this.locate(name);
|
|
222
|
+
const raw = readOptional(snapshot.file);
|
|
223
|
+
const record = raw === undefined ? newServer(name, version) : parseRecord(raw, snapshot.file, name);
|
|
224
|
+
if (version !== undefined)
|
|
225
|
+
record.version = version;
|
|
226
|
+
this.snapshots.set(name, { file: snapshot.file, digest: raw === undefined ? undefined : digest(raw) });
|
|
227
|
+
this.cache.set(name, record);
|
|
228
|
+
return record;
|
|
229
|
+
}
|
|
230
|
+
has(name) {
|
|
231
|
+
if (this.cache.has(name))
|
|
232
|
+
return true;
|
|
233
|
+
const { file } = this.locate(name);
|
|
234
|
+
const raw = readOptional(file);
|
|
235
|
+
if (raw === undefined)
|
|
236
|
+
return false;
|
|
237
|
+
parseRecord(raw, file, name);
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
save(name) {
|
|
241
|
+
const record = this.cache.get(name);
|
|
242
|
+
if (!record)
|
|
243
|
+
return;
|
|
244
|
+
const snapshot = this.snapshots.get(name);
|
|
245
|
+
const file = snapshot.file;
|
|
246
|
+
const raw = this.serialize(record, file, name);
|
|
247
|
+
const lock = `${file}.lock`;
|
|
248
|
+
// Keep temporary names short even when reading a long legacy filename.
|
|
249
|
+
const tmp = join(this.dir, `.shape-${process.pid}-${randomUUID()}.tmp`);
|
|
250
|
+
let locked = false;
|
|
251
|
+
let temporary = false;
|
|
252
|
+
try {
|
|
253
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
254
|
+
let fd;
|
|
255
|
+
try {
|
|
256
|
+
fd = openSync(lock, "wx", 0o600);
|
|
257
|
+
}
|
|
258
|
+
catch (cause) {
|
|
259
|
+
if (hasCode(cause, "EEXIST"))
|
|
260
|
+
throw new ShapeStoreError("LOCKED", `ShapeStore file ${JSON.stringify(file)} is locked by another writer. Retry later; inspect the .lock file if a writer crashed.`, cause);
|
|
261
|
+
throw cause;
|
|
262
|
+
}
|
|
263
|
+
locked = true;
|
|
264
|
+
try {
|
|
265
|
+
writeFileSync(fd, `${process.pid}\n`);
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
closeSync(fd);
|
|
269
|
+
}
|
|
270
|
+
const current = readOptional(file);
|
|
271
|
+
if ((current === undefined ? undefined : digest(current)) !== snapshot.digest) {
|
|
272
|
+
throw new ShapeStoreError("CONFLICT", `ShapeStore file ${JSON.stringify(file)} changed since load. Reload using a new ShapeStore before saving; the newer file was preserved.`);
|
|
273
|
+
}
|
|
274
|
+
const out = openSync(tmp, "wx", 0o600);
|
|
275
|
+
temporary = true;
|
|
276
|
+
try {
|
|
277
|
+
writeFileSync(out, raw);
|
|
278
|
+
fsyncSync(out);
|
|
279
|
+
}
|
|
280
|
+
finally {
|
|
281
|
+
closeSync(out);
|
|
282
|
+
}
|
|
283
|
+
renameSync(tmp, file);
|
|
284
|
+
temporary = false;
|
|
285
|
+
snapshot.digest = digest(raw);
|
|
286
|
+
}
|
|
287
|
+
catch (cause) {
|
|
288
|
+
if (cause instanceof ShapeStoreError)
|
|
289
|
+
throw cause;
|
|
290
|
+
throw ioError("save", file, cause);
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
if (temporary)
|
|
294
|
+
this.cleanup(tmp);
|
|
295
|
+
if (locked)
|
|
296
|
+
this.cleanup(lock);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Apply one synchronous mutation to the latest persisted record while holding its writer lock.
|
|
301
|
+
* If no file exists, reuse only a never-persisted cache as a detached copy. A previously
|
|
302
|
+
* persisted record that disappeared starts fresh, respecting another process's forget.
|
|
303
|
+
* A successful return means the write committed and the cache/save baseline were refreshed.
|
|
304
|
+
*
|
|
305
|
+
* A throw has NO return value and does NOT imply the mutator was never called: read/lock
|
|
306
|
+
* failures precede it, while serialization/write failures follow it. The mutator is never
|
|
307
|
+
* retried internally. For fail-open recording, capture its record and mark callback entry;
|
|
308
|
+
* if it ran, use that in-memory record without applying the mutation again. The cache is
|
|
309
|
+
* replaced only on success; failed callback records remain available only to their caller.
|
|
310
|
+
* Unsaved local changes are superseded whenever a persisted record exists. Callbacks must
|
|
311
|
+
* not perform upstream calls or other irreversible effects. Existing locks fail with LOCKED.
|
|
312
|
+
*/
|
|
313
|
+
transact(name, mutate) {
|
|
314
|
+
const { file } = this.locate(name);
|
|
315
|
+
const lock = `${file}.lock`;
|
|
316
|
+
const tmp = join(this.dir, `.shape-${process.pid}-${randomUUID()}.tmp`);
|
|
317
|
+
let locked = false;
|
|
318
|
+
let temporary = false;
|
|
319
|
+
// Keep filesystem setup separate so an exception from mutate is propagated unchanged.
|
|
320
|
+
try {
|
|
321
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
322
|
+
let fd;
|
|
323
|
+
try {
|
|
324
|
+
fd = openSync(lock, "wx", 0o600);
|
|
325
|
+
}
|
|
326
|
+
catch (cause) {
|
|
327
|
+
if (hasCode(cause, "EEXIST"))
|
|
328
|
+
throw new ShapeStoreError("LOCKED", `ShapeStore file ${JSON.stringify(file)} is locked by another writer. Retry later; inspect the .lock file if a writer crashed.`, cause);
|
|
329
|
+
throw cause;
|
|
330
|
+
}
|
|
331
|
+
locked = true;
|
|
332
|
+
try {
|
|
333
|
+
writeFileSync(fd, `${process.pid}\n`);
|
|
334
|
+
}
|
|
335
|
+
finally {
|
|
336
|
+
closeSync(fd);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
catch (cause) {
|
|
340
|
+
if (locked)
|
|
341
|
+
this.cleanup(lock);
|
|
342
|
+
if (cause instanceof ShapeStoreError)
|
|
343
|
+
throw cause;
|
|
344
|
+
throw ioError("transact", file, cause);
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
// An old-format file may have appeared while locating/acquiring the lock.
|
|
348
|
+
if (this.locate(name).file !== file) {
|
|
349
|
+
throw new ShapeStoreError("CONFLICT", `ShapeStore location for ${JSON.stringify(name)} changed during lock acquisition. Retry the transaction.`);
|
|
350
|
+
}
|
|
351
|
+
const current = readOptional(file);
|
|
352
|
+
// Only initial, never-persisted learning may seed an absent file. Reusing a stale
|
|
353
|
+
// persisted cache here would resurrect observations deleted by another process.
|
|
354
|
+
const cached = this.snapshots.get(name)?.digest === undefined ? this.cache.get(name) : undefined;
|
|
355
|
+
const record = current !== undefined ? parseRecord(current, file, name)
|
|
356
|
+
: cached ? parseRecord(this.serialize(cached, file, name), file, name) : newServer(name);
|
|
357
|
+
const value = mutate(record);
|
|
358
|
+
if (value !== null && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function") {
|
|
359
|
+
throw new TypeError("ShapeStore.transact mutator must be synchronous.");
|
|
360
|
+
}
|
|
361
|
+
const raw = this.serialize(record, file, name);
|
|
362
|
+
try {
|
|
363
|
+
const out = openSync(tmp, "wx", 0o600);
|
|
364
|
+
temporary = true;
|
|
365
|
+
try {
|
|
366
|
+
writeFileSync(out, raw);
|
|
367
|
+
fsyncSync(out);
|
|
368
|
+
}
|
|
369
|
+
finally {
|
|
370
|
+
closeSync(out);
|
|
371
|
+
}
|
|
372
|
+
renameSync(tmp, file);
|
|
373
|
+
temporary = false;
|
|
374
|
+
}
|
|
375
|
+
catch (cause) {
|
|
376
|
+
throw ioError("transact", file, cause);
|
|
377
|
+
}
|
|
378
|
+
this.cache.set(name, record);
|
|
379
|
+
this.snapshots.set(name, { file, digest: digest(raw) });
|
|
380
|
+
return value;
|
|
381
|
+
}
|
|
382
|
+
finally {
|
|
383
|
+
if (temporary)
|
|
384
|
+
this.cleanup(tmp);
|
|
385
|
+
this.cleanup(lock);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/** Forget only files whose validated identity matches name. Never contacts the server. */
|
|
389
|
+
remove(name) {
|
|
390
|
+
const canonical = this.fileFor(name);
|
|
391
|
+
const candidates = [...new Set([canonical, this.legacyFileFor(name)].filter((f) => f !== undefined))];
|
|
392
|
+
const owned = [];
|
|
393
|
+
for (const file of candidates) {
|
|
394
|
+
const raw = readOptional(file);
|
|
395
|
+
if (raw === undefined)
|
|
396
|
+
continue;
|
|
397
|
+
const record = parseRecord(raw, file);
|
|
398
|
+
if (record.name !== name) {
|
|
399
|
+
if (file === canonical)
|
|
400
|
+
parseRecord(raw, file, name); // Actionable identity error.
|
|
401
|
+
else
|
|
402
|
+
this.warn(`Preserving legacy ShapeStore file ${JSON.stringify(file)}: it belongs to a different server.`);
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
owned.push({ file, digest: digest(raw) });
|
|
406
|
+
}
|
|
407
|
+
const locks = [];
|
|
408
|
+
try {
|
|
409
|
+
for (const { file } of owned.sort((a, b) => a.file.localeCompare(b.file))) {
|
|
410
|
+
const lock = `${file}.lock`;
|
|
411
|
+
let fd;
|
|
412
|
+
try {
|
|
413
|
+
fd = openSync(lock, "wx", 0o600);
|
|
414
|
+
}
|
|
415
|
+
catch (cause) {
|
|
416
|
+
if (hasCode(cause, "EEXIST"))
|
|
417
|
+
throw new ShapeStoreError("LOCKED", `ShapeStore file ${JSON.stringify(file)} is locked by another writer. Retry later; inspect the .lock file if a writer crashed.`, cause);
|
|
418
|
+
throw ioError("remove", file, cause);
|
|
419
|
+
}
|
|
420
|
+
locks.push(lock);
|
|
421
|
+
try {
|
|
422
|
+
writeFileSync(fd, `${process.pid}\n`);
|
|
423
|
+
}
|
|
424
|
+
finally {
|
|
425
|
+
closeSync(fd);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
// Validate all files before deleting any, and reject concurrent edits during lock acquisition.
|
|
429
|
+
for (const { file, digest: expected } of owned) {
|
|
430
|
+
const raw = readOptional(file);
|
|
431
|
+
if (raw === undefined || digest(raw) !== expected) {
|
|
432
|
+
throw new ShapeStoreError("CONFLICT", `ShapeStore file ${JSON.stringify(file)} changed during removal. Retry after inspecting the current record.`);
|
|
433
|
+
}
|
|
434
|
+
parseRecord(raw, file, name);
|
|
435
|
+
}
|
|
436
|
+
for (const { file } of owned) {
|
|
437
|
+
try {
|
|
438
|
+
unlinkSync(file);
|
|
439
|
+
}
|
|
440
|
+
catch (cause) {
|
|
441
|
+
if (!hasCode(cause, "ENOENT"))
|
|
442
|
+
throw ioError("remove", file, cause);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
this.cache.delete(name);
|
|
446
|
+
this.snapshots.delete(name);
|
|
447
|
+
}
|
|
448
|
+
catch (cause) {
|
|
449
|
+
if (cause instanceof ShapeStoreError)
|
|
450
|
+
throw cause;
|
|
451
|
+
throw ioError("remove", canonical, cause);
|
|
452
|
+
}
|
|
453
|
+
finally {
|
|
454
|
+
for (const lock of locks.reverse())
|
|
455
|
+
this.cleanup(lock);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
list() {
|
|
459
|
+
let files;
|
|
460
|
+
try {
|
|
461
|
+
files = readdirSync(this.dir);
|
|
462
|
+
}
|
|
463
|
+
catch (cause) {
|
|
464
|
+
if (hasCode(cause, "ENOENT"))
|
|
465
|
+
return [];
|
|
466
|
+
throw ioError("list", this.dir, cause);
|
|
467
|
+
}
|
|
468
|
+
const names = new Set();
|
|
469
|
+
for (const entry of files.sort()) {
|
|
470
|
+
if (!entry.endsWith(".json"))
|
|
471
|
+
continue;
|
|
472
|
+
const file = join(this.dir, entry);
|
|
473
|
+
try {
|
|
474
|
+
const raw = readOptional(file);
|
|
475
|
+
if (raw === undefined)
|
|
476
|
+
continue; // Deleted between readdir and read.
|
|
477
|
+
const record = parseRecord(raw, file);
|
|
478
|
+
if (file !== this.fileFor(record.name) && file !== this.legacyFileFor(record.name)) {
|
|
479
|
+
throw new ShapeStoreError("IDENTITY", `ShapeStore file ${JSON.stringify(file)} does not match its server name.`);
|
|
480
|
+
}
|
|
481
|
+
names.add(record.name);
|
|
482
|
+
}
|
|
483
|
+
catch (cause) {
|
|
484
|
+
this.warn(cause instanceof Error ? cause.message : `Cannot read ${JSON.stringify(file)}.`);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return [...names].sort();
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Read-only, best-effort snapshot of lock/temp artifacts; never reclaims or reads result data.
|
|
491
|
+
* Each lock read is bounded to 64 bytes. Symlinks/nonregular/unreadable locks report unknown.
|
|
492
|
+
* Temp PIDs come only from recognized filenames; their contents are never opened.
|
|
493
|
+
* A temp may belong to an active write. Liveness is advisory, not permission to delete: PID
|
|
494
|
+
* reuse, concurrent file replacement, and process namespaces prevent reliable ownership proof.
|
|
495
|
+
*/
|
|
496
|
+
diagnostics() {
|
|
497
|
+
let files;
|
|
498
|
+
try {
|
|
499
|
+
const stat = lstatSync(this.dir);
|
|
500
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
501
|
+
throw new ShapeStoreError("IO", `ShapeStore diagnostic directory ${JSON.stringify(this.dir)} must be a directory, not a symlink.`);
|
|
502
|
+
}
|
|
503
|
+
files = readdirSync(this.dir);
|
|
504
|
+
}
|
|
505
|
+
catch (cause) {
|
|
506
|
+
if (hasCode(cause, "ENOENT"))
|
|
507
|
+
return [];
|
|
508
|
+
if (cause instanceof ShapeStoreError)
|
|
509
|
+
throw cause;
|
|
510
|
+
throw ioError("inspect", this.dir, cause);
|
|
511
|
+
}
|
|
512
|
+
const diagnostics = [];
|
|
513
|
+
for (const entry of files.sort()) {
|
|
514
|
+
const locked = entry.endsWith(".json.lock");
|
|
515
|
+
const temporary = (entry.startsWith(".shape-") || /\.json\..+\.tmp$/.test(entry)) && entry.endsWith(".tmp");
|
|
516
|
+
if (!locked && !temporary)
|
|
517
|
+
continue;
|
|
518
|
+
const file = join(this.dir, entry);
|
|
519
|
+
let pid;
|
|
520
|
+
try {
|
|
521
|
+
const stat = lstatSync(file);
|
|
522
|
+
if (stat.isFile() && !stat.isSymbolicLink()) {
|
|
523
|
+
if (locked)
|
|
524
|
+
pid = readLockPid(file, stat.dev, stat.ino);
|
|
525
|
+
else {
|
|
526
|
+
const match = /^\.shape-([0-9]+)-[0-9a-f-]+\.tmp$/.exec(entry) ?? /\.json\.([0-9]+)\.tmp$/.exec(entry);
|
|
527
|
+
if (match)
|
|
528
|
+
pid = parsePid(match[1]);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
catch (cause) {
|
|
533
|
+
if (hasCode(cause, "ENOENT"))
|
|
534
|
+
continue; // Normal during concurrent writes.
|
|
535
|
+
this.warn(`Cannot inspect ShapeStore artifact ${JSON.stringify(file)}; owner is unknown.`);
|
|
536
|
+
}
|
|
537
|
+
const diagnostic = { file, kind: locked ? "locked" : "orphan-temp", owner: "unknown" };
|
|
538
|
+
if (pid !== undefined) {
|
|
539
|
+
diagnostic.pid = pid;
|
|
540
|
+
try {
|
|
541
|
+
process.kill(pid, 0);
|
|
542
|
+
diagnostic.owner = "running";
|
|
543
|
+
}
|
|
544
|
+
catch (cause) {
|
|
545
|
+
if (hasCode(cause, "ESRCH"))
|
|
546
|
+
diagnostic.owner = "not-running";
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
diagnostics.push(diagnostic);
|
|
550
|
+
}
|
|
551
|
+
return diagnostics;
|
|
552
|
+
}
|
|
553
|
+
locate(name) {
|
|
554
|
+
const file = this.fileFor(name);
|
|
555
|
+
if (readOptional(file) !== undefined)
|
|
556
|
+
return { file };
|
|
557
|
+
const legacy = this.legacyFileFor(name);
|
|
558
|
+
if (legacy && legacy !== file) {
|
|
559
|
+
const raw = readOptional(legacy);
|
|
560
|
+
if (raw !== undefined) {
|
|
561
|
+
const record = parseRecord(raw, legacy);
|
|
562
|
+
if (record.name === name)
|
|
563
|
+
return { file: legacy };
|
|
564
|
+
this.warn(`Ignoring legacy ShapeStore file ${JSON.stringify(legacy)}: it belongs to a different server.`);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return { file };
|
|
568
|
+
}
|
|
569
|
+
fileFor(name) {
|
|
570
|
+
// Keep established, portable lowercase names. '~' reserves a separate namespace for hashes.
|
|
571
|
+
// Hash JSON spelling so lone UTF-16 surrogates remain distinct from replacement characters.
|
|
572
|
+
const portable = /^[a-z0-9][a-z0-9_-]{0,79}$/.test(name) && !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(name);
|
|
573
|
+
const stem = name.replace(/[^A-Za-z0-9_-]+/g, "_").slice(0, 40);
|
|
574
|
+
return join(this.dir, `${portable ? name : `~${stem}--${digest(JSON.stringify(name))}`}.json`);
|
|
575
|
+
}
|
|
576
|
+
legacyFileFor(name) {
|
|
577
|
+
const stem = name.replace(/[^A-Za-z0-9._-]+/g, "_");
|
|
578
|
+
// Avoid NAME_MAX failures and reserved device names when checking old filenames.
|
|
579
|
+
if (stem.length > 180 || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(stem))
|
|
580
|
+
return undefined;
|
|
581
|
+
return join(this.dir, `${stem}.json`);
|
|
582
|
+
}
|
|
583
|
+
serialize(record, file, name) {
|
|
584
|
+
// Validate the serialized representation too: undefined/nonfinite values can change in JSON.
|
|
585
|
+
try {
|
|
586
|
+
const raw = JSON.stringify(record, null, 2);
|
|
587
|
+
parseRecord(raw, file, name);
|
|
588
|
+
return raw;
|
|
589
|
+
}
|
|
590
|
+
catch (cause) {
|
|
591
|
+
if (cause instanceof ShapeStoreError)
|
|
592
|
+
throw cause;
|
|
593
|
+
throw new ShapeStoreError("CORRUPT", `Cannot serialize ShapeStore record for ${JSON.stringify(name)}.`, cause);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
cleanup(file) {
|
|
597
|
+
try {
|
|
598
|
+
unlinkSync(file);
|
|
599
|
+
}
|
|
600
|
+
catch (cause) {
|
|
601
|
+
if (!hasCode(cause, "ENOENT"))
|
|
602
|
+
this.warn(`Could not clean up ShapeStore file ${JSON.stringify(file)}.`);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
warn(message) {
|
|
606
|
+
// A diagnostic callback must not turn a successful save into a failed tool response.
|
|
607
|
+
try {
|
|
608
|
+
this.options.onWarning?.(message);
|
|
609
|
+
}
|
|
610
|
+
catch { /* diagnostics are best effort */ }
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
function parsePid(raw) {
|
|
614
|
+
if (!/^[1-9][0-9]{0,9}\n?$/.test(raw))
|
|
615
|
+
return undefined;
|
|
616
|
+
const pid = Number(raw);
|
|
617
|
+
return Number.isSafeInteger(pid) && pid <= 2_147_483_647 ? pid : undefined;
|
|
618
|
+
}
|
|
619
|
+
function readLockPid(file, device, inode) {
|
|
620
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
621
|
+
try {
|
|
622
|
+
const stat = fstatSync(fd);
|
|
623
|
+
if (!stat.isFile() || stat.dev !== device || stat.ino !== inode || stat.size < 1 || stat.size > 64)
|
|
624
|
+
return undefined;
|
|
625
|
+
const buffer = Buffer.alloc(64);
|
|
626
|
+
const bytes = readSync(fd, buffer, 0, 64, 0);
|
|
627
|
+
if (bytes !== stat.size)
|
|
628
|
+
return undefined;
|
|
629
|
+
return parsePid(buffer.toString("utf8", 0, bytes));
|
|
630
|
+
}
|
|
631
|
+
finally {
|
|
632
|
+
closeSync(fd);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
function digest(raw) { return createHash("sha256").update(raw).digest("hex"); }
|
|
636
|
+
function hasCode(error, code) {
|
|
637
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
|
638
|
+
}
|
|
639
|
+
function ioError(action, file, cause) {
|
|
640
|
+
const code = typeof cause === "object" && cause !== null && "code" in cause ? String(cause.code) : "unknown error";
|
|
641
|
+
return new ShapeStoreError("IO", `Cannot ${action} ShapeStore file ${JSON.stringify(file)} (${code}). Check the store path and permissions.`, cause);
|
|
642
|
+
}
|
|
643
|
+
/** No existsSync: only ENOENT means absent; permissions and wrong file types stay actionable. */
|
|
644
|
+
function readOptional(file) {
|
|
645
|
+
let fd;
|
|
646
|
+
try {
|
|
647
|
+
const stat = lstatSync(file);
|
|
648
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
649
|
+
throw new ShapeStoreError("IO", `ShapeStore path ${JSON.stringify(file)} must be a regular file, not a directory or symlink.`);
|
|
650
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
651
|
+
if (!fstatSync(fd).isFile())
|
|
652
|
+
throw new ShapeStoreError("IO", `ShapeStore path ${JSON.stringify(file)} must be a regular file.`);
|
|
653
|
+
return readFileSync(fd, "utf8");
|
|
654
|
+
}
|
|
655
|
+
catch (cause) {
|
|
656
|
+
if (hasCode(cause, "ENOENT"))
|
|
657
|
+
return undefined;
|
|
658
|
+
if (cause instanceof ShapeStoreError)
|
|
659
|
+
throw cause;
|
|
660
|
+
throw ioError("read", file, cause);
|
|
661
|
+
}
|
|
662
|
+
finally {
|
|
663
|
+
if (fd !== undefined)
|
|
664
|
+
closeSync(fd);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
function object(value) {
|
|
668
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
669
|
+
}
|
|
670
|
+
function count(value) { return Number.isSafeInteger(value) && value >= 0; }
|
|
671
|
+
function finite(value) { return typeof value === "number" && Number.isFinite(value); }
|
|
672
|
+
function strings(value) { return Array.isArray(value) && value.every(v => typeof v === "string"); }
|
|
673
|
+
function optionalString(value) { return value === undefined || typeof value === "string"; }
|
|
674
|
+
function optionalBoolean(value) { return value === undefined || typeof value === "boolean"; }
|
|
675
|
+
function counts(value) { return object(value) && Object.values(value).every(count); }
|
|
676
|
+
/** Validate nested statistics before schema generation or further observation can touch them. */
|
|
677
|
+
function validShape(value, depth = 0) {
|
|
678
|
+
if (depth > 128 || !object(value) || !count(value.count) || !count(value.null) || !count(value.boolean))
|
|
679
|
+
return false;
|
|
680
|
+
const n = value.number;
|
|
681
|
+
if (n !== undefined && (!object(n) || !count(n.count) || !count(n.integers) || !finite(n.min) || !finite(n.max) || n.min > n.max || !Array.isArray(n.examples) || !n.examples.every(finite)))
|
|
682
|
+
return false;
|
|
683
|
+
const s = value.string;
|
|
684
|
+
if (s !== undefined && (!object(s) || !count(s.count) || !(s.values === null || counts(s.values)) || !counts(s.formats) || !count(s.minLength) || !count(s.maxLength) || s.minLength > s.maxLength || !strings(s.examples) || !optionalBoolean(s.redacted) || !(s.jsonCount === undefined || count(s.jsonCount)) || !(s.json === undefined || validShape(s.json, depth + 1))))
|
|
685
|
+
return false;
|
|
686
|
+
const a = value.array;
|
|
687
|
+
if (a !== undefined && (!object(a) || !count(a.count) || !count(a.minItems) || !count(a.maxItems) || a.minItems > a.maxItems || !validShape(a.items, depth + 1)))
|
|
688
|
+
return false;
|
|
689
|
+
const o = value.object;
|
|
690
|
+
if (o !== undefined && (!object(o) || !count(o.count) || !optionalBoolean(o.truncated) || !object(o.props) || !Object.values(o.props).every(v => validShape(v, depth + 1))))
|
|
691
|
+
return false;
|
|
692
|
+
return true;
|
|
693
|
+
}
|
|
694
|
+
function validDrift(value) {
|
|
695
|
+
return value === undefined || (object(value) && count(value.revision) && Array.isArray(value.events) &&
|
|
696
|
+
value.events.every(event => object(event) && typeof event.at === "string" && strings(event.changes) && typeof event.reason === "string"));
|
|
697
|
+
}
|
|
698
|
+
function validSchemaValidation(value) {
|
|
699
|
+
return value === undefined || (object(value) && count(value.checked) && count(value.mismatches) &&
|
|
700
|
+
typeof value.latest === "string" && strings(value.paths));
|
|
701
|
+
}
|
|
702
|
+
function validTool(value, name) {
|
|
703
|
+
if (!object(value) || value.name !== name || !count(value.calls) || !object(value.kinds) ||
|
|
704
|
+
!["structured", "json-text", "text", "error", "empty"].every(k => count(value.kinds[k])) ||
|
|
705
|
+
!validShape(value.shape) || !strings(value.textSamples) || !strings(value.errorSamples) || !strings(value.prefixes) ||
|
|
706
|
+
!optionalString(value.description) || !optionalString(value.updatedAt) ||
|
|
707
|
+
!validDrift(value.drift) || !validSchemaValidation(value.schemaValidation) ||
|
|
708
|
+
!(value.inputSchema === undefined || object(value.inputSchema)) || !(value.outputSchema === undefined || object(value.outputSchema)))
|
|
709
|
+
return false;
|
|
710
|
+
const a = value.annotations;
|
|
711
|
+
return a === undefined || (object(a) && optionalString(a.title) && [a.readOnlyHint, a.destructiveHint, a.idempotentHint, a.openWorldHint].every(optionalBoolean));
|
|
712
|
+
}
|
|
713
|
+
/** Internal shared validation for persistent backends. The label must not contain credentials. */
|
|
714
|
+
export function decodeStoredRecord(raw, name) {
|
|
715
|
+
return parseRecord(raw, "database record", name);
|
|
716
|
+
}
|
|
717
|
+
function parseRecord(raw, file, expectedName) {
|
|
718
|
+
let value;
|
|
719
|
+
try {
|
|
720
|
+
value = JSON.parse(raw);
|
|
721
|
+
}
|
|
722
|
+
catch {
|
|
723
|
+
throw new ShapeStoreError("CORRUPT", `ShapeStore file ${JSON.stringify(file)} contains invalid JSON. Restore a backup or move it aside before recording again.`);
|
|
724
|
+
}
|
|
725
|
+
if (!object(value) || typeof value.name !== "string" || !object(value.tools) ||
|
|
726
|
+
!optionalString(value.version) || !optionalString(value.updatedAt) || !optionalString(value.exportedAt) || !optionalString(value.exportedFingerprint) ||
|
|
727
|
+
!Object.entries(value.tools).every(([name, tool]) => validTool(tool, name))) {
|
|
728
|
+
throw new ShapeStoreError("CORRUPT", `ShapeStore file ${JSON.stringify(file)} has an invalid record structure. Restore a backup or move it aside before recording again.`);
|
|
729
|
+
}
|
|
730
|
+
if (expectedName !== undefined && value.name !== expectedName) {
|
|
731
|
+
throw new ShapeStoreError("IDENTITY", `ShapeStore file ${JSON.stringify(file)} belongs to ${JSON.stringify(value.name)}, not ${JSON.stringify(expectedName)}. The file was preserved.`);
|
|
732
|
+
}
|
|
733
|
+
// Unknown metadata and extra fields survive round trips; known structures were validated above.
|
|
734
|
+
return value;
|
|
735
|
+
}
|