fascicle 0.12.13 → 0.13.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/dist/adapters-DNnzeLxr.js +447 -0
  3. package/dist/adapters-DNnzeLxr.js.map +1 -0
  4. package/dist/adapters.d.ts +54 -9
  5. package/dist/adapters.js +1 -1
  6. package/dist/agents.d.ts +12 -9
  7. package/dist/agents.js +1 -1
  8. package/dist/{core-BVCVUMmH.js → core-B-M7nAkg.js} +704 -33
  9. package/dist/core-B-M7nAkg.js.map +1 -0
  10. package/dist/diagram_bin.d.ts +1 -2
  11. package/dist/diagram_bin.js +1 -1
  12. package/dist/diagram_bin.js.map +1 -1
  13. package/dist/{engine-Ct4LBzb9.js → engine-BRzVcTBB.js} +366 -36
  14. package/dist/engine-BRzVcTBB.js.map +1 -0
  15. package/dist/index.d.ts +325 -179
  16. package/dist/index.js +149 -123
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-BcPDqE5C.js → invoke-CIdhjChw.js} +3 -3
  19. package/dist/{invoke-BcPDqE5C.js.map → invoke-CIdhjChw.js.map} +1 -1
  20. package/dist/mcp.d.ts +8 -9
  21. package/dist/mcp.js +1 -1
  22. package/dist/otel.d.ts +3 -4
  23. package/dist/stdio.d.ts +4 -5
  24. package/dist/stdio.js +2 -2
  25. package/dist/testing.d.ts +46 -10
  26. package/dist/testing.js +540 -4
  27. package/dist/testing.js.map +1 -1
  28. package/dist/{trajectory-D1eq9eue.js → trajectory-BI-mrVFT.js} +25 -2
  29. package/dist/trajectory-BI-mrVFT.js.map +1 -0
  30. package/dist/{trajectory-ByoOQZ6T.d.ts → trajectory-Bm-mOtqw.d.ts} +34 -3
  31. package/dist/{types-BasW4Wwb.d.ts → types-CPqLZOEr.d.ts} +40 -2
  32. package/dist/{types-bEpfDrys.d.ts → types-CZ83Q5nm.d.ts} +12 -7
  33. package/dist/ui.d.ts +11 -10
  34. package/dist/ui.js +3 -2
  35. package/dist/ui.js.map +1 -1
  36. package/dist/viewer-app/assets/index-DXsB0byD.js +2 -0
  37. package/dist/viewer-app/index.html +1 -1
  38. package/dist/viewer.d.ts +7 -8
  39. package/dist/viewer.js +2 -2
  40. package/dist/viewer.js.map +1 -1
  41. package/package.json +28 -28
  42. package/dist/adapters-CutexJd3.js +0 -270
  43. package/dist/adapters-CutexJd3.js.map +0 -1
  44. package/dist/core-BVCVUMmH.js.map +0 -1
  45. package/dist/engine-Ct4LBzb9.js.map +0 -1
  46. package/dist/leading_system-CfOIc5fi.js +0 -330
  47. package/dist/leading_system-CfOIc5fi.js.map +0 -1
  48. package/dist/trajectory-D1eq9eue.js.map +0 -1
  49. package/dist/viewer-app/assets/index-BBEYkjnQ.js +0 -2
