fascicle 0.12.13 → 0.13.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +34 -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-DK7g1Z40.js} +887 -74
  9. package/dist/core-DK7g1Z40.js.map +1 -0
  10. package/dist/diagram_bin.d.ts +1 -2
  11. package/dist/diagram_bin.js +5 -2
  12. package/dist/diagram_bin.js.map +1 -1
  13. package/dist/{engine-Ct4LBzb9.js → engine-BOGuc0X2.js} +366 -36
  14. package/dist/engine-BOGuc0X2.js.map +1 -0
  15. package/dist/index.d.ts +342 -180
  16. package/dist/index.js +149 -123
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-BcPDqE5C.js → invoke-Beef3R3X.js} +3 -3
  19. package/dist/{invoke-BcPDqE5C.js.map → invoke-Beef3R3X.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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.13.1 — 2026-10-09
4
+
5
+ ### Added
6
+
7
+ - **`describe.replays(step)` names the steps a resume would pay for twice, before anything runs.** A run that resumes at a `suspend` replays the flow from its input, so a step marked `side_effect` (every `model_call` is) that can run before the gate runs again, unless a `checkpoint` that holds the step and not the gate stored its result. It reads the `describe.json` tree and returns a `ReplayHint` (`{ id, label, gates }`) for each such step, so a test can hold a flow to an empty list, and on `examples/durable-runs` it names the same step that the run's `step_replayed` event reports. Inside a `sequence`, a `chain`, a `fallback`, or one round of a `loop` the children run in order, `parallel` members and a step's arms can start in either order, and the arms of a `branch` never run against each other. A model call that a step's body makes without declaring it as an `arm` is out of its sight.
8
+ - **`describe.diagram` and `fascicle-diagram` can mark those steps.** Pass `replays: true` to `describe.diagram`, or `--replays` to the bin, and each of those rows ends with the gates it runs before, as in `(replays before approve)`. Without the option the diagram is unchanged byte for byte.
9
+
10
+ ## v0.13.0 — 2026-10-09
11
+
12
+ ### Added
13
+
14
+ - **`durable({ store })` keeps a suspended run in a store, so events can drive it from fresh processes.** `start`, `resume`, `get`, and `delete` drive a run one event at a time (a webhook, a finished job, a deadline timer), and every drive runs the flow again from its input, so replay and checkpoints behave the way they always have. A lease keeps two invocations from driving one run at once, a revision on every write stops a stalled drive from writing over the drive that took the run over, an event that finds the run busy waits in its inbox, and a change to the flow's shape mid-run throws `flow_changed_error` unless you pass `on_flow_change: 'replay'`. `examples/durable-runs` races a webhook and a deadline timer for one gate.
15
+ - **Checkpoint stores can scope and claim.** `CheckpointStore` gains three optional capabilities, which `durable` needs. `scope(prefix)` hands out a store whose keys and claims stand apart from its parent's and that can `clear`, and `claim(key, owner, ttl_ms)` with `release(key, owner)` takes and frees a key per owner. A store without them satisfies the contract as before, and `filesystem_store` implements all three, with claims created through `link(2)` so that two claimers can't both win.
16
+ - **`checkpoint_store_conformance` in `fascicle/testing` proves a store keeps that contract.** It runs 32 checks against fresh stores from your factory, racing claimers, expired claims, damaged values, and a `clear` that mustn't reach a look-alike scope among them, and it returns a report rather than registering tests, so it works under any runner. `examples/object-store` writes a store over an S3-style client, with claims made of conditional writes, and passes every check.
17
+ - **A `suspend` gate can carry a deadline.** `deadline_ms` rides out on the `suspended_error`, the `suspended` event, and the outcome that `run.until_suspended` reports, so whoever drives the run can schedule the timer, and `durable` hands it back as `deadline_at`. `resume_validation_error` carries the `suspend_id` of the gate whose data it refused.
18
+ - **Replayed side effects show up in the trajectory.** `StepMetadata.side_effect` marks a step that isn't free to run twice, and every `model_call` sets it. When a resumed run starts a marked step before it has reached the gates it was resumed at, the runner records a `step_replayed` event, which `is_step_replayed_event` narrows, so a replay that bills you twice shows up before the invoice does.
19
+ - **`map` can settle every item instead of failing on the first.** With `settle: true` every item runs, and the output holds one entry per item, `{ ok: true, value }` or `{ ok: false, error }`. The error is reduced to plain data (`message`, plus `name`, `kind`, and `path` when it has them), so a settled array survives a checkpoint. Each failure records a `map_item_failed` event, which `is_map_item_failed_event` narrows, and `suspended_error` and `aborted_error` still propagate. The config type is `MapSettleConfig`.
20
+
21
+ ### Changed
22
+
23
+ - **`pipe_ui_message_stream_to_response` returns a promise.** As of `ai` 7.0.130, `pipeUIMessageStreamToResponse` returns one, and the wrapper passes it on and resolves once the response has ended.
24
+ - **`filesystem_store` surfaces read failures other than a missing file or one that won't parse.** A permission error or a failing disk used to read as a miss, which could start a durable run over or hand a live claim to a second owner, and now it throws.
25
+
26
+ ### Fixed
27
+
28
+ - **A `suspend` gate named like an `Object.prototype` member resumes correctly.** It read its resume data with a plain index, so a gate named `toString` or `constructor` found the inherited function on any run that passed resume data. It reads only the run's own data now.
29
+
30
+ ### Internal
31
+
32
+ - The dependency audit runs only as `pnpm check:security`, outside `pnpm check` and `check:all`. The braces package (3.0.3) has a high advisory and no patched release, and leaving the audit in the default set would have failed CI and the publish job.
33
+ - The dev toolchain moved to the newest release inside each major (oxlint 1.87, fallow 3.31, checkride 0.13, vitest 4.1.11, and more), and the audit cleared every advisory that had a fix.
34
+ - Nine doc snippets marked for checking sat a blank line away from their fence, so the snippet check skipped them. All of them compile and are checked now, and two doc errors are corrected (ollama native's effort note and the cloud spec's cost guardrail).
35
+
3
36
  ## v0.12.13 — 2026-09-25
4
37
 
5
38
  ### Fixed
@@ -717,7 +750,7 @@ work is in the docs surface, the example apps, and the check suite.
717
750
 
718
751
  ### Changed
719
752
 
720
- - **Breaking: model resolution is now a verbatim pass-through.** `model` is an opaque string sent to the provider unchanged; `provider` selects the transport. One canonical input shape remains — separate `provider` + `model` params — with no interpretation in between.
753
+ - **Breaking: model resolution is now a verbatim pass-through.** `model` is an opaque string sent to the provider unchanged; `provider` selects the transport. One canonical input shape remains (separate `provider` + `model` params), with no interpretation in between.
721
754
  - Removed the `provider:model` colon shorthand. Pass `{ provider: 'openrouter', model: 'anthropic/claude-sonnet-4.5' }` instead of `model: 'openrouter:anthropic/claude-sonnet-4.5'`. Model ids that contain colons (Ollama tags like `qwen3-coder:30b`, Bedrock `...-v1:0`) now ride through untouched.
722
755
  - Removed the built-in `MODEL_FAMILIES` catalog and the `families` engine-config field. Family tokens (`opus`, `sonnet`, `gpt`, `gemini`) no longer expand — pass the provider's concrete id. (The `claude_cli` transport still resolves `opus`/`sonnet`/`haiku` itself, via the CLI.)
723
756
  - Removed the user alias table: `Engine.register_alias` / `unregister_alias` / `resolve_alias` / `list_aliases` and `EngineConfig.aliases`. Keep your own name→id map in your harness if you want shortcuts.
@@ -0,0 +1,447 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { link, mkdir, readFile, readdir, 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`, every optional capability
208
+ * included. Each key is stored as
209
+ * a JSON file under the configured root directory. Writes are all-or-nothing:
210
+ * values are written to a temporary sibling file and then atomically renamed
211
+ * into place, so an interrupted write never leaves a partially written file
212
+ * at the target key. On `get`, a missing file, a partial temp file that was
213
+ * never atomically renamed, or a JSON parse failure each read as a cache
214
+ * miss (returning `null`) rather than an error. Any other failure to read
215
+ * (a permission error, a failing disk) surfaces, because reading it as a miss
216
+ * could start a durable run over, or hand a live claim to a second owner.
217
+ *
218
+ * A scope is a directory beside the values (`<prefix>.scope/`), which makes
219
+ * `clear` one recursive delete. A claim is a directory of numbered
220
+ * generations (`<key>.claim/<n>.json`), and the newest one is the claim. A
221
+ * claimer takes a free or expired key by creating the next generation with
222
+ * `link`, which makes the file appear whole and refuses a target that
223
+ * already exists, so two claimers can't both create it. Taking an expired
224
+ * claim never overwrites a live one, which a rename into place couldn't
225
+ * promise, and a claimer that finds a newer generation than its own has lost.
226
+ * All of this leans on `link` and `rename` being atomic and on a directory
227
+ * listing being current, which a local filesystem gives and a network
228
+ * filesystem may not.
229
+ *
230
+ * Paths are accepted at construction; the store never reads `process.env`.
231
+ */
232
+ /**
233
+ * Turn a key or a scope prefix into a filesystem-safe name.
234
+ *
235
+ * Slugs it down to `[a-zA-Z0-9._-]` and appends a short hash of the whole
236
+ * string, so two strings that slug alike still land on distinct names.
237
+ */
238
+ function safe_name(key) {
239
+ const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
240
+ return `${key.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64)}.${hash}`;
241
+ }
242
+ /**
243
+ * Read the `code` a Node filesystem error carries, if it has one.
244
+ */
245
+ function error_code(err) {
246
+ return err instanceof Error ? Reflect.get(err, "code") : void 0;
247
+ }
248
+ /**
249
+ * Serialize a value for disk. A value JSON has no text for (`undefined`, a
250
+ * bare function) is written as `null`, which reads back as a miss.
251
+ */
252
+ function to_json(value) {
253
+ return JSON.stringify(value) ?? "null";
254
+ }
255
+ /**
256
+ * Write `value` to `path` through a temporary sibling and a rename, so a
257
+ * reader sees the old file or the new one and never a torn one.
258
+ */
259
+ async function write_atomic(path, value) {
260
+ const tmp = `${path}.${randomUUID().slice(0, 8)}.tmp`;
261
+ await writeFile(tmp, to_json(value));
262
+ await rename(tmp, path);
263
+ }
264
+ /**
265
+ * Create `path` holding `value` unless something is already there.
266
+ *
267
+ * The JSON goes to a temporary file first and is hard-linked into place, so
268
+ * the file appears whole, and `link` refuses an existing target, so exactly
269
+ * one of several racing creators sees true.
270
+ */
271
+ async function create_exclusive(path, value) {
272
+ const tmp = `${path}.${randomUUID().slice(0, 8)}.tmp`;
273
+ await writeFile(tmp, to_json(value));
274
+ try {
275
+ await link(tmp, path);
276
+ return true;
277
+ } catch (err) {
278
+ if (error_code(err) === "EEXIST") return false;
279
+ throw err;
280
+ } finally {
281
+ await rm(tmp);
282
+ }
283
+ }
284
+ /**
285
+ * The path of one generation in a claim directory.
286
+ */
287
+ function generation_path(dir, generation) {
288
+ return join(dir, `${generation}.json`);
289
+ }
290
+ /**
291
+ * The newest generation in a claim directory, or 0 when it holds none or
292
+ * doesn't exist yet.
293
+ */
294
+ async function latest_generation(dir) {
295
+ return Math.max(0, ...await generations(dir));
296
+ }
297
+ /**
298
+ * Every generation number present in a claim directory.
299
+ */
300
+ async function generations(dir) {
301
+ let names;
302
+ try {
303
+ names = await readdir(dir);
304
+ } catch (err) {
305
+ if (error_code(err) === "ENOENT") return [];
306
+ throw err;
307
+ }
308
+ return names.flatMap((name) => {
309
+ const match = /^(\d+)\.json$/.exec(name);
310
+ return match === null ? [] : [Number(match[1])];
311
+ });
312
+ }
313
+ /**
314
+ * Read and parse the JSON at `path`, or `null` when the file is missing or
315
+ * doesn't parse. Any other failure surfaces.
316
+ */
317
+ async function read_json(path) {
318
+ let raw;
319
+ try {
320
+ raw = await readFile(path, "utf8");
321
+ } catch (err) {
322
+ if (error_code(err) === "ENOENT") return null;
323
+ throw err;
324
+ }
325
+ try {
326
+ return JSON.parse(raw);
327
+ } catch {
328
+ return null;
329
+ }
330
+ }
331
+ /**
332
+ * Read the claim one generation holds, or null when the file is gone or
333
+ * doesn't hold a claim.
334
+ */
335
+ async function read_claim(path) {
336
+ const parsed = await read_json(path);
337
+ return is_claim_record(parsed) ? parsed : null;
338
+ }
339
+ /**
340
+ * True for the `{ owner, expires_at }` shape a generation file holds.
341
+ */
342
+ function is_claim_record(value) {
343
+ if (typeof value !== "object" || value === null) return false;
344
+ return typeof Reflect.get(value, "owner") === "string" && typeof Reflect.get(value, "expires_at") === "number";
345
+ }
346
+ /**
347
+ * Delete every generation older than `keep`. A claimer only reads the newest
348
+ * generation, so the older ones are history and nothing waits on them.
349
+ */
350
+ async function prune(dir, keep) {
351
+ const stale = (await generations(dir)).filter((generation) => generation < keep);
352
+ await Promise.all(stale.map((generation) => rm(generation_path(dir, generation), { force: true })));
353
+ }
354
+ /**
355
+ * Take or renew the claim in `dir` for `owner`.
356
+ *
357
+ * A live claim held by `owner` is renewed in place. Anything else that isn't
358
+ * a live claim is taken by creating the next generation, and the claimer
359
+ * still loses if a newer generation shows up before it confirms. Only a live
360
+ * claim is ever renewed in place, so an expired one changes hands through
361
+ * `create_exclusive` alone and two claimers can't both win it. A renewal that
362
+ * lands at the very instant its claim expires can still race a takeover, and
363
+ * it loses whenever the takeover's generation appears before it confirms.
364
+ */
365
+ async function claim_in(dir, owner, ttl_ms) {
366
+ await mkdir(dir, { recursive: true });
367
+ const generation = await latest_generation(dir);
368
+ const current = await read_claim(generation_path(dir, generation));
369
+ const now = Date.now();
370
+ const claim = {
371
+ owner,
372
+ expires_at: now + ttl_ms
373
+ };
374
+ if (current !== null && current.expires_at > now) {
375
+ if (current.owner !== owner) return false;
376
+ await write_atomic(generation_path(dir, generation), claim);
377
+ return await latest_generation(dir) === generation;
378
+ }
379
+ const next = generation + 1;
380
+ if (!await create_exclusive(generation_path(dir, next), claim)) return false;
381
+ if (await latest_generation(dir) !== next) return false;
382
+ await prune(dir, next);
383
+ return true;
384
+ }
385
+ /**
386
+ * Release the claim in `dir` when `owner` holds it.
387
+ *
388
+ * The newest generation is rewritten as expired rather than deleted, so
389
+ * generation numbers only ever grow and a slow claimer can't recreate one
390
+ * that was already taken. A directory that vanished meanwhile (its scope was
391
+ * cleared) has nothing left to release.
392
+ */
393
+ async function release_in(dir, owner) {
394
+ const path = generation_path(dir, await latest_generation(dir));
395
+ if ((await read_claim(path))?.owner !== owner) return;
396
+ try {
397
+ await write_atomic(path, {
398
+ owner,
399
+ expires_at: 0
400
+ });
401
+ } catch (err) {
402
+ if (error_code(err) !== "ENOENT") throw err;
403
+ }
404
+ }
405
+ /**
406
+ * Build the store rooted at `root_dir`, scopes and claims included.
407
+ */
408
+ function store_at(root_dir) {
409
+ const value_path = (key) => join(root_dir, `${safe_name(key)}.json`);
410
+ const claim_dir = (key) => join(root_dir, `${safe_name(key)}.claim`);
411
+ const get = (key) => read_json(value_path(key));
412
+ const set = async (key, value) => {
413
+ await mkdir(root_dir, { recursive: true });
414
+ await write_atomic(value_path(key), value);
415
+ };
416
+ const delete_key = async (key) => {
417
+ await rm(value_path(key), { force: true });
418
+ };
419
+ const scope = (prefix) => {
420
+ const dir = join(root_dir, `${safe_name(prefix)}.scope`);
421
+ return {
422
+ ...store_at(dir),
423
+ clear: () => rm(dir, {
424
+ recursive: true,
425
+ force: true
426
+ })
427
+ };
428
+ };
429
+ return {
430
+ get,
431
+ set,
432
+ delete: delete_key,
433
+ scope,
434
+ claim: (key, owner, ttl_ms) => claim_in(claim_dir(key), owner, ttl_ms),
435
+ release: (key, owner) => release_in(claim_dir(key), owner)
436
+ };
437
+ }
438
+ /**
439
+ * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.
440
+ */
441
+ function filesystem_store(config) {
442
+ return store_at(config.root_dir);
443
+ }
444
+ //#endregion
445
+ 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 };
446
+
447
+ //# sourceMappingURL=adapters-DNnzeLxr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters-DNnzeLxr.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`, every optional capability\n * included. 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. Any other failure to read\n * (a permission error, a failing disk) surfaces, because reading it as a miss\n * could start a durable run over, or hand a live claim to a second owner.\n *\n * A scope is a directory beside the values (`<prefix>.scope/`), which makes\n * `clear` one recursive delete. A claim is a directory of numbered\n * generations (`<key>.claim/<n>.json`), and the newest one is the claim. A\n * claimer takes a free or expired key by creating the next generation with\n * `link`, which makes the file appear whole and refuses a target that\n * already exists, so two claimers can't both create it. Taking an expired\n * claim never overwrites a live one, which a rename into place couldn't\n * promise, and a claimer that finds a newer generation than its own has lost.\n * All of this leans on `link` and `rename` being atomic and on a directory\n * listing being current, which a local filesystem gives and a network\n * filesystem may not.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { link, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nexport type FilesystemStoreConfig = {\n readonly root_dir: string\n}\n\n/**\n * What `filesystem_store` returns: a `CheckpointStore` with every optional\n * capability, which is what `durable` needs from its store.\n */\nexport type FilesystemStore = {\n readonly get: (key: string) => Promise<unknown>\n readonly set: (key: string, value: unknown) => Promise<void>\n readonly delete: (key: string) => Promise<void>\n readonly scope: (prefix: string) => FilesystemScopedStore\n readonly claim: (key: string, owner: string, ttl_ms: number) => Promise<boolean>\n readonly release: (key: string, owner: string) => Promise<void>\n}\n\n/**\n * A scope of a `filesystem_store`, which can also `clear`.\n */\nexport type FilesystemScopedStore = FilesystemStore & {\n readonly clear: () => Promise<void>\n}\n\ntype ClaimRecord = {\n readonly owner: string\n readonly expires_at: number\n}\n\n/**\n * Turn a key or a scope prefix into a filesystem-safe name.\n *\n * Slugs it down to `[a-zA-Z0-9._-]` and appends a short hash of the whole\n * string, so two strings that slug alike still land on distinct names.\n */\nfunction safe_name(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}`\n}\n\n/**\n * Read the `code` a Node filesystem error carries, if it has one.\n */\nfunction error_code(err: unknown): unknown {\n return err instanceof Error ? Reflect.get(err, 'code') : undefined\n}\n\n/**\n * Serialize a value for disk. A value JSON has no text for (`undefined`, a\n * bare function) is written as `null`, which reads back as a miss.\n */\nfunction to_json(value: unknown): string {\n const text: string | undefined = JSON.stringify(value)\n return text ?? 'null'\n}\n\n/**\n * Write `value` to `path` through a temporary sibling and a rename, so a\n * reader sees the old file or the new one and never a torn one.\n */\nasync function write_atomic(path: string, value: unknown): Promise<void> {\n // Stryker disable next-line MethodExpression: the temporary name only has to be unique, which the whole UUID is as well.\n const tmp = `${path}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, to_json(value))\n await rename(tmp, path)\n}\n\n/**\n * Create `path` holding `value` unless something is already there.\n *\n * The JSON goes to a temporary file first and is hard-linked into place, so\n * the file appears whole, and `link` refuses an existing target, so exactly\n * one of several racing creators sees true.\n */\nasync function create_exclusive(path: string, value: unknown): Promise<boolean> {\n // Stryker disable next-line MethodExpression: the temporary name only has to be unique, which the whole UUID is as well.\n const tmp = `${path}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, to_json(value))\n try {\n await link(tmp, path)\n return true\n } catch (err) {\n if (error_code(err) === 'EEXIST') return false\n throw err\n } finally {\n await rm(tmp)\n }\n}\n\n/**\n * The path of one generation in a claim directory.\n */\nfunction generation_path(dir: string, generation: number): string {\n return join(dir, `${generation}.json`)\n}\n\n/**\n * The newest generation in a claim directory, or 0 when it holds none or\n * doesn't exist yet.\n */\nasync function latest_generation(dir: string): Promise<number> {\n return Math.max(0, ...(await generations(dir)))\n}\n\n/**\n * Every generation number present in a claim directory.\n */\nasync function generations(dir: string): Promise<number[]> {\n let names: string[]\n try {\n names = await readdir(dir)\n } catch (err) {\n if (error_code(err) === 'ENOENT') return []\n throw err\n }\n return names.flatMap((name) => {\n const match = /^(\\d+)\\.json$/.exec(name)\n return match === null ? [] : [Number(match[1])]\n })\n}\n\n/**\n * Read and parse the JSON at `path`, or `null` when the file is missing or\n * doesn't parse. Any other failure surfaces.\n */\nasync function read_json(path: string): Promise<unknown> {\n let raw: string\n try {\n // Stryker disable next-line StringLiteral: without an encoding readFile hands back a Buffer, which JSON.parse turns into the same text before parsing.\n raw = await readFile(path, 'utf8')\n } catch (err) {\n if (error_code(err) === 'ENOENT') return null\n throw err\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n}\n\n/**\n * Read the claim one generation holds, or null when the file is gone or\n * doesn't hold a claim.\n */\nasync function read_claim(path: string): Promise<ClaimRecord | null> {\n const parsed = await read_json(path)\n return is_claim_record(parsed) ? parsed : null\n}\n\n/**\n * True for the `{ owner, expires_at }` shape a generation file holds.\n */\nfunction is_claim_record(value: unknown): value is ClaimRecord {\n // Stryker disable next-line BooleanLiteral: a value that isn't an object reads as free either way, since null fails the null check and a primitive has no expiry to keep it live.\n if (typeof value !== 'object' || value === null) return false\n return (\n typeof Reflect.get(value, 'owner') === 'string' &&\n typeof Reflect.get(value, 'expires_at') === 'number'\n )\n}\n\n/**\n * Delete every generation older than `keep`. A claimer only reads the newest\n * generation, so the older ones are history and nothing waits on them.\n */\nasync function prune(dir: string, keep: number): Promise<void> {\n const stale = (await generations(dir)).filter((generation) => generation < keep)\n await Promise.all(stale.map((generation) => rm(generation_path(dir, generation), { force: true })))\n}\n\n/**\n * Take or renew the claim in `dir` for `owner`.\n *\n * A live claim held by `owner` is renewed in place. Anything else that isn't\n * a live claim is taken by creating the next generation, and the claimer\n * still loses if a newer generation shows up before it confirms. Only a live\n * claim is ever renewed in place, so an expired one changes hands through\n * `create_exclusive` alone and two claimers can't both win it. A renewal that\n * lands at the very instant its claim expires can still race a takeover, and\n * it loses whenever the takeover's generation appears before it confirms.\n */\nasync function claim_in(dir: string, owner: string, ttl_ms: number): Promise<boolean> {\n await mkdir(dir, { recursive: true })\n const generation = await latest_generation(dir)\n const current = await read_claim(generation_path(dir, generation))\n const now = Date.now()\n const claim: ClaimRecord = { owner, expires_at: now + ttl_ms }\n if (current !== null && current.expires_at > now) {\n if (current.owner !== owner) return false\n await write_atomic(generation_path(dir, generation), claim)\n return (await latest_generation(dir)) === generation\n }\n const next = generation + 1\n if (!(await create_exclusive(generation_path(dir, next), claim))) return false\n if ((await latest_generation(dir)) !== next) return false\n await prune(dir, next)\n return true\n}\n\n/**\n * Release the claim in `dir` when `owner` holds it.\n *\n * The newest generation is rewritten as expired rather than deleted, so\n * generation numbers only ever grow and a slow claimer can't recreate one\n * that was already taken. A directory that vanished meanwhile (its scope was\n * cleared) has nothing left to release.\n */\nasync function release_in(dir: string, owner: string): Promise<void> {\n const generation = await latest_generation(dir)\n const path = generation_path(dir, generation)\n const current = await read_claim(path)\n if (current?.owner !== owner) return\n try {\n await write_atomic(path, { owner, expires_at: 0 })\n } catch (err) {\n if (error_code(err) !== 'ENOENT') throw err\n }\n}\n\n/**\n * Build the store rooted at `root_dir`, scopes and claims included.\n */\nfunction store_at(root_dir: string): FilesystemStore {\n const value_path = (key: string): string => join(root_dir, `${safe_name(key)}.json`)\n const claim_dir = (key: string): string => join(root_dir, `${safe_name(key)}.claim`)\n\n const get = (key: string): Promise<unknown> => read_json(value_path(key))\n\n const set = async (key: string, value: unknown): Promise<void> => {\n await mkdir(root_dir, { recursive: true })\n await write_atomic(value_path(key), value)\n }\n\n const delete_key = async (key: string): Promise<void> => {\n await rm(value_path(key), { force: true })\n }\n\n const scope = (prefix: string): FilesystemScopedStore => {\n const dir = join(root_dir, `${safe_name(prefix)}.scope`)\n return {\n ...store_at(dir),\n clear: () => rm(dir, { recursive: true, force: true }),\n }\n }\n\n return {\n get,\n set,\n delete: delete_key,\n scope,\n claim: (key, owner, ttl_ms) => claim_in(claim_dir(key), owner, ttl_ms),\n release: (key, owner) => release_in(claim_dir(key), owner),\n }\n}\n\n/**\n * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.\n */\nexport function filesystem_store(config: FilesystemStoreConfig): FilesystemStore {\n return store_at(config.root_dir)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,oBACd,MACkB;CAClB,MAAM,QAAkB,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,UAAU,GAAG,UAAU,GAAG,EAAE,OAAO;CAEnF,MAAM,OAAO,QAAkC,UAAU,WAAW,GAAG,CAAC;CAExE,MAAM,MAAM,OAAO,KAAa,UAAkC;EAChE,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;EACzC,MAAM,aAAa,WAAW,GAAG,GAAG,KAAK;CAC3C;CAEA,MAAM,aAAa,OAAO,QAA+B;EACvD,MAAM,GAAG,WAAW,GAAG,GAAG,EAAE,OAAO,KAAK,CAAC;CAC3C;CAEA,MAAM,SAAS,WAA0C;EACvD,MAAM,MAAM,KAAK,UAAU,GAAG,UAAU,MAAM,EAAE,OAAO;EACvD,OAAO;GACL,GAAG,SAAS,GAAG;GACf,aAAa,GAAG,KAAK;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;EACvD;CACF;CAEA,OAAO;EACL;EACA;EACA,QAAQ;EACR;EACA,QAAQ,KAAK,OAAO,WAAW,SAAS,UAAU,GAAG,GAAG,OAAO,MAAM;EACrE,UAAU,KAAK,UAAU,WAAW,UAAU,GAAG,GAAG,KAAK;CAC3D;AACF;;;;AAKA,SAAgB,iBAAiB,QAAgD;CAC/E,OAAO,SAAS,OAAO,QAAQ;AACjC"}
@@ -1,5 +1,4 @@
1
- import { m as TrajectoryLogger, n as CheckpointStore } from "./types-BasW4Wwb.js";
2
-
1
+ import { h as TrajectoryLogger } from "./types-CPqLZOEr.js";
3
2
  //#region src/adapters/filesystem_logger.d.ts
4
3
  type FilesystemLoggerConfig = {
5
4
  readonly output_path: string;
@@ -8,7 +7,7 @@ type FilesystemLoggerConfig = {
8
7
  * Create a `TrajectoryLogger` that appends one JSON object per line to
9
8
  * `output_path`, creating the parent directory if needed.
10
9
  */
11
- declare function filesystem_logger(config: FilesystemLoggerConfig): TrajectoryLogger;
10
+ export declare function filesystem_logger(config: FilesystemLoggerConfig): TrajectoryLogger;
12
11
  //#endregion
13
12
  //#region src/adapters/http_logger.d.ts
14
13
  type HttpLoggerFetch = (url: string, init: {
@@ -32,13 +31,13 @@ type HttpLoggerConfig = {
32
31
  * optional `on_error` callback, so a dev viewer being unreachable never
33
32
  * blocks the flow.
34
33
  */
35
- declare function http_logger(config: HttpLoggerConfig): TrajectoryLogger;
34
+ export declare function http_logger(config: HttpLoggerConfig): TrajectoryLogger;
36
35
  //#endregion
37
36
  //#region src/adapters/noop_logger.d.ts
38
37
  /**
39
38
  * Create a `TrajectoryLogger` whose methods do nothing.
40
39
  */
41
- declare function noop_logger(): TrajectoryLogger;
40
+ export declare function noop_logger(): TrajectoryLogger;
42
41
  //#endregion
43
42
  //#region src/adapters/stderr_logger.d.ts
44
43
  type StderrLoggerOptions = {
@@ -50,22 +49,68 @@ type StderrLoggerOptions = {
50
49
  * Create a `TrajectoryLogger` that writes one JSON object per line to
51
50
  * stderr, or to `options.stream` when supplied.
52
51
  */
53
- declare function stderr_logger(options?: StderrLoggerOptions): TrajectoryLogger;
52
+ export declare function stderr_logger(options?: StderrLoggerOptions): TrajectoryLogger;
54
53
  //#endregion
55
54
  //#region src/adapters/tee_logger.d.ts
56
55
  /**
57
56
  * Create a `TrajectoryLogger` that fans every call out to `loggers`.
58
57
  */
59
- declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
58
+ export declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
60
59
  //#endregion
61
60
  //#region src/adapters/filesystem_store.d.ts
61
+ /**
62
+ * Filesystem-backed checkpoint store.
63
+ *
64
+ * Satisfies `CheckpointStore` from `core`, every optional capability
65
+ * included. Each key is stored as
66
+ * a JSON file under the configured root directory. Writes are all-or-nothing:
67
+ * values are written to a temporary sibling file and then atomically renamed
68
+ * into place, so an interrupted write never leaves a partially written file
69
+ * at the target key. On `get`, a missing file, a partial temp file that was
70
+ * never atomically renamed, or a JSON parse failure each read as a cache
71
+ * miss (returning `null`) rather than an error. Any other failure to read
72
+ * (a permission error, a failing disk) surfaces, because reading it as a miss
73
+ * could start a durable run over, or hand a live claim to a second owner.
74
+ *
75
+ * A scope is a directory beside the values (`<prefix>.scope/`), which makes
76
+ * `clear` one recursive delete. A claim is a directory of numbered
77
+ * generations (`<key>.claim/<n>.json`), and the newest one is the claim. A
78
+ * claimer takes a free or expired key by creating the next generation with
79
+ * `link`, which makes the file appear whole and refuses a target that
80
+ * already exists, so two claimers can't both create it. Taking an expired
81
+ * claim never overwrites a live one, which a rename into place couldn't
82
+ * promise, and a claimer that finds a newer generation than its own has lost.
83
+ * All of this leans on `link` and `rename` being atomic and on a directory
84
+ * listing being current, which a local filesystem gives and a network
85
+ * filesystem may not.
86
+ *
87
+ * Paths are accepted at construction; the store never reads `process.env`.
88
+ */
62
89
  type FilesystemStoreConfig = {
63
90
  readonly root_dir: string;
64
91
  };
92
+ /**
93
+ * What `filesystem_store` returns: a `CheckpointStore` with every optional
94
+ * capability, which is what `durable` needs from its store.
95
+ */
96
+ type FilesystemStore = {
97
+ readonly get: (key: string) => Promise<unknown>;
98
+ readonly set: (key: string, value: unknown) => Promise<void>;
99
+ readonly delete: (key: string) => Promise<void>;
100
+ readonly scope: (prefix: string) => FilesystemScopedStore;
101
+ readonly claim: (key: string, owner: string, ttl_ms: number) => Promise<boolean>;
102
+ readonly release: (key: string, owner: string) => Promise<void>;
103
+ };
104
+ /**
105
+ * A scope of a `filesystem_store`, which can also `clear`.
106
+ */
107
+ type FilesystemScopedStore = FilesystemStore & {
108
+ readonly clear: () => Promise<void>;
109
+ };
65
110
  /**
66
111
  * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.
67
112
  */
68
- declare function filesystem_store(config: FilesystemStoreConfig): CheckpointStore;
113
+ export declare function filesystem_store(config: FilesystemStoreConfig): FilesystemStore;
69
114
  //#endregion
70
- export { type FilesystemLoggerConfig, type FilesystemStoreConfig, type HttpLoggerConfig, type HttpLoggerFetch, type StderrLoggerOptions, filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
115
+ export type { FilesystemLoggerConfig, FilesystemScopedStore, FilesystemStore, FilesystemStoreConfig, HttpLoggerConfig, HttpLoggerFetch, StderrLoggerOptions };
71
116
  //# sourceMappingURL=adapters.d.ts.map
package/dist/adapters.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-CutexJd3.js";
1
+ import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-DNnzeLxr.js";
2
2
  export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };