fascicle 0.18.1 → 0.19.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 (51) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +27 -1
  3. package/dist/AGENTS.md +11 -10
  4. package/dist/a2a.d.ts +358 -0
  5. package/dist/a2a.js +2234 -0
  6. package/dist/a2a.js.map +1 -0
  7. package/dist/acp.d.ts +120 -9
  8. package/dist/acp.js +927 -154
  9. package/dist/acp.js.map +1 -1
  10. package/dist/adapters-DYFauXE1.js +1147 -0
  11. package/dist/adapters-DYFauXE1.js.map +1 -0
  12. package/dist/adapters.d.ts +124 -36
  13. package/dist/adapters.js +1 -1
  14. package/dist/agents.d.ts +2 -2
  15. package/dist/agents.js +1 -1
  16. package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
  17. package/dist/core-xTtRZqdb.js.map +1 -0
  18. package/dist/diagram_bin.js +1 -1
  19. package/dist/durable-CgU0kO2H.d.ts +144 -0
  20. package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
  21. package/dist/engine-B_Yl7acj.js.map +1 -0
  22. package/dist/index.d.ts +9 -136
  23. package/dist/index.js +6 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
  26. package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
  27. package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
  28. package/dist/leading_system-m-x7HzbQ.js.map +1 -0
  29. package/dist/mcp-D1hN5ywq.js +662 -0
  30. package/dist/mcp-D1hN5ywq.js.map +1 -0
  31. package/dist/mcp.d.ts +115 -5
  32. package/dist/mcp.js +2 -2
  33. package/dist/otel.d.ts +1 -1
  34. package/dist/stdio.d.ts +1 -1
  35. package/dist/stdio.js +2 -2
  36. package/dist/testing.d.ts +7 -5
  37. package/dist/testing.js +618 -318
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
  40. package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
  41. package/dist/ui.d.ts +2 -2
  42. package/dist/viewer.js +2 -2
  43. package/dist/web.d.ts +1 -1
  44. package/package.json +18 -6
  45. package/dist/adapters-CpKpDk7r.js +0 -461
  46. package/dist/adapters-CpKpDk7r.js.map +0 -1
  47. package/dist/core-BH7sWpEG.js.map +0 -1
  48. package/dist/engine-fOjYHcv6.js.map +0 -1
  49. package/dist/leading_system-BeQUSAim.js.map +0 -1
  50. package/dist/mcp-CHJ88HiG.js +0 -262
  51. package/dist/mcp-CHJ88HiG.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters-DYFauXE1.js","names":["to_json","read_claim","store_at","open","to_json","store_at"],"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","../src/adapters/memory_store.ts","../src/adapters/sqlite_store.ts","../src/adapters/object_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 * Failure policy: an event that can't be serialized or appended is dropped\n * and reported, through the optional `on_error` callback or else as one line\n * on stderr. Never throws into the flow, the same as every adapter logger.\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 * Called with the error when an event can't be serialized or appended.\n * Omitted, each failure writes one `filesystem_logger:` line to stderr.\n * Either way the event is dropped and the flow carries on.\n */\n readonly on_error?: (err: unknown) => void\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 const report = config.on_error ?? ((err: unknown) => report_to_stderr(output_path, err))\n mkdirSync(dirname(output_path), { recursive: true })\n\n return line_logger((event) => {\n try {\n appendFileSync(output_path, `${JSON.stringify(event)}\\n`)\n } catch (err: unknown) {\n try {\n report(err)\n } catch {\n // A reporter that throws is dropped too: the flow always wins.\n }\n }\n })\n}\n\n/**\n * The default reporter: one stderr line that names the file and the reason\n * an event was dropped.\n */\nfunction report_to_stderr(output_path: string, err: unknown): void {\n const reason = err instanceof Error ? err.message : String(err)\n process.stderr.write(\n `filesystem_logger: dropped an event it could not write to ${output_path} (${reason}). Check that the path is a writable file and that every emitted value is JSON-serializable.\\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, an event JSON can't serialize, and a\n * custom `fetch` that throws are each 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 // The executor serializes the event as it is now, and a throw there or\n // in `send` rejects into the catch below rather than into the flow.\n void new Promise<string>((resolve) => {\n resolve(`${JSON.stringify(event)}\\n`)\n })\n .then(async (body) =>\n send(url, {\n method: 'POST',\n headers: { 'content-type': 'application/x-ndjson' },\n body,\n }),\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. A caller passes it where a logger is required and nothing should be\n * recorded, such as a test that does not care about trajectory output.\n * `run(...)` keeps its own private no-op for a run given no logger.\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 id from the first sink whose `start_span` returns is canonical and goes\n * back to the caller, or `<name>:tee` when every sink throws. The tee\n * remembers each sink's own id by its position, so that\n * `end_span(canonical_id, ...)` translates back to the right id for each sink,\n * and a sink that threw on `start_span` gets the canonical id. Within any one\n * sink the wire format stays internally consistent; only the across-sink ids\n * 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(\n 'tee_logger needs at least one logger: pass the sinks to fan out to, as in `tee_logger(stderr_logger(), http_logger(config))`',\n )\n }\n\n const id_map = new Map<string, ReadonlyArray<string | undefined>>()\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: Array<string | undefined> = loggers.map(() => undefined)\n safe_each((l, idx) => {\n ids[idx] = l.start_span(name, meta)\n })\n const canonical = ids.find((sink_id) => sink_id !== undefined) ?? `${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 *\n * A value's version, for `get_versioned` and `set_if`, is a hash of its\n * file's bytes, so the files stay where they always were. Every write to a\n * key holds a lock on it while it works, `set` and `delete` included, which\n * is what makes `set_if` atomic against all of them. The lock is an empty\n * directory beside the value (`<key>.lock/`), made with one `mkdir`, which\n * refuses a directory that exists, and removed with one `rmdir` when the\n * write is done, so nothing stays behind. Under the lock, `set_if` writes its\n * temporary file, reads the bytes at the key, and renames the file into place\n * only when their hash is the version it was given. A create\n * (`expected: null`) needs no lock, because it's the same `link` a claim\n * uses.\n *\n * The lock costs a write two calls more than it would make without one: a\n * `set` is four filesystem calls, a `delete` three, and a `set_if` on a\n * version six. Writers to one key go one at a time. Those in one process\n * queue in memory, and those in other processes ask for the lock again every\n * couple of milliseconds, so a key that many writers want at once is as slow\n * as the queue is long.\n *\n * A writer that dies between its `mkdir` and its `rmdir` leaves the lock\n * behind. A lock older than ten seconds counts as abandoned, and the writer\n * that finds one removes it while holding a claim on the directory's\n * `lock.recovery/`, so two writers can't both clear the way and a lock taken\n * since is never the one removed. That directory appears the first time a\n * lock is recovered and stays. A writer that stalls for longer than ten\n * seconds inside a write is taken for dead, and the write it finishes late\n * is no longer exclusive.\n *\n * All of this leans on `link`, `rename`, and `mkdir` being atomic and on a\n * directory listing being current, which a local filesystem gives and a network\n * filesystem may not. So this is a store for the processes of one machine,\n * and a run that events reach on several hosts wants `object_store`.\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, rmdir, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport type { CheckpointStore } from '#core'\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 = Required<Omit<CheckpointStore, 'scope'>> & {\n readonly scope: (prefix: string) => FilesystemScopedStore\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// How old a write's lock gets before it counts as abandoned, which only\n// happens when the process that took it died.\nconst LOCK_MS = 10_000\n\n// How long a writer waits before it asks for a held lock again.\nconst LOCK_RETRY_MS = 2\n\n// The claim directory a writer holds while it removes an abandoned lock, one\n// to each directory of values. No key's files can take the name, since each\n// of those carries the key's hash.\nconst RECOVERY = 'lock.recovery'\n\n// The last write this process queued on each lock path, there while a write\n// on that path is under way.\nconst turns = new Map<string, Promise<void>>()\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 return parse_json(raw)\n}\n\n/**\n * Parse stored text, or `null` when it isn't whole JSON.\n */\nfunction parse_json(raw: string): unknown {\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n}\n\n/**\n * The bytes at `path`, or `undefined` when no file is there. Any other\n * failure surfaces.\n */\nasync function read_bytes(path: string): Promise<Buffer | undefined> {\n try {\n return await readFile(path)\n } catch (err) {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n }\n}\n\n/**\n * The version of a value whose file holds `bytes`: a hash of them, so it\n * moves whenever the stored text does.\n */\nfunction version_of(bytes: Buffer): string {\n return createHash('sha256').update(bytes).digest('hex')\n}\n\n/**\n * Replace the value at `path` with `value` while the file there still\n * hashes to `expected`, resolving whether it did.\n *\n * The temporary file is written before the bytes are read. A scope that's\n * cleared and made again in between takes the temporary file with it, and\n * the rename then fails, where a file written after the read would land in\n * the new scope over a value this call never saw. A missing directory or a\n * missing file is a conflict like any other, since the key is absent.\n */\nasync function replace_if(path: string, value: unknown, expected: string): 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 try {\n await writeFile(tmp, to_json(value))\n const bytes = await read_bytes(path)\n if (bytes === undefined || version_of(bytes) !== expected) return false\n await rename(tmp, path)\n return true\n } catch (err) {\n if (error_code(err) === 'ENOENT') return false\n throw err\n } finally {\n await rm(tmp, { force: true })\n }\n}\n\n/**\n * Wait `ms` milliseconds.\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * True when the lock at `path` is older than `LOCK_MS`. A lock that's gone\n * isn't abandoned, it was let go.\n */\nasync function is_abandoned(path: string): Promise<boolean> {\n try {\n return Date.now() - (await stat(path)).mtimeMs > LOCK_MS\n } catch (err) {\n if (error_code(err) === 'ENOENT') return false\n throw err\n }\n}\n\n/**\n * Remove the abandoned lock at `path`, or wait a moment when another writer\n * is already removing one.\n *\n * Two writers that both found the lock abandoned can't both be let remove\n * it: the second would remove the lock a third writer took after the first\n * cleared the way. So the removal happens under a claim, and the lock's age\n * is read again once the claim is held. The claim lapses by itself when its\n * holder dies, which a second lock directory wouldn't.\n */\nasync function recover(path: string): Promise<void> {\n const dir = join(dirname(path), RECOVERY)\n const owner = randomUUID()\n if (!(await claim_in(dir, owner, LOCK_MS))) return sleep(LOCK_RETRY_MS)\n try {\n if (await is_abandoned(path)) await rm(path, { recursive: true, force: true })\n } finally {\n await release_in(dir, owner)\n }\n}\n\n/**\n * Take the lock at `path`, waiting for it while another writer has it.\n *\n * The lock is a directory, and `mkdir` refuses one that exists, so of the\n * writers that ask at once exactly one gets it. The first write to a store\n * finds no directory to make the lock in, and makes that first.\n */\nasync function take_lock(path: string): Promise<void> {\n for (;;) {\n try {\n await mkdir(path)\n return\n } catch (err) {\n const code = error_code(err)\n if (code === 'ENOENT') {\n await mkdir(dirname(path), { recursive: true })\n continue\n }\n if (code !== 'EEXIST') throw err\n }\n if (await is_abandoned(path)) await recover(path)\n else await sleep(LOCK_RETRY_MS)\n }\n}\n\n/**\n * Let go of the lock at `path`. A lock that vanished meanwhile (its scope\n * was cleared) has nothing left to let go of.\n */\nasync function drop_lock(path: string): Promise<void> {\n try {\n await rmdir(path)\n } catch (err) {\n if (error_code(err) !== 'ENOENT') throw err\n }\n}\n\n/**\n * Run `body` once every write this process began on `path` before it has\n * finished.\n *\n * The lock directory is for the other processes. Inside one process the\n * writers to a key queue here, so each takes the lock on its first try and\n * none of them spends its wait asking the disk for it.\n */\nasync function in_turn<t>(path: string, body: () => Promise<t>): Promise<t> {\n const ahead = turns.get(path)\n const done = Promise.withResolvers<void>()\n turns.set(path, done.promise)\n await ahead\n try {\n return await body()\n } finally {\n if (turns.get(path) === done.promise) turns.delete(path)\n done.resolve()\n }\n}\n\n/**\n * Run `body` while holding the lock at `path`, waiting for it when another\n * writer has it.\n */\nfunction with_lock<t>(path: string, body: () => Promise<t>): Promise<t> {\n return in_turn(path, async () => {\n await take_lock(path)\n try {\n return await body()\n } finally {\n await drop_lock(path)\n }\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 lock_dir = (key: string): string => join(root_dir, `${safe_name(key)}.lock`)\n\n const get = (key: string): Promise<unknown> => read_json(value_path(key))\n\n // Taking the lock makes the root when it isn't there yet.\n const set = (key: string, value: unknown): Promise<void> =>\n with_lock(lock_dir(key), () => write_atomic(value_path(key), value))\n\n const delete_key = (key: string): Promise<void> =>\n with_lock(lock_dir(key), () => rm(value_path(key), { force: true }))\n\n const get_versioned: FilesystemStore['get_versioned'] = async (key) => {\n const bytes = await read_bytes(value_path(key))\n if (bytes === undefined) return undefined\n const parsed = parse_json(bytes.toString('utf8'))\n return { value: parsed === null ? undefined : parsed, version: version_of(bytes) }\n }\n\n const set_if: FilesystemStore['set_if'] = async (key, value, expected) => {\n if (expected === null) {\n await mkdir(root_dir, { recursive: true })\n return create_exclusive(value_path(key), value)\n }\n return with_lock(lock_dir(key), () => replace_if(value_path(key), value, expected))\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 get_versioned,\n set_if,\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","/**\n * In-memory checkpoint store.\n *\n * Satisfies `CheckpointStore` from `core`, every optional capability\n * included, so `durable` can keep its runs in one without touching disk. It\n * lasts as long as the value does, which suits a test, a demo, and a server\n * whose runs may end with the process.\n *\n * Every scope lives in one map keyed by the path of prefixes that reached\n * it, so reopening a scope finds its data and `clear` drops a whole subtree.\n * Values are cloned on the way in and on the way out, the way a store that\n * serializes hands back a copy, so a caller can't change what the store\n * holds by changing what it was given. A version is a count of the store's\n * writes, so no two writes share one, in any scope, unless\n * `content_versions` asks for the value's JSON instead.\n */\n\nimport type { CheckpointStore, Versioned } from '#core'\n\ntype ClaimRecord = { owner: string; expires_at: number }\n\ntype Entry = { readonly value: unknown; readonly version: string }\n\ntype Space = {\n readonly path: ReadonlyArray<string>\n readonly values: Map<string, Entry>\n readonly claims: Map<string, ClaimRecord>\n}\n\nexport type MemoryStoreOptions = {\n /** The clock claims expire against, which a test that moves time replaces; default: `Date.now`. */\n readonly now?: (() => number) | undefined\n /**\n * Derive a value's version from its content, the way a store that hashes\n * the bytes or reads an ETag does, so two writes of one value share a\n * version; default: false.\n */\n readonly content_versions?: boolean | undefined\n}\n\n/**\n * A scope of a `memory_store`, which can also `clear`.\n */\nexport type MemoryScopedStore = Required<Omit<CheckpointStore, 'scope'>> & {\n readonly scope: (prefix: string) => MemoryScopedStore\n readonly clear: () => Promise<void>\n}\n\n/**\n * What `memory_store` returns: a `CheckpointStore` with every optional\n * capability, plus `dump`.\n */\nexport type MemoryStore = Omit<MemoryScopedStore, 'clear'> & {\n /**\n * Every value the store holds, by scope path and then by key, for a test\n * that asserts on what was kept. A scope's path is the JSON of the\n * prefixes that led to it, so the root is `'[]'`.\n */\n readonly dump: () => Record<string, Record<string, unknown>>\n}\n\n/**\n * Build an in-memory `CheckpointStore` with scopes, claims, and conditional\n * writes.\n */\nexport function memory_store(options: MemoryStoreOptions = {}): MemoryStore {\n const now = options.now ?? (() => Date.now())\n const spaces = new Map<string, Space>()\n let writes = 0\n\n const space_at = (path: ReadonlyArray<string>): Space => {\n const id = JSON.stringify(path)\n const existing = spaces.get(id)\n if (existing !== undefined) return existing\n const created: Space = { path, values: new Map(), claims: new Map() }\n spaces.set(id, created)\n return created\n }\n\n const clear_under = (path: ReadonlyArray<string>): void => {\n for (const [id, space] of spaces) {\n if (path.every((part, i) => space.path[i] === part)) spaces.delete(id)\n }\n }\n\n const write = (path: ReadonlyArray<string>, key: string, value: unknown): void => {\n writes += 1\n const version = options.content_versions === true ? JSON.stringify(value) : `w${writes}`\n space_at(path).values.set(key, { value: structuredClone(value), version })\n }\n\n const store_at = (path: ReadonlyArray<string>): Omit<MemoryScopedStore, 'clear'> => ({\n get: async (key) => {\n const value = space_at(path).values.get(key)?.value\n return value === undefined ? null : structuredClone(value)\n },\n set: async (key, value) => {\n write(path, key, value)\n },\n delete: async (key) => {\n space_at(path).values.delete(key)\n },\n scope: (prefix) => {\n const inner = [...path, prefix]\n return { ...store_at(inner), clear: async () => clear_under(inner) }\n },\n claim: async (key, owner, ttl_ms) => {\n const claims = space_at(path).claims\n const current = claims.get(key)\n const at = now()\n if (current !== undefined && current.expires_at > at && current.owner !== owner) return false\n claims.set(key, { owner, expires_at: at + ttl_ms })\n return true\n },\n release: async (key, owner) => {\n const claims = space_at(path).claims\n if (claims.get(key)?.owner === owner) claims.delete(key)\n },\n get_versioned: async (key): Promise<Versioned | undefined> => {\n const entry = space_at(path).values.get(key)\n if (entry === undefined) return undefined\n const value = entry.value === null ? undefined : structuredClone(entry.value)\n return { value, version: entry.version }\n },\n set_if: async (key, value, expected) => {\n const version = space_at(path).values.get(key)?.version ?? null\n if (version !== expected) return false\n write(path, key, value)\n return true\n },\n })\n\n const dump = (): Record<string, Record<string, unknown>> => {\n const out: Record<string, Record<string, unknown>> = {}\n for (const [id, space] of spaces) {\n if (space.values.size === 0) continue\n out[id] = Object.fromEntries([...space.values].map(([key, entry]) => [key, entry.value]))\n }\n return out\n }\n\n return { ...store_at([]), dump }\n}\n","/**\n * SQLite-backed checkpoint store.\n *\n * Satisfies `CheckpointStore` from `core`, every optional capability\n * included, on `node:sqlite`, which is built into Node and needs no native\n * module. One file holds every run, and several processes on one machine can\n * share it, since SQLite runs each statement atomically across connections.\n *\n * `node:sqlite` is loaded when `sqlite_store` is called and not before, so\n * importing `fascicle/adapters` never loads it, and never prints the warning\n * that an older Node 24 prints for an experimental module.\n *\n * Values and claims sit in a table each, keyed by scope and key. A scope is\n * a path of percent-encoded segments, each followed by `/`, so `clear`\n * deletes the range of paths that start with the scope's own and can't reach\n * a sibling whose name only looks alike. A value's version is drawn fresh on\n * every write, which is what `set_if` compares.\n *\n * A claim is one statement: an insert that updates on conflict only when the\n * current claim is the same owner's or has expired. The claimer has won when\n * the statement changed a row.\n *\n * The database opens in WAL mode with a busy timeout, so a second process\n * waits for a lock instead of failing at once.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { DatabaseSync, StatementSync } from 'node:sqlite'\nimport type { CheckpointStore, Versioned } from '#core'\n\nexport type SqliteStoreConfig = {\n /** The database file, or `':memory:'` for one that lasts as long as the store. */\n readonly path: string\n /** How long a write waits on another connection's lock, in milliseconds; default: 5_000. */\n readonly timeout_ms?: number | undefined\n}\n\n/**\n * A scope of a `sqlite_store`, which can also `clear`.\n */\nexport type SqliteScopedStore = Required<Omit<CheckpointStore, 'scope'>> & {\n readonly scope: (prefix: string) => SqliteScopedStore\n readonly clear: () => Promise<void>\n}\n\n/**\n * What `sqlite_store` returns: a `CheckpointStore` with every optional\n * capability, which is what `durable` needs from its store, plus `close`.\n */\nexport type SqliteStore = Omit<SqliteScopedStore, 'clear'> & {\n /** Closes the database. The store can't be used afterwards. */\n readonly close: () => void\n}\n\ntype Statements = {\n readonly get: StatementSync\n readonly put: StatementSync\n readonly remove: StatementSync\n readonly create: StatementSync\n readonly replace: StatementSync\n readonly claim: StatementSync\n readonly release: StatementSync\n readonly clear_values: StatementSync\n readonly clear_claims: StatementSync\n}\n\nconst DEFAULT_TIMEOUT_MS = 5_000\n\nconst SCHEMA = `\n CREATE TABLE IF NOT EXISTS fascicle_values (\n scope TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n version TEXT NOT NULL,\n PRIMARY KEY (scope, key)\n ) WITHOUT ROWID;\n CREATE TABLE IF NOT EXISTS fascicle_claims (\n scope TEXT NOT NULL,\n key TEXT NOT NULL,\n owner TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n PRIMARY KEY (scope, key)\n ) WITHOUT ROWID;\n`\n\n/**\n * Open the database at `path` in WAL mode, with `timeout_ms` as its busy\n * timeout.\n */\nfunction open(path: string, timeout_ms: number): DatabaseSync {\n const sqlite = process.getBuiltinModule('node:sqlite')\n const db = new sqlite.DatabaseSync(path)\n db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.trunc(timeout_ms))}`)\n db.exec('PRAGMA journal_mode = WAL')\n db.exec(SCHEMA)\n return db\n}\n\n/**\n * Prepare every statement the store runs.\n */\nfunction prepare(db: DatabaseSync): Statements {\n return {\n get: db.prepare('SELECT value, version FROM fascicle_values WHERE scope = ? AND key = ?'),\n put: db.prepare(\n `INSERT INTO fascicle_values (scope, key, value, version) VALUES (?, ?, ?, ?)\n ON CONFLICT (scope, key) DO UPDATE SET value = excluded.value, version = excluded.version`,\n ),\n remove: db.prepare('DELETE FROM fascicle_values WHERE scope = ? AND key = ?'),\n create: db.prepare(\n `INSERT INTO fascicle_values (scope, key, value, version) VALUES (?, ?, ?, ?)\n ON CONFLICT (scope, key) DO NOTHING`,\n ),\n replace: db.prepare(\n 'UPDATE fascicle_values SET value = ?, version = ? WHERE scope = ? AND key = ? AND version = ?',\n ),\n claim: db.prepare(\n `INSERT INTO fascicle_claims (scope, key, owner, expires_at) VALUES (?, ?, ?, ?)\n ON CONFLICT (scope, key) DO UPDATE SET owner = excluded.owner, expires_at = excluded.expires_at\n WHERE fascicle_claims.owner = excluded.owner OR fascicle_claims.expires_at <= ?`,\n ),\n release: db.prepare('DELETE FROM fascicle_claims WHERE scope = ? AND key = ? AND owner = ?'),\n clear_values: db.prepare('DELETE FROM fascicle_values WHERE scope >= ? AND scope < ?'),\n clear_claims: db.prepare('DELETE FROM fascicle_claims WHERE scope >= ? AND scope < ?'),\n }\n}\n\n/**\n * Serialize a value for a row. 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 * Parse a row's text, or `undefined` when it isn't JSON or holds `null`.\n */\nfunction from_json(text: unknown): unknown {\n if (typeof text !== 'string') return undefined\n try {\n const value: unknown = JSON.parse(text)\n return value === null ? undefined : value\n } catch {\n return undefined\n }\n}\n\n/**\n * The path of the scope that `prefix` names under `parent`. Each segment is\n * percent-encoded, which leaves no `/` inside it, and ends in one.\n */\nfunction child_path(parent: string, prefix: string): string {\n return `${parent}${encodeURIComponent(prefix)}/`\n}\n\n/**\n * The first path that sorts after every path starting with `path`. A scope's\n * path ends in `/`, and `0` is the character after it.\n */\nfunction path_end(path: string): string {\n return `${path.slice(0, -1)}0`\n}\n\n/**\n * The store over the rows of one scope path.\n */\nfunction store_at(db: DatabaseSync, sql: Statements, path: string): Omit<SqliteScopedStore, 'clear'> {\n return {\n get: async (key) => from_json(sql.get.get(path, key)?.['value']) ?? null,\n set: async (key, value) => {\n sql.put.run(path, key, to_json(value), randomUUID())\n },\n delete: async (key) => {\n sql.remove.run(path, key)\n },\n scope: (prefix) => {\n const inner = child_path(path, prefix)\n return {\n ...store_at(db, sql, inner),\n clear: async () => {\n db.exec('BEGIN IMMEDIATE')\n try {\n sql.clear_values.run(inner, path_end(inner))\n sql.clear_claims.run(inner, path_end(inner))\n db.exec('COMMIT')\n } catch (err) {\n db.exec('ROLLBACK')\n throw err\n }\n },\n }\n },\n claim: async (key, owner, ttl_ms) => {\n const at = Date.now()\n return sql.claim.run(path, key, owner, at + ttl_ms, at).changes === 1\n },\n release: async (key, owner) => {\n sql.release.run(path, key, owner)\n },\n get_versioned: async (key): Promise<Versioned | undefined> => {\n const row = sql.get.get(path, key)\n if (row === undefined) return undefined\n return { value: from_json(row['value']), version: String(row['version']) }\n },\n set_if: async (key, value, expected) => {\n const text = to_json(value)\n const version = randomUUID()\n const result =\n expected === null\n ? sql.create.run(path, key, text, version)\n : sql.replace.run(text, version, path, key, expected)\n return result.changes === 1\n },\n }\n}\n\n/**\n * Build a `CheckpointStore` over a SQLite database, with scopes, claims, and\n * conditional writes.\n *\n * The file is created when it doesn't exist, and so are the store's two\n * tables, which leaves room for other tables beside them. `close` closes the\n * database.\n */\nexport function sqlite_store(config: SqliteStoreConfig): SqliteStore {\n const db = open(config.path, config.timeout_ms ?? DEFAULT_TIMEOUT_MS)\n return {\n ...store_at(db, prepare(db), ''),\n close: () => {\n db.close()\n },\n }\n}\n","/**\n * Object-store-backed checkpoint store.\n *\n * Satisfies `CheckpointStore` from `core`, every optional capability\n * included, over a small client interface, so a durable run can live in a\n * bucket that every host in a fleet reaches. The store needs four things of\n * the service: get, put, delete, and a paginated list by prefix, plus the two\n * conditional puts that S3 and the services shaped like it have.\n * `If-None-Match: *` creates a key only while it's absent, and `If-Match`\n * replaces one only while its ETag still matches. Fascicle ships no client\n * and depends on no cloud SDK. `ObjectClient` is the seam, and\n * `docs/human-in-the-loop.md` shows one for `@aws-sdk/client-s3`.\n *\n * A scope is a key prefix, which makes `clear` a paginated list and a delete\n * per key, with the scope's own claims deleted last, so whoever holds a claim\n * on the scope (the lease that `durable` deletes a run under) holds it until\n * everything else is gone. Every name is percent-encoded before it joins a key, dots\n * included, and values, claims, and nested scopes each take a segment of\n * their own (`v/`, `c/`, `s/`), so two names can't land on one object however\n * alike they look. A name whose encoding runs past `MAX_SEGMENT` characters\n * is cut and given a hash of the whole name, which keeps a key under S3's\n * 1,024-byte limit through several scopes.\n *\n * A value's version is its ETag. A claim is an object holding its owner and\n * expiry, and every change to it is a conditional put on the ETag the\n * claimer read, so when claimers race, the bucket accepts exactly one of\n * them. The store never asks for a conditional delete, which not every\n * service has, so a release overwrites the claim as expired.\n *\n * A failed condition is read again before it counts. A client that retries\n * a put whose answer got lost sees its own earlier write as the conflict, so\n * when the object's body is the one this call tried to write, the write\n * landed. That reading is safe as long as no two writers send the same body,\n * which holds for a claim (it carries its owner and expiry) and for a\n * durable run's record (it carries its revision).\n *\n * The store needs a read, and a list, to see the last write. A bucket whose\n * reads lag its writes (some multi-region setups) can't hold a run.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { CheckpointStore } from '#core'\n\n/** The slice of an S3-style client that the store needs. */\nexport type ObjectClient = {\n /** The object and its ETag, or `undefined` when there's none. */\n readonly get: (\n key: string,\n ) => Promise<{ readonly body: string; readonly etag: string } | undefined>\n /**\n * Write the object, only while it's absent (`if_none_match: '*'`) or only\n * while its ETag still matches (`if_match`) when a condition is given.\n * Resolves false when the condition failed, and throws on anything else.\n */\n readonly put: (key: string, body: string, condition?: ObjectPutCondition) => Promise<boolean>\n readonly delete: (key: string) => Promise<void>\n /** One page of the keys under `prefix`, after `start_after` when given. */\n readonly list: (\n prefix: string,\n start_after?: string,\n ) => Promise<{ readonly keys: ReadonlyArray<string>; readonly next?: string }>\n}\n\n/**\n * The condition on a put: create the key only while it's absent, or replace\n * it only while its ETag still matches.\n */\nexport type ObjectPutCondition = { readonly if_none_match: '*' } | { readonly if_match: string }\n\nexport type ObjectStoreConfig = {\n readonly client: ObjectClient\n /** The key prefix that every object goes under, such as `'runs/'`. */\n readonly prefix?: string\n}\n\n/**\n * What `object_store` returns: a `CheckpointStore` with every optional\n * capability, which is what `durable` needs from its store.\n */\nexport type ObjectStore = Required<Omit<CheckpointStore, 'scope'>> & {\n readonly scope: (prefix: string) => ObjectScopedStore\n}\n\n/**\n * A scope of an `object_store`, which can also `clear`.\n */\nexport type ObjectScopedStore = ObjectStore & {\n readonly clear: () => Promise<void>\n}\n\ntype ClaimRecord = {\n readonly owner: string\n readonly expires_at: number\n}\n\n// Values, claims, and nested scopes each take their own segment under a\n// scope's prefix.\nconst VALUE = 'v/'\nconst CLAIM = 'c/'\nconst SCOPE = 's/'\n\n// The longest a name's encoding runs before it's cut and hashed.\nconst MAX_SEGMENT = 128\n\n// How much of a long name's encoding stays readable in front of its hash.\nconst KEPT = 64\n\n/**\n * Encode a key or a scope prefix as one segment of an object key.\n *\n * Percent encoding leaves no `/` inside a name, so a value's key can never\n * pass for a nested scope's prefix, and dots are encoded too, because some\n * HTTP layers rewrite `.` and `..` segments in a path. A long name keeps the\n * start of its encoding and takes a hash of the whole name after a dot.\n * Nothing else puts a dot in a segment, so a hashed name can't land on a\n * short one.\n */\nfunction segment(name: string): string {\n const encoded = encodeURIComponent(name).replaceAll('.', '%2E')\n if (encoded.length <= MAX_SEGMENT) return encoded\n const hash = createHash('sha256').update(name).digest('hex')\n return `${encoded.slice(0, KEPT).replaceAll('%', '_')}.${hash}`\n}\n\n/**\n * Parse a stored body, reading anything that isn't whole JSON as a miss.\n */\nfunction parse(body: string): unknown {\n try {\n return JSON.parse(body) as unknown\n } catch {\n return null\n }\n}\n\n/**\n * Serialize a value as JSON. A value that JSON has no text for (`undefined`,\n * a 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 * Read a claim object back, or `null` when its body isn't a claim.\n */\nfunction read_claim(body: string): ClaimRecord | null {\n const parsed = parse(body)\n if (typeof parsed !== 'object' || parsed === null) return null\n const owner: unknown = Reflect.get(parsed, 'owner')\n const expires_at: unknown = Reflect.get(parsed, 'expires_at')\n return typeof owner === 'string' && typeof expires_at === 'number' ? { owner, expires_at } : null\n}\n\n/**\n * Put `body` under `key` if `condition` holds, resolving whether the object\n * now holds this call's write.\n *\n * A failed condition usually means another writer got there first. It can\n * also be this call's own write, landed by an attempt whose answer was lost\n * and refused on the retry, so the object is read again, and a body\n * identical to `body` counts as the write landing.\n */\nasync function put_if(\n client: ObjectClient,\n key: string,\n body: string,\n condition: ObjectPutCondition,\n): Promise<boolean> {\n if (await client.put(key, body, condition)) return true\n const current = await client.get(key)\n return current?.body === body\n}\n\n/**\n * Take or renew the claim at `key` for `owner`.\n *\n * A key nobody has claimed is created with `If-None-Match: *`. Anything else\n * that isn't a live claim held by another owner is replaced with `If-Match`\n * on the ETag just read, which covers both a renewal and the takeover of an\n * expired claim. Either way, a claimer that read a state someone else has\n * since changed loses the put.\n */\nasync function claim_at(\n client: ObjectClient,\n key: string,\n owner: string,\n ttl_ms: number,\n): Promise<boolean> {\n const current = await client.get(key)\n const now = Date.now()\n const held = current === undefined ? null : read_claim(current.body)\n if (held !== null && held.expires_at > now && held.owner !== owner) return false\n const body = JSON.stringify({ owner, expires_at: now + ttl_ms })\n return put_if(client, key, body, current === undefined ? { if_none_match: '*' } : { if_match: current.etag })\n}\n\n/**\n * Release the claim at `key` when `owner` holds it.\n *\n * The claim is overwritten as expired, on the ETag just read, and never\n * deleted. A plain delete could erase a claim that another owner took after\n * the read, and a conditional delete isn't something every service has. A\n * put that loses means the claim changed hands, which leaves nothing to\n * release.\n */\nasync function release_at(client: ObjectClient, key: string, owner: string): Promise<void> {\n const current = await client.get(key)\n if (current === undefined || read_claim(current.body)?.owner !== owner) return\n await client.put(key, JSON.stringify({ owner, expires_at: 0 }), { if_match: current.etag })\n}\n\n/**\n * Delete every object whose key starts with `prefix`, a page at a time, and\n * the claims directly under it after everything else.\n *\n * A listing is sorted, and `c/` sorts ahead of `s/` and `v/`, so deleting in\n * listing order would free a claim on the scope while later pages still held\n * its values. A caller that clears under a claim, as `durable` deletes a run\n * under its lease, keeps that claim until the rest of the scope is gone.\n */\nasync function delete_prefix(client: ObjectClient, prefix: string): Promise<void> {\n const claims = `${prefix}${CLAIM}`\n const held: string[] = []\n let start_after: string | undefined\n for (;;) {\n const page = await client.list(prefix, start_after)\n held.push(...page.keys.filter((key) => key.startsWith(claims)))\n await Promise.all(page.keys.filter((key) => !key.startsWith(claims)).map((key) => client.delete(key)))\n if (page.next === undefined) break\n start_after = page.next\n }\n await Promise.all(held.map((key) => client.delete(key)))\n}\n\n/**\n * Build the store whose keys live under `base`.\n */\nfunction store_at(client: ObjectClient, base: string): ObjectStore {\n const value_key = (key: string): string => `${base}${VALUE}${segment(key)}`\n const claim_key = (key: string): string => `${base}${CLAIM}${segment(key)}`\n\n const scope = (prefix: string): ObjectScopedStore => {\n const dir = `${base}${SCOPE}${segment(prefix)}/`\n return { ...store_at(client, dir), clear: () => delete_prefix(client, dir) }\n }\n\n return {\n get: async (key) => {\n const object = await client.get(value_key(key))\n return object === undefined ? null : parse(object.body)\n },\n set: async (key, value) => {\n await client.put(value_key(key), to_json(value))\n },\n delete: (key) => client.delete(value_key(key)),\n scope,\n claim: (key, owner, ttl_ms) => claim_at(client, claim_key(key), owner, ttl_ms),\n release: (key, owner) => release_at(client, claim_key(key), owner),\n get_versioned: async (key) => {\n const object = await client.get(value_key(key))\n if (object === undefined) return undefined\n const parsed = parse(object.body)\n return { value: parsed === null ? undefined : parsed, version: object.etag }\n },\n set_if: (key, value, expected) =>\n put_if(\n client,\n value_key(key),\n to_json(value),\n expected === null ? { if_none_match: '*' } : { if_match: expected },\n ),\n }\n}\n\n/**\n * Create a `CheckpointStore` that keeps its values, claims, and scopes as\n * objects behind `config.client`, under `config.prefix`.\n *\n * Run `checkpoint_store_conformance` from `fascicle/testing` against a real\n * bucket once before trusting a service with it. A service that accepts a\n * condition and ignores it lets two writers both win, and that suite is what\n * catches it.\n */\nexport function object_store(config: ObjectStoreConfig): ObjectStore {\n return store_at(config.client, config.prefix ?? '')\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,oBAAoB,MAAM,MAAM,SAAS;EAEjD,KAAK,KAAK;EACV,MAAM,KAAK,OAAO;EAClB,OAAO;CACT;CAEA,MAAM,YAA0C,IAAI,SAAS;EAC3D,KAAK;GAAE,MAAM;GAAY,SAAS;GAAI,GA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A,UAAU,GAAG,GACb,QAAQ,KAAK,GACb,aAAa,OAAO,EAAE,eAAe,IAAI,IAAI,EAAE,UAAU,SAAS,CACpE;CACJ;AACF;;;;;;;;;;AAWA,SAAgB,aAAa,QAAwC;CACnE,OAAO,SAAS,OAAO,QAAQ,OAAO,UAAU,EAAE;AACpD"}
@@ -1,4 +1,4 @@
1
- import { h as TrajectoryLogger } from "./types-BUXt_zgJ.js";
1
+ import { h as TrajectoryLogger, n as CheckpointStore } from "./types-BtRpSctv.js";
2
2
  type FilesystemLoggerConfig = {
3
3
  readonly output_path: string;
4
4
  /**
@@ -54,34 +54,6 @@ export declare function stderr_logger(options?: StderrLoggerOptions): Trajectory
54
54
  * Create a `TrajectoryLogger` that fans every call out to `loggers`.
55
55
  */
56
56
  export declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
57
- /**
58
- * Filesystem-backed checkpoint store.
59
- *
60
- * Satisfies `CheckpointStore` from `core`, every optional capability
61
- * included. Each key is stored as
62
- * a JSON file under the configured root directory. Writes are all-or-nothing:
63
- * values are written to a temporary sibling file and then atomically renamed
64
- * into place, so an interrupted write never leaves a partially written file
65
- * at the target key. On `get`, a missing file, a partial temp file that was
66
- * never atomically renamed, or a JSON parse failure each read as a cache
67
- * miss (returning `null`) rather than an error. Any other failure to read
68
- * (a permission error, a failing disk) surfaces, because reading it as a miss
69
- * could start a durable run over, or hand a live claim to a second owner.
70
- *
71
- * A scope is a directory beside the values (`<prefix>.scope/`), which makes
72
- * `clear` one recursive delete. A claim is a directory of numbered
73
- * generations (`<key>.claim/<n>.json`), and the newest one is the claim. A
74
- * claimer takes a free or expired key by creating the next generation with
75
- * `link`, which makes the file appear whole and refuses a target that
76
- * already exists, so two claimers can't both create it. Taking an expired
77
- * claim never overwrites a live one, which a rename into place couldn't
78
- * promise, and a claimer that finds a newer generation than its own has lost.
79
- * All of this leans on `link` and `rename` being atomic and on a directory
80
- * listing being current, which a local filesystem gives and a network
81
- * filesystem may not.
82
- *
83
- * Paths are accepted at construction; the store never reads `process.env`.
84
- */
85
57
  type FilesystemStoreConfig = {
86
58
  readonly root_dir: string;
87
59
  };
@@ -89,13 +61,8 @@ type FilesystemStoreConfig = {
89
61
  * What `filesystem_store` returns: a `CheckpointStore` with every optional
90
62
  * capability, which is what `durable` needs from its store.
91
63
  */
92
- type FilesystemStore = {
93
- readonly get: (key: string) => Promise<unknown>;
94
- readonly set: (key: string, value: unknown) => Promise<void>;
95
- readonly delete: (key: string) => Promise<void>;
64
+ type FilesystemStore = Required<Omit<CheckpointStore, 'scope'>> & {
96
65
  readonly scope: (prefix: string) => FilesystemScopedStore;
97
- readonly claim: (key: string, owner: string, ttl_ms: number) => Promise<boolean>;
98
- readonly release: (key: string, owner: string) => Promise<void>;
99
66
  };
100
67
  /**
101
68
  * A scope of a `filesystem_store`, which can also `clear`.
@@ -107,5 +74,126 @@ type FilesystemScopedStore = FilesystemStore & {
107
74
  * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.
108
75
  */
109
76
  export declare function filesystem_store(config: FilesystemStoreConfig): FilesystemStore;
110
- export type { FilesystemLoggerConfig, FilesystemScopedStore, FilesystemStore, FilesystemStoreConfig, HttpLoggerConfig, HttpLoggerFetch, StderrLoggerOptions };
77
+ type MemoryStoreOptions = {
78
+ /** The clock claims expire against, which a test that moves time replaces; default: `Date.now`. */
79
+ readonly now?: (() => number) | undefined;
80
+ /**
81
+ * Derive a value's version from its content, the way a store that hashes
82
+ * the bytes or reads an ETag does, so two writes of one value share a
83
+ * version; default: false.
84
+ */
85
+ readonly content_versions?: boolean | undefined;
86
+ };
87
+ /**
88
+ * A scope of a `memory_store`, which can also `clear`.
89
+ */
90
+ type MemoryScopedStore = Required<Omit<CheckpointStore, 'scope'>> & {
91
+ readonly scope: (prefix: string) => MemoryScopedStore;
92
+ readonly clear: () => Promise<void>;
93
+ };
94
+ /**
95
+ * What `memory_store` returns: a `CheckpointStore` with every optional
96
+ * capability, plus `dump`.
97
+ */
98
+ type MemoryStore = Omit<MemoryScopedStore, 'clear'> & {
99
+ /**
100
+ * Every value the store holds, by scope path and then by key, for a test
101
+ * that asserts on what was kept. A scope's path is the JSON of the
102
+ * prefixes that led to it, so the root is `'[]'`.
103
+ */
104
+ readonly dump: () => Record<string, Record<string, unknown>>;
105
+ };
106
+ /**
107
+ * Build an in-memory `CheckpointStore` with scopes, claims, and conditional
108
+ * writes.
109
+ */
110
+ export declare function memory_store(options?: MemoryStoreOptions): MemoryStore;
111
+ type SqliteStoreConfig = {
112
+ /** The database file, or `':memory:'` for one that lasts as long as the store. */
113
+ readonly path: string;
114
+ /** How long a write waits on another connection's lock, in milliseconds; default: 5_000. */
115
+ readonly timeout_ms?: number | undefined;
116
+ };
117
+ /**
118
+ * A scope of a `sqlite_store`, which can also `clear`.
119
+ */
120
+ type SqliteScopedStore = Required<Omit<CheckpointStore, 'scope'>> & {
121
+ readonly scope: (prefix: string) => SqliteScopedStore;
122
+ readonly clear: () => Promise<void>;
123
+ };
124
+ /**
125
+ * What `sqlite_store` returns: a `CheckpointStore` with every optional
126
+ * capability, which is what `durable` needs from its store, plus `close`.
127
+ */
128
+ type SqliteStore = Omit<SqliteScopedStore, 'clear'> & {
129
+ /** Closes the database. The store can't be used afterwards. */
130
+ readonly close: () => void;
131
+ };
132
+ /**
133
+ * Build a `CheckpointStore` over a SQLite database, with scopes, claims, and
134
+ * conditional writes.
135
+ *
136
+ * The file is created when it doesn't exist, and so are the store's two
137
+ * tables, which leaves room for other tables beside them. `close` closes the
138
+ * database.
139
+ */
140
+ export declare function sqlite_store(config: SqliteStoreConfig): SqliteStore;
141
+ /** The slice of an S3-style client that the store needs. */
142
+ type ObjectClient = {
143
+ /** The object and its ETag, or `undefined` when there's none. */
144
+ readonly get: (key: string) => Promise<{
145
+ readonly body: string;
146
+ readonly etag: string;
147
+ } | undefined>;
148
+ /**
149
+ * Write the object, only while it's absent (`if_none_match: '*'`) or only
150
+ * while its ETag still matches (`if_match`) when a condition is given.
151
+ * Resolves false when the condition failed, and throws on anything else.
152
+ */
153
+ readonly put: (key: string, body: string, condition?: ObjectPutCondition) => Promise<boolean>;
154
+ readonly delete: (key: string) => Promise<void>;
155
+ /** One page of the keys under `prefix`, after `start_after` when given. */
156
+ readonly list: (prefix: string, start_after?: string) => Promise<{
157
+ readonly keys: ReadonlyArray<string>;
158
+ readonly next?: string;
159
+ }>;
160
+ };
161
+ /**
162
+ * The condition on a put: create the key only while it's absent, or replace
163
+ * it only while its ETag still matches.
164
+ */
165
+ type ObjectPutCondition = {
166
+ readonly if_none_match: '*';
167
+ } | {
168
+ readonly if_match: string;
169
+ };
170
+ type ObjectStoreConfig = {
171
+ readonly client: ObjectClient;
172
+ /** The key prefix that every object goes under, such as `'runs/'`. */
173
+ readonly prefix?: string;
174
+ };
175
+ /**
176
+ * What `object_store` returns: a `CheckpointStore` with every optional
177
+ * capability, which is what `durable` needs from its store.
178
+ */
179
+ type ObjectStore = Required<Omit<CheckpointStore, 'scope'>> & {
180
+ readonly scope: (prefix: string) => ObjectScopedStore;
181
+ };
182
+ /**
183
+ * A scope of an `object_store`, which can also `clear`.
184
+ */
185
+ type ObjectScopedStore = ObjectStore & {
186
+ readonly clear: () => Promise<void>;
187
+ };
188
+ /**
189
+ * Create a `CheckpointStore` that keeps its values, claims, and scopes as
190
+ * objects behind `config.client`, under `config.prefix`.
191
+ *
192
+ * Run `checkpoint_store_conformance` from `fascicle/testing` against a real
193
+ * bucket once before trusting a service with it. A service that accepts a
194
+ * condition and ignores it lets two writers both win, and that suite is what
195
+ * catches it.
196
+ */
197
+ export declare function object_store(config: ObjectStoreConfig): ObjectStore;
198
+ export type { FilesystemLoggerConfig, FilesystemScopedStore, FilesystemStore, FilesystemStoreConfig, HttpLoggerConfig, HttpLoggerFetch, MemoryScopedStore, MemoryStore, MemoryStoreOptions, ObjectClient, ObjectPutCondition, ObjectScopedStore, ObjectStore, ObjectStoreConfig, SqliteScopedStore, SqliteStore, SqliteStoreConfig, StderrLoggerOptions };
111
199
  //# sourceMappingURL=adapters.d.ts.map
package/dist/adapters.js CHANGED
@@ -1 +1 @@
1
- export { o as filesystem_logger, t as filesystem_store, a as http_logger, i as noop_logger, r as stderr_logger, n as tee_logger } from "./adapters-CpKpDk7r.js";
1
+ export { l as filesystem_logger, i as filesystem_store, c as http_logger, r as memory_store, s as noop_logger, t as object_store, n as sqlite_store, o as stderr_logger, a as tee_logger } from "./adapters-DYFauXE1.js";
package/dist/agents.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as Step } from "./types-BUXt_zgJ.js";
2
- import { l as EffortLevel, u as Engine } from "./types-Dk9tLpUq.js";
1
+ import { c as Step } from "./types-BtRpSctv.js";
2
+ import { l as EffortLevel, u as Engine } from "./types-CDTW7XWB.js";
3
3
  import { r as ToolSchema } from "./types-CvghbZ0x.js";
4
4
  type AgentBuiltPrompt = string | {
5
5
  readonly user: string;
package/dist/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as step, j as aborted_error, v as assert_valid_step_id } from "./core-BH7sWpEG.js";
1
+ import { _ as step, j as aborted_error, v as assert_valid_step_id } from "./core-xTtRZqdb.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  // src/agents/define_agent.ts