@@ -1,270 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
4
- import { appendFileSync, mkdirSync } from "node:fs";
5
- //#region src/adapters/trajectory_recorder.ts
6
- /**
7
- * Shared span/record core for trajectory loggers.
8
- *
9
- * Every Fascicle trajectory logger emits the same wire format (one JSON object
10
- * per event) and differs only in where each event goes: `line_logger` writes a
11
- * line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they
12
- * share, parameterized by a single `emit` sink.
13
- *
14
- * `start_span` and `end_span` each emit one event; `record` emits the event as
15
- * written. When the caller supplies `parent_span_id` in the span meta (the
16
- * runner threads the true structural parent through `RunContext`), that value is
17
- * used verbatim, so span trees are correct even for concurrent children under
18
- * `parallel`/`map`. Only when no parent is supplied does the recorder fall back
19
- * to an in-memory stack of still-open spans, which is best-effort under
20
- * concurrency.
21
- */
22
- /**
23
- * Build a `TrajectoryLogger` whose events are handed, one at a time, to `emit`.
24
- */
25
- function trajectory_recorder(emit) {
26
- const stack = [];
27
- const start_span = (name, meta) => {
28
- const span_id = `${name}:${randomUUID().slice(0, 8)}`;
29
- const event = {
30
- kind: "span_start",
31
- span_id,
32
- name,
33
- ...meta
34
- };
35
- if (event["parent_span_id"] === void 0 && stack.length > 0) event["parent_span_id"] = stack[stack.length - 1];
36
- emit(event);
37
- stack.push(span_id);
38
- return span_id;
39
- };
40
- const end_span = (id, meta) => {
41
- emit({
42
- kind: "span_end",
43
- span_id: id,
44
- ...meta
45
- });
46
- const idx = stack.lastIndexOf(id);
47
- if (idx !== -1) stack.splice(idx, 1);
48
- };
49
- const record = (event) => {
50
- emit({ ...event });
51
- };
52
- return {
53
- record,
54
- start_span,
55
- end_span
56
- };
57
- }
58
- //#endregion
59
- //#region src/adapters/line_logger.ts
60
- /**
61
- * Create a `TrajectoryLogger` that writes one JSON object per line via
62
- * `write_line`.
63
- */
64
- function line_logger(write_line) {
65
- return trajectory_recorder(write_line);
66
- }
67
- //#endregion
68
- //#region src/adapters/filesystem_logger.ts
69
- /**
70
- * Filesystem JSONL trajectory logger.
71
- *
72
- * Appends one JSON object per line to a configured output file. Span
73
- * bookkeeping (including the `parent_span_id` handling that keeps span trees
74
- * correct for concurrent children under `parallel`/`map`) lives in
75
- * `line_logger`. Two concurrent `run(...)` calls that pass distinct logger
76
- * instances (constructed with distinct `output_path`s) share nothing.
77
- *
78
- * Paths are accepted at construction; the logger never reads `process.env`.
79
- */
80
- /**
81
- * Create a `TrajectoryLogger` that appends one JSON object per line to
82
- * `output_path`, creating the parent directory if needed.
83
- */
84
- function filesystem_logger(config) {
85
- const { output_path } = config;
86
- mkdirSync(dirname(output_path), { recursive: true });
87
- return line_logger((event) => {
88
- appendFileSync(output_path, `${JSON.stringify(event)}\n`);
89
- });
90
- }
91
- //#endregion
92
- //#region src/adapters/http_logger.ts
93
- /**
94
- * Default `HttpLoggerFetch`, backed by the global `fetch`.
95
- */
96
- const default_fetch = async (url, init) => {
97
- const res = await fetch(url, init);
98
- return {
99
- ok: res.ok,
100
- status: res.status
101
- };
102
- };
103
- /**
104
- * Create a `TrajectoryLogger` that POSTs each event as NDJSON to
105
- * `config.url`.
106
- *
107
- * Never throws: a transport failure is dropped and reported through the
108
- * optional `on_error` callback, so a dev viewer being unreachable never
109
- * blocks the flow.
110
- */
111
- function http_logger(config) {
112
- const { url, on_error } = config;
113
- const send = config.fetch ?? default_fetch;
114
- const post = (event) => {
115
- const body = `${JSON.stringify(event)}\n`;
116
- send(url, {
117
- method: "POST",
118
- headers: { "content-type": "application/x-ndjson" },
119
- body
120
- }).then((res) => {
121
- if (!res.ok && on_error) on_error(/* @__PURE__ */ new Error(`http_logger: POST ${url} -> ${res.status}`));
122
- }).catch((err) => {
123
- if (on_error) on_error(err);
124
- });
125
- };
126
- return trajectory_recorder(post);
127
- }
128
- //#endregion
129
- //#region src/adapters/noop_logger.ts
130
- /**
131
- * No-op trajectory logger.
132
- *
133
- * Satisfies `TrajectoryLogger` from `core` without emitting any
134
- * output. Used as the default when no logger is supplied to `run(...)` and as
135
- * a cheap fallback in tests that do not care about trajectory output.
136
- */
137
- /**
138
- * Create a `TrajectoryLogger` whose methods do nothing.
139
- */
140
- function noop_logger() {
141
- return {
142
- record: () => {},
143
- start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,
144
- end_span: () => {}
145
- };
146
- }
147
- //#endregion
148
- //#region src/adapters/stderr_logger.ts
149
- /**
150
- * Create a `TrajectoryLogger` that writes one JSON object per line to
151
- * stderr, or to `options.stream` when supplied.
152
- */
153
- function stderr_logger(options = {}) {
154
- const stream = options.stream ?? process.stderr;
155
- return line_logger((event) => {
156
- try {
157
- stream.write(`${JSON.stringify(event)}\n`);
158
- } catch {}
159
- });
160
- }
161
- //#endregion
162
- //#region src/adapters/tee_logger.ts
163
- /**
164
- * Create a `TrajectoryLogger` that fans every call out to `loggers`.
165
- */
166
- function tee_logger(...loggers) {
167
- if (loggers.length === 0) throw new Error("tee_logger: at least one logger required");
168
- const id_map = /* @__PURE__ */ new Map();
169
- const safe_each = (fn) => {
170
- for (let i = 0; i < loggers.length; i += 1) {
171
- const l = loggers[i];
172
- if (l === void 0) continue;
173
- try {
174
- fn(l, i);
175
- } catch {}
176
- }
177
- };
178
- return {
179
- record: (event) => {
180
- safe_each((l) => l.record(event));
181
- },
182
- start_span: (name, meta) => {
183
- const ids = [];
184
- safe_each((l) => {
185
- ids.push(l.start_span(name, meta));
186
- });
187
- const canonical = ids[0] ?? `${name}:tee`;
188
- if (loggers.length > 1) id_map.set(canonical, ids);
189
- return canonical;
190
- },
191
- end_span: (id, meta) => {
192
- const ids = id_map.get(id);
193
- if (ids === void 0) {
194
- safe_each((l) => l.end_span(id, meta));
195
- return;
196
- }
197
- id_map.delete(id);
198
- safe_each((l, idx) => l.end_span(ids[idx] ?? id, meta));
199
- }
200
- };
201
- }
202
- //#endregion
203
- //#region src/adapters/filesystem_store.ts
204
- /**
205
- * Filesystem-backed checkpoint store.
206
- *
207
- * Satisfies `CheckpointStore` from `core`. Each key is stored as
208
- * a JSON file under the configured root directory. Writes are all-or-nothing:
209
- * values are written to a temporary sibling file and then atomically renamed
210
- * into place, so an interrupted write never leaves a partially written file
211
- * at the target key. On `get`, a missing file, a partial temp file that was
212
- * never atomically renamed, or a JSON parse failure each read as a cache
213
- * miss (returning `null`) rather than an error.
214
- *
215
- * Paths are accepted at construction; the store never reads `process.env`.
216
- */
217
- /**
218
- * Turn a checkpoint key into a filesystem-safe filename.
219
- *
220
- * Slugs the key down to `[a-zA-Z0-9._-]` and appends a short hash of the
221
- * full key, so two keys that slug to the same string still land on distinct
222
- * files.
223
- */
224
- function safe_filename(key) {
225
- const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
226
- return `${key.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64)}.${hash}.json`;
227
- }
228
- /**
229
- * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.
230
- */
231
- function filesystem_store(config) {
232
- const { root_dir } = config;
233
- const ensure_root = async () => {
234
- await mkdir(root_dir, { recursive: true });
235
- };
236
- const path_for = (key) => join(root_dir, safe_filename(key));
237
- const get = async (key) => {
238
- const path = path_for(key);
239
- let raw;
240
- try {
241
- raw = await readFile(path, "utf8");
242
- } catch {
243
- return null;
244
- }
245
- try {
246
- return JSON.parse(raw);
247
- } catch {
248
- return null;
249
- }
250
- };
251
- const set = async (key, value) => {
252
- await ensure_root();
253
- const target = path_for(key);
254
- const tmp = `${target}.${randomUUID().slice(0, 8)}.tmp`;
255
- await writeFile(tmp, JSON.stringify(value), "utf8");
256
- await rename(tmp, target);
257
- };
258
- const delete_key = async (key) => {
259
- await rm(path_for(key), { force: true });
260
- };
261
- return {
262
- get,
263
- set,
264
- delete: delete_key
265
- };
266
- }
267
- //#endregion
268
- export { http_logger as a, noop_logger as i, tee_logger as n, filesystem_logger as o, stderr_logger as r, filesystem_store as t };
269
-
270
- //# sourceMappingURL=adapters-CutexJd3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapters-CutexJd3.js","names":[],"sources":["../src/adapters/trajectory_recorder.ts","../src/adapters/line_logger.ts","../src/adapters/filesystem_logger.ts","../src/adapters/http_logger.ts","../src/adapters/noop_logger.ts","../src/adapters/stderr_logger.ts","../src/adapters/tee_logger.ts","../src/adapters/filesystem_store.ts"],"sourcesContent":["/**\n * Shared span/record core for trajectory loggers.\n *\n * Every Fascicle trajectory logger emits the same wire format (one JSON object\n * per event) and differs only in where each event goes: `line_logger` writes a\n * line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they\n * share, parameterized by a single `emit` sink.\n *\n * `start_span` and `end_span` each emit one event; `record` emits the event as\n * written. When the caller supplies `parent_span_id` in the span meta (the\n * runner threads the true structural parent through `RunContext`), that value is\n * used verbatim, so span trees are correct even for concurrent children under\n * `parallel`/`map`. Only when no parent is supplied does the recorder fall back\n * to an in-memory stack of still-open spans, which is best-effort under\n * concurrency.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Build a `TrajectoryLogger` whose events are handed, one at a time, to `emit`.\n */\nexport function trajectory_recorder(\n emit: (event: Record<string, unknown>) => void,\n): TrajectoryLogger {\n const stack: string[] = []\n\n const start_span: TrajectoryLogger['start_span'] = (name, meta) => {\n const span_id = `${name}:${randomUUID().slice(0, 8)}`\n const event: Record<string, unknown> = { kind: 'span_start', span_id, name, ...meta }\n // Prefer the caller-threaded structural parent; fall back to the open-span\n // stack only when none was supplied (best-effort under concurrency).\n if (event['parent_span_id'] === undefined && stack.length > 0) {\n event['parent_span_id'] = stack[stack.length - 1]\n }\n emit(event)\n stack.push(span_id)\n return span_id\n }\n\n const end_span: TrajectoryLogger['end_span'] = (id, meta) => {\n emit({ kind: 'span_end', span_id: id, ...meta })\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n }\n\n const record: TrajectoryLogger['record'] = (event) => {\n emit({ ...event })\n }\n\n return { record, start_span, end_span }\n}\n","/**\n * Line-oriented trajectory logger core.\n *\n * `filesystem_logger` and `stderr_logger` emit the same wire format (one JSON\n * object per line) and differ only in where the line goes. Both build on this:\n * `line_logger` adapts the shared span/record core (`trajectory_recorder`) to a\n * `write_line` sink, so the span bookkeeping and `parent_span_id` handling that\n * keep span trees correct under `parallel`/`map` live in exactly one place.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { trajectory_recorder } from './trajectory_recorder.js'\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line via\n * `write_line`.\n */\nexport function line_logger(write_line: (event: Record<string, unknown>) => void): TrajectoryLogger {\n return trajectory_recorder(write_line)\n}\n","/**\n * Filesystem JSONL trajectory logger.\n *\n * Appends one JSON object per line to a configured output file. Span\n * bookkeeping (including the `parent_span_id` handling that keeps span trees\n * correct for concurrent children under `parallel`/`map`) lives in\n * `line_logger`. Two concurrent `run(...)` calls that pass distinct logger\n * instances (constructed with distinct `output_path`s) share nothing.\n *\n * Paths are accepted at construction; the logger never reads `process.env`.\n */\n\nimport { appendFileSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type FilesystemLoggerConfig = {\n readonly output_path: string\n}\n\n/**\n * Create a `TrajectoryLogger` that appends one JSON object per line to\n * `output_path`, creating the parent directory if needed.\n */\nexport function filesystem_logger(config: FilesystemLoggerConfig): TrajectoryLogger {\n const { output_path } = config\n mkdirSync(dirname(output_path), { recursive: true })\n\n return line_logger((event) => {\n appendFileSync(output_path, `${JSON.stringify(event)}\\n`)\n })\n}\n","/**\n * HTTP push trajectory logger.\n *\n * Conforms to `TrajectoryLogger`. POSTs each event as a single line of\n * newline-delimited JSON to a configured URL. Pairs naturally with the\n * Fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the\n * receiver can be anything that accepts NDJSON over HTTP.\n *\n * Failure policy: drop on transport error and invoke the optional `on_error`\n * callback. Never throws, never blocks the user's flow on a dev tool being\n * up. The flow always wins; the viewer is best-effort.\n *\n * Span bookkeeping (including the `parent_span_id` handling that mirrors\n * `filesystem_logger` so the wire format is identical) lives in the shared\n * `trajectory_recorder`; this adapter only supplies the emit sink.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { trajectory_recorder } from './trajectory_recorder.js'\n\nexport type HttpLoggerFetch = (\n url: string,\n init: { method: 'POST'; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number }>\n\nexport type HttpLoggerConfig = {\n readonly url: string\n readonly fetch?: HttpLoggerFetch\n readonly on_error?: (err: unknown) => void\n}\n\n/**\n * Default `HttpLoggerFetch`, backed by the global `fetch`.\n */\nconst default_fetch: HttpLoggerFetch = async (url, init) => {\n const res = await fetch(url, init)\n return { ok: res.ok, status: res.status }\n}\n\n/**\n * Create a `TrajectoryLogger` that POSTs each event as NDJSON to\n * `config.url`.\n *\n * Never throws: a transport failure is dropped and reported through the\n * optional `on_error` callback, so a dev viewer being unreachable never\n * blocks the flow.\n */\nexport function http_logger(config: HttpLoggerConfig): TrajectoryLogger {\n const { url, on_error } = config\n const send = config.fetch ?? default_fetch\n\n const post = (event: Record<string, unknown>): void => {\n const body = `${JSON.stringify(event)}\\n`\n void send(url, {\n method: 'POST',\n headers: { 'content-type': 'application/x-ndjson' },\n body,\n })\n .then((res) => {\n if (!res.ok && on_error) on_error(new Error(`http_logger: POST ${url} -> ${res.status}`))\n })\n .catch((err: unknown) => {\n if (on_error) on_error(err)\n })\n }\n\n return trajectory_recorder(post)\n}\n","/**\n * No-op trajectory logger.\n *\n * Satisfies `TrajectoryLogger` from `core` without emitting any\n * output. Used as the default when no logger is supplied to `run(...)` and as\n * a cheap fallback in tests that do not care about trajectory output.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` whose methods do nothing.\n */\nexport function noop_logger(): TrajectoryLogger {\n return {\n record: () => {},\n start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,\n end_span: () => {},\n }\n}\n","/**\n * Stderr JSONL trajectory logger.\n *\n * Writes one JSON object per line to stderr (or an injected stream), leaving\n * stdout untouched. This is the blessed console logger for agents that run as\n * somebody's child process: under the stdio agent contract, stdout carries the\n * result envelope and belongs to the parent, so trajectory must go elsewhere.\n * The wire format is identical to `filesystem_logger`, so captured stderr is a\n * valid trajectory JSONL file (`2>events.jsonl`) the viewer parses unchanged.\n *\n * Writes never throw: a broken pipe or closed stream drops the event rather\n * than failing the flow.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type StderrLoggerOptions = {\n readonly stream?: { write(chunk: string): unknown }\n}\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line to\n * stderr, or to `options.stream` when supplied.\n */\nexport function stderr_logger(options: StderrLoggerOptions = {}): TrajectoryLogger {\n const stream = options.stream ?? process.stderr\n return line_logger((event) => {\n try {\n stream.write(`${JSON.stringify(event)}\\n`)\n } catch {\n // Never throw from a logger; the flow always wins.\n }\n })\n}\n","/**\n * tee_logger: fan one TrajectoryLogger contract out to many sinks.\n *\n * Each sink receives every record/start_span/end_span call. Sinks are called\n * in registration order and exceptions in one sink do not prevent the others\n * from receiving the event.\n *\n * The first sink's `start_span` return value is treated as canonical and\n * returned to the caller; the tee remembers each sink's per-sink id so that\n * `end_span(canonical_id, ...)` translates back to the right id for each sink.\n * Within any one sink the wire format stays internally consistent; only the\n * across-sink ids may differ.\n */\n\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` that fans every call out to `loggers`.\n */\nexport function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger {\n if (loggers.length === 0) {\n throw new Error('tee_logger: at least one logger required')\n }\n\n const id_map = new Map<string, ReadonlyArray<string>>()\n\n const safe_each = (fn: (l: TrajectoryLogger, idx: number) => void): void => {\n for (let i = 0; i < loggers.length; i += 1) {\n const l = loggers[i]\n if (l === undefined) continue\n try {\n fn(l, i)\n } catch {\n // best-effort fan-out: a misbehaving sink must not derail the others\n }\n }\n }\n\n return {\n record: (event) => {\n safe_each((l) => l.record(event))\n },\n start_span: (name, meta) => {\n const ids: string[] = []\n safe_each((l) => {\n ids.push(l.start_span(name, meta))\n })\n const canonical = ids[0] ?? `${name}:tee`\n if (loggers.length > 1) id_map.set(canonical, ids)\n return canonical\n },\n end_span: (id, meta) => {\n const ids = id_map.get(id)\n if (ids === undefined) {\n safe_each((l) => l.end_span(id, meta))\n return\n }\n id_map.delete(id)\n safe_each((l, idx) => l.end_span(ids[idx] ?? id, meta))\n },\n }\n}\n","/**\n * Filesystem-backed checkpoint store.\n *\n * Satisfies `CheckpointStore` from `core`. Each key is stored as\n * a JSON file under the configured root directory. Writes are all-or-nothing:\n * values are written to a temporary sibling file and then atomically renamed\n * into place, so an interrupted write never leaves a partially written file\n * at the target key. On `get`, a missing file, a partial temp file that was\n * never atomically renamed, or a JSON parse failure each read as a cache\n * miss (returning `null`) rather than an error.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { CheckpointStore } from '#core'\n\nexport type FilesystemStoreConfig = {\n readonly root_dir: string\n}\n\n/**\n * Turn a checkpoint key into a filesystem-safe filename.\n *\n * Slugs the key down to `[a-zA-Z0-9._-]` and appends a short hash of the\n * full key, so two keys that slug to the same string still land on distinct\n * files.\n */\nfunction safe_filename(key: string): string {\n const hash = createHash('sha256').update(key).digest('hex').slice(0, 12)\n const slug = key.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64)\n return `${slug}.${hash}.json`\n}\n\n/**\n * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.\n */\nexport function filesystem_store(config: FilesystemStoreConfig): CheckpointStore {\n const { root_dir } = config\n\n const ensure_root = async (): Promise<void> => {\n await mkdir(root_dir, { recursive: true })\n }\n\n const path_for = (key: string): string => join(root_dir, safe_filename(key))\n\n const get = async (key: string): Promise<unknown> => {\n const path = path_for(key)\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch {\n return null\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n }\n\n const set = async (key: string, value: unknown): Promise<void> => {\n await ensure_root()\n const target = path_for(key)\n const tmp = `${target}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, JSON.stringify(value), 'utf8')\n await rename(tmp, target)\n }\n\n const delete_key = async (key: string): Promise<void> => {\n const target = path_for(key)\n await rm(target, { force: true })\n }\n\n return { get, set, delete: delete_key }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,oBACd,MACkB;CAClB,MAAM,QAAkB,CAAC;CAEzB,MAAM,cAA8C,MAAM,SAAS;EACjE,MAAM,UAAU,GAAG,KAAK,GAAG,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC;EAClD,MAAM,QAAiC;GAAE,MAAM;GAAc;GAAS;GAAM,GAAG;EAAK;EAGpF,IAAI,MAAM,sBAAsB,KAAA,KAAa,MAAM,SAAS,GAC1D,MAAM,o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