fascicle 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +8 -8
  3. package/dist/acp.d.ts +16 -2
  4. package/dist/acp.js +1406 -1307
  5. package/dist/acp.js.map +1 -1
  6. package/dist/{adapters-DNnzeLxr.js → adapters-CDUzZlby.js} +35 -13
  7. package/dist/adapters-CDUzZlby.js.map +1 -0
  8. package/dist/adapters.d.ts +8 -1
  9. package/dist/adapters.js +1 -1
  10. package/dist/agents.d.ts +1 -1
  11. package/dist/agents.js +15 -8
  12. package/dist/agents.js.map +1 -1
  13. package/dist/bin/fascicle-viewer.js +4 -1
  14. package/dist/console-CdB4pcFO.js +37 -0
  15. package/dist/console-CdB4pcFO.js.map +1 -0
  16. package/dist/{core-CDrz0NM1.js → core-CErsxGF6.js} +246 -147
  17. package/dist/core-CErsxGF6.js.map +1 -0
  18. package/dist/diagram_bin.js +2 -2
  19. package/dist/diagram_bin.js.map +1 -1
  20. package/dist/{engine-BDWB2jdn.js → engine-CR8q2IqV.js} +683 -511
  21. package/dist/engine-CR8q2IqV.js.map +1 -0
  22. package/dist/index.d.ts +529 -73
  23. package/dist/index.js +440 -137
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-tjTjZLHj.js → invoke-COaeZ-vy.js} +98 -26
  26. package/dist/invoke-COaeZ-vy.js.map +1 -0
  27. package/dist/{json_schema_to_standard-r21kW2LI.js → json_schema_to_standard-C4F4lXHE.js} +11 -32
  28. package/dist/json_schema_to_standard-C4F4lXHE.js.map +1 -0
  29. package/dist/{leading_system-BQe_405V.js → leading_system-PoHzNHuV.js} +277 -3
  30. package/dist/leading_system-PoHzNHuV.js.map +1 -0
  31. package/dist/mcp.d.ts +6 -5
  32. package/dist/mcp.js +11 -6
  33. package/dist/mcp.js.map +1 -1
  34. package/dist/otel.js +10 -10
  35. package/dist/otel.js.map +1 -1
  36. package/dist/records-1HU7mWXf.js +22 -0
  37. package/dist/records-1HU7mWXf.js.map +1 -0
  38. package/dist/{search-CqH5hmuF.js → search-CpCJYMUm.js} +73 -10
  39. package/dist/search-CpCJYMUm.js.map +1 -0
  40. package/dist/search_worker.js +1 -1
  41. package/dist/stdio.js +7 -3
  42. package/dist/stdio.js.map +1 -1
  43. package/dist/testing.d.ts +1 -1
  44. package/dist/testing.js +3 -3
  45. package/dist/testing.js.map +1 -1
  46. package/dist/{trajectory-Bm-mOtqw.d.ts → trajectory-BKGNxi7u.d.ts} +10 -9
  47. package/dist/{trajectory-BI-mrVFT.js → trajectory-DeURWIhj.js} +6 -5
  48. package/dist/trajectory-DeURWIhj.js.map +1 -0
  49. package/dist/{types-C_Rmcgck.d.ts → types-Sw0oHW-_.d.ts} +47 -9
  50. package/dist/ui.d.ts +2 -1
  51. package/dist/ui.js +8 -1
  52. package/dist/ui.js.map +1 -1
  53. package/dist/viewer-app/assets/index-BYF5Dp7d.js +2 -0
  54. package/dist/viewer-app/index.html +2 -1
  55. package/dist/viewer.d.ts +26 -12
  56. package/dist/viewer.js +282 -63
  57. package/dist/viewer.js.map +1 -1
  58. package/package.json +4 -4
  59. package/dist/adapters-DNnzeLxr.js.map +0 -1
  60. package/dist/core-CDrz0NM1.js.map +0 -1
  61. package/dist/engine-BDWB2jdn.js.map +0 -1
  62. package/dist/invoke-tjTjZLHj.js.map +0 -1
  63. package/dist/json_schema_to_standard-r21kW2LI.js.map +0 -1
  64. package/dist/leading_system-BQe_405V.js.map +0 -1
  65. package/dist/search-CqH5hmuF.js.map +0 -1
  66. package/dist/trajectory-BI-mrVFT.js.map +0 -1
  67. package/dist/viewer-app/assets/index-Fnh5HKSU.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"viewer.js","names":["fs_watch"],"sources":["../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterConfig = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(config: BroadcasterConfig): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, config.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (config.on_subscriber_error) config.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the\n * compiled run canvas served as static files.\n *\n * GET /api/events -> text/event-stream, replaying past the client cursor\n * GET /api/trajectory -> the full run history as NDJSON (file, or ring)\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n * GET /<anything> -> a file from the compiled app, `/` being index.html\n *\n * The server owns nothing but the socket. The broadcaster owns the recent\n * event ring; the tailed file owns the full history; the canvas is a vite build\n * on disk. A client folds `/api/trajectory` for the whole run and then follows\n * `/api/events`, which replays anything past the cursor it names and streams\n * new events live. The ring is bounded memory by design, so history older than\n * it is served from the file the tail already reads (D7).\n */\n\nimport { createReadStream, statSync, type Stats } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, extname, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The header `/api/trajectory` stamps with the broadcaster's newest id: the\n * seam the client resumes SSE from after folding the history dump. The client\n * carries the same literal (`app/history.ts`); the two ends cannot share a\n * module because the browser bundle must not pull in node builtins.\n */\nconst CURSOR_HEADER = 'x-fascicle-cursor'\n\n/**\n * Content types for everything the compiled app ships. Anything outside the\n * map is served as an opaque download rather than guessed at, which keeps a\n * stray file from being executed as script by a browser.\n */\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css; charset=utf-8',\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.woff2': 'font/woff2',\n}\n\nconst FALLBACK_CONTENT_TYPE = 'application/octet-stream'\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n /**\n * Where the compiled canvas lives, defaulting to the bundled\n * `dist/viewer-app`. The tests point it at a fixture directory so the suite\n * never depends on a build having run.\n */\n readonly app_dir?: string\n /**\n * The trajectory file `/api/trajectory` streams as full history. Absent when\n * the server is ingest-fed only, where that route falls back to the ring\n * (D7). Threaded from the tailed `path` by `start_viewer`.\n */\n readonly trajectory_path?: string\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the four API routes (health, snapshot, SSE, ingest) plus the compiled\n * app's static files to a single request handler, and resolves with the bound\n * URL and a `close` that shuts the socket down. The API routes are matched\n * first and exactly, so no file the canvas ships can ever shadow one.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, app_dir, trajectory_path, on_parse_error } = config\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/trajectory') {\n serve_trajectory(res, broadcaster, trajectory_path)\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n if (route.startsWith('GET /')) {\n serve_app_asset(res, route, app_dir)\n return\n }\n send_not_found(res, route)\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (for example, port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n const url = `http://${host}:${bound_port_of(http_server.address(), port)}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Resolves the port a listening server actually bound to.\n *\n * `address()` is only an `AddressInfo` for a TCP listen; it is a path string\n * for a unix socket and `null` before listening, so the fallback covers both.\n * The bound port differs from the requested one only when the caller passed 0\n * and asked the OS to pick a free port.\n */\nexport function bound_port_of(addr: ReturnType<Server['address']>, fallback: number): number {\n return addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : fallback\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Resolves the path against the client's `Host` header when it parses, and\n * against the server's own `host`/`port` otherwise. A header can be present yet\n * malformed (`'in valid'`), which `??` cannot catch because it is neither null\n * nor undefined; fed to `new URL` it throws. Trying the header inside a\n * try/catch and falling back to the server's authority keeps route resolution\n * total for any header a client sends.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const method = req.method ?? 'GET'\n const path = req.url ?? '/'\n const header = req.headers.host\n if (header !== undefined) {\n try {\n return `${method} ${new URL(path, `http://${header}`).pathname}`\n } catch {\n // A malformed Host header falls through to the server's own authority.\n }\n }\n return `${method} ${new URL(path, `http://${host}:${port}`).pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n // `closeAllConnections` has existed since node 18.2 and `engines.node` is\n // `>=24`, so the call is unconditional.\n server.closeAllConnections()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Writes the JSON 404 that names the route that missed.\n */\nfunction send_not_found(res: ServerResponse, route: string): void {\n send_json(res, 404, { error: 'not_found', route })\n}\n\n/**\n * Handles `GET /api/trajectory` by streaming the whole run history as NDJSON,\n * one event per line, so the client folds the full run before it follows the\n * live tail (D7).\n *\n * The tailed file is the source of truth: its bytes stream straight through,\n * which keeps memory bounded no matter how long the run grew, and a finished\n * `.jsonl` opened with no live producer becomes the same client path as live.\n * An ingest-fed server has no file, so it falls back to the ring buffer, the\n * only history it holds. Either way the response is stamped with the\n * broadcaster's newest id, the seam the client resumes SSE from; the client\n * still takes the larger of that and its own folded count, so a file that ran\n * ahead of the broadcaster is not re-folded.\n */\nfunction serve_trajectory(\n res: ServerResponse,\n broadcaster: Broadcaster,\n trajectory_path: string | undefined,\n): void {\n const ring = broadcaster.snapshot()\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0))\n\n // The two guards are nested rather than joined with `&&` on purpose: only a\n // present file reaches `createReadStream`, so a path that is undefined (ingest\n // mode) or set-but-uncreated (a run not yet started) falls through to the\n // ring, the only history such a server holds (D7). `stat_file` returns null\n // for a missing path either way, which keeps the fallthrough total.\n if (trajectory_path !== undefined) {\n if (stat_file(trajectory_path) !== null) {\n createReadStream(trajectory_path).pipe(res)\n return\n }\n }\n res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\\n`).join(''))\n}\n\n/**\n * Where the compiled canvas can be, relative to this module.\n *\n * Published, `viewer.js` sits in `dist/` beside `dist/viewer-app/`. Running\n * from source, this module is `src/viewer/server.ts` and the same build output\n * is two levels up in the repo's `dist/`. The two candidates never both exist\n * for the same install, so probing them in order is unambiguous.\n */\nfunction app_dir_candidates(here: string): readonly string[] {\n return [resolve(here, 'viewer-app'), resolve(here, '..', '..', 'dist', 'viewer-app')]\n}\n\n/**\n * The compiled app directory, or `null` when the canvas has not been built.\n *\n * A directory only counts once its `index.html` is really there, so a\n * half-written build reads as absent rather than as a directory that 404s\n * every asset.\n */\nfunction resolve_app_dir(override: string | undefined): string | null {\n const candidates = override === undefined ? app_dir_candidates(HERE) : [override]\n return candidates.find((dir) => stat_file(resolve(dir, 'index.html')) !== null) ?? null\n}\n\n/**\n * The stats of an existing regular file, or `null` for anything else.\n *\n * One syscall answers both questions the asset route asks: whether to serve\n * the path at all, and what `content-length` to declare. Reading the stats\n * before the stream opens is what keeps a missing file a clean 404 rather\n * than a stream error raised after the headers have gone out.\n */\nfunction stat_file(path: string): Stats | null {\n try {\n const stats = statSync(path)\n return stats.isFile() ? stats : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolves a URL path inside the compiled app directory, or `null` when it\n * escapes it.\n *\n * The server is bound to localhost by default, but a browser will happily\n * send `/../../etc/passwd`, so containment is checked on the resolved path\n * rather than trusted from the URL text.\n */\nfunction resolve_app_file(dir: string, url_path: string): string | null {\n const file = resolve(dir, `.${url_path}`)\n if (file !== dir && !file.startsWith(dir + sep)) return null\n return file === dir ? resolve(dir, 'index.html') : file\n}\n\n/**\n * Streams one file of the compiled canvas as the response body.\n *\n * A missing app directory is a 500 naming the build step, because the server\n * is fine and the operator forgot to compile; a missing file inside a present\n * app is an ordinary 404.\n */\nfunction serve_app_asset(res: ServerResponse, route: string, override: string | undefined): void {\n const dir = resolve_app_dir(override)\n if (dir === null) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer app not built; run `pnpm build`')\n return\n }\n\n // The route key is `\"<METHOD> <path>\"`; splitting on the space keeps the\n // path independent of which method got here, so the GET guard above stays\n // the only thing deciding whether a non-GET reaches the filesystem.\n const file = resolve_app_file(dir, route.slice(route.indexOf(' ') + 1))\n const stats = file === null ? null : stat_file(file)\n if (file === null || stats === null) {\n send_not_found(res, route)\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE)\n // A localhost dev tool is rebuilt while its tab is open, so nothing it\n // serves may be cached: a stale bundle would look like a broken canvas.\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(stats.size))\n createReadStream(file).pipe(res)\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its cursor, subscribes it to the\n * broadcaster for new events, and keeps the connection alive with a periodic\n * heartbeat comment. The cursor is the furthest the client can name: the\n * `Last-Event-ID` a reconnecting browser sends, or the `?since=` a fresh load\n * sets after folding `/api/trajectory`, because native `EventSource` cannot set\n * the header on a first connect. That same cursor guards the live subscription,\n * so an event the history dump already carried is never delivered twice when\n * the file ran ahead of the broadcaster at dump time.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Node holds the response head back until something is written, so a stream\n // that opens on an empty ring buffer would sit headerless until the first\n // heartbeat 15 seconds later, and `EventSource` would not raise `open` until\n // then. One comment frame flushes the head immediately and is ignored by\n // every SSE client.\n res.write(': connected\\n\\n')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const cursor = Math.max(\n parse_last_event_id(req.headers['last-event-id']),\n parse_since(req.url),\n )\n for (const entry of broadcaster.snapshot_after(cursor)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n // The live guard matters only when the cursor sits ahead of the ring: a fresh\n // load that folded a file the broadcaster had not caught up to. In the common\n // reconnect case every live id is already past the cursor, so nothing drops.\n const unsubscribe = broadcaster.subscribe((entry) => {\n if (entry.id > cursor) write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Parses the `?since=` cursor off a request URL, defaulting to 0.\n *\n * A fresh load sets it after folding `/api/trajectory`, since native\n * `EventSource` cannot send a `Last-Event-ID` header on a first connect. The\n * value reuses `parse_last_event_id`'s number rule, so a missing, absent, or\n * unusable `since` reads as \"no cursor\" exactly as the header does.\n */\nfunction parse_since(url: string | undefined): number {\n if (typeof url !== 'string') return 0\n const query = url.indexOf('?')\n if (query === -1) return 0\n return parse_last_event_id(new URLSearchParams(url.slice(query + 1)).get('since') ?? undefined)\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n let buf = ''\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = {\n SSE_HEARTBEAT_MS,\n CURSOR_HEADER,\n app_dir_candidates,\n resolve_app_dir,\n resolve_app_file,\n parse_last_event_id,\n parse_since,\n serve_trajectory,\n handle_sse,\n handle_ingest,\n}\n","/**\n * JSONL file tailer.\n *\n * Watches a file for appends and emits one parsed trajectory event per\n * complete line. Handles three pathological cases:\n *\n * - Truncation / rotation: a watcher event whose stat is shorter than the\n * current offset means the file shrunk. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `parse_trajectory_event` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * The watcher is fs.watch-based; reads are serialized and change events\n * that arrive mid-read are coalesced into one extra pass rather than\n * dropped, so a burst of appends never starts overlapping reads. Each pass\n * re-stats and re-reads from the saved offset, which also covers platforms\n * where fs.watch misses some append notifications: the next successful\n * change event catches the file up regardless.\n */\n\nimport { type FSWatcher, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailConfig = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. Overlapping change events are coalesced: a read already in\n * flight absorbs any events that fire while it runs instead of starting a\n * second concurrent read.\n */\nexport function start_tail(config: TailConfig): Tail {\n const { path, on_event, on_parse_error, on_io_error } = config\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n const read_more = async (): Promise<void> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return\n }\n if (st.size < offset) {\n // File is shorter than our offset: it was truncated or rotated.\n // Restart from the top instead of seeking to a now-invalid offset.\n offset = 0\n buffer = ''\n }\n if (st.size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n if (on_io_error) on_io_error(err)\n return null\n })\n if (!fh) return\n try {\n const length = st.size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n try {\n watcher = fs_watch(path, { persistent: true }, () => { schedule() })\n } catch (err) {\n if (on_io_error) on_io_error(err)\n }\n\n const stop = (): void => {\n closed = true\n if (watcher) {\n watcher.close()\n watcher = null\n }\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. HTTP ingest\n * and SSE are always available; tailing is opt-in via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n // The tailed file is `/api/trajectory`'s full-history source (D7); an\n // ingest-only viewer leaves it unset and that route serves the ring.\n ...(options.path !== undefined ? { trajectory_path: options.path } : {}),\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse. The port is read\n * back from `server.url` rather than the requested `port` option, since\n * a caller that passes `0` gets whatever port the OS actually bound.\n */\nfunction wrap_handle(server: ViewerServer, tail: Tail | null, host: string): ViewerHandle {\n return {\n url: server.url,\n host,\n port: Number(new URL(server.url).port),\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { start_viewer } from './start_viewer.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nexport function parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port ?? '4242'\n const buffer_raw = values.buffer ?? '1000'\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen ?? false\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host ?? '127.0.0.1',\n port,\n buffer,\n listen,\n open: !values['no-open'] && (values.open ?? true),\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nexport function open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is 0.0.0.0 (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\\n`,\n )\n }\n if (args.host === '0.0.0.0') {\n process.stderr.write(\n 'fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\\n',\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`fascicle-viewer: watching ${args.path}\\n`)\n if (args.listen || args.path === undefined) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/index.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (for example, `tsx src/viewer/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBAAmB,QAAwC;CAGzE,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO,SAAS,CAAC;CACzC,MAAM,OAAyB,CAAC;CAChC,MAAM,8BAAc,IAAI,IAAgB;CACxC,IAAI,UAAU;CAEd,MAAM,QAAQ,UAAiD;EAC7D,MAAM,QAAwB;GAAE,IAAI;GAAW;EAAM;EACrD,KAAK,KAAK,KAAK;EACf,IAAI,KAAK,SAAS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AAM,8BAA8B,OAAO,IAAI,GAAG;CAEjE,IAAI,KAAK,MAAM,aAAa,OAAO,GAAG;CAEtC,MAAM,WAAW,YAA2B;EAC1C,QAAQ,OAAO,MAAM,oCAAoC;EACzD,MAAM,OAAO,MAAM;EACnB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,gBAAgB;EAAE,SAAc;CAAE,CAAC;CAC9C,QAAQ,GAAG,iBAAiB;EAAE,SAAc;CAAE,CAAC;AACjD;;;;AAKA,SAAS,eAAe,KAAsB;CAC5C,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG;CAC3B,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAYA,IAHE,QAAQ,KAAK,OAAO,KAAA,KACpB,QAAQ,KAAK,OAAO,cAAc,YAAY,GAAG,GAGjD,eAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,QAAiB;CACjE,QAAQ,OAAO,MAAM,oBAAoB,eAAe,GAAG,EAAE,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"viewer.js","names":["watch","fs_watch"],"sources":["../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterConfig = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(config: BroadcasterConfig): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, config.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (config.on_subscriber_error) config.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 API routes, SSE fan-out, NDJSON ingest, plus the\n * compiled run canvas served as static files.\n *\n * GET /api/events -> text/event-stream, replaying past the client cursor\n * GET /api/trajectory -> the full run history as NDJSON (file, or ring)\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n * GET /<anything> -> a file from the compiled app, `/` being index.html\n *\n * The server owns nothing but the socket. The broadcaster owns the recent\n * event ring; the tailed file owns the full history; the canvas is a vite build\n * on disk. A client folds `/api/trajectory` for the whole run and then follows\n * `/api/events`, which replays anything past the cursor it names and streams\n * new events live. The ring is bounded memory by design, so history older than\n * it is served from the file the tail already reads.\n *\n * A server bound to a loopback name answers only requests whose `Host` names\n * loopback too, so a web page can't reach it by rebinding a domain of its own\n * to 127.0.0.1. Ingest is mounted unless the config turns it off, reads only\n * `application/x-ndjson`, and refuses a body past 8 MB.\n */\n\nimport { createReadStream, statSync, type Stats } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { isIPv6 } from 'node:net'\nimport { dirname, extname, resolve, sep } from 'node:path'\nimport { pipeline } from 'node:stream'\nimport { fileURLToPath } from 'node:url'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\n\n/**\n * The header `/api/trajectory` stamps with the broadcaster's newest id: the\n * seam the client resumes SSE from after folding the history dump. The client\n * carries the same literal (`app/history.ts`); the two ends cannot share a\n * module because the browser bundle must not pull in node builtins.\n */\nconst CURSOR_HEADER = 'x-fascicle-cursor'\n\n/**\n * Content types for everything the compiled app ships. Anything outside the\n * map is served as an opaque download rather than guessed at, which keeps a\n * stray file from being executed as script by a browser.\n */\nconst CONTENT_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css; charset=utf-8',\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain; charset=utf-8',\n '.woff2': 'font/woff2',\n}\n\nconst FALLBACK_CONTENT_TYPE = 'application/octet-stream'\n\n/**\n * The names that keep the viewer on this machine. A server bound to one of\n * them answers only a request whose `Host` names one of them as well.\n */\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '127.0.0.1', '::1'])\n\n/** The one content type `/api/ingest` reads, which is what `http_logger` sends. */\nconst NDJSON = 'application/x-ndjson'\n\n/**\n * The most bytes one ingest body may carry. `http_logger` posts a single\n * event per request, so only a runaway or hostile client comes near it.\n */\nconst INGEST_LIMIT_BYTES = 8_000_000\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n /**\n * Where the compiled canvas lives, defaulting to the bundled\n * `dist/viewer-app`. The tests point it at a fixture directory so the suite\n * never depends on a build having run.\n */\n readonly app_dir?: string\n /**\n * The trajectory file `/api/trajectory` streams as full history. Absent when\n * the server is ingest-fed only, where that route falls back to the ring.\n * Threaded from the tailed `path` by `start_viewer`.\n */\n readonly trajectory_path?: string\n /**\n * Whether `POST /api/ingest` is mounted; default true. Off, the route is a\n * 404 like any path the API doesn't claim, which is how the CLI keeps a\n * viewer that only tails a file from taking posts.\n */\n readonly ingest?: boolean | undefined\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n /** The port the socket bound, which differs from the requested one for `port: 0`. */\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the five API routes (health, snapshot, trajectory, SSE, ingest) plus\n * the compiled app's static files to a single request handler, and resolves\n * with the bound URL and port and a `close` that shuts the socket down. The\n * `Host` check runs before anything else, then the API routes are matched\n * first and exactly, so no file the canvas ships can ever shadow one.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, app_dir, trajectory_path, ingest = true, on_parse_error } = config\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n if (!host_allowed(host, req.headers.host)) {\n send_forbidden_host(res, host)\n return\n }\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/trajectory') {\n serve_trajectory(res, broadcaster, trajectory_path)\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (ingest && route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n if (route.startsWith('GET /')) {\n serve_app_asset(res, route, app_dir)\n return\n }\n send_not_found(res, route)\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (for example, port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n const bound_port = bound_port_of(http_server.address(), port)\n res_ok({\n url: `http://${format_authority(host, bound_port)}`,\n port: bound_port,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Resolves the port a listening server actually bound to.\n *\n * `address()` is only an `AddressInfo` for a TCP listen; it is a path string\n * for a unix socket and `null` before listening, so the fallback covers both.\n * The bound port differs from the requested one only when the caller passed 0\n * and asked the OS to pick a free port.\n */\nexport function bound_port_of(addr: ReturnType<Server['address']>, fallback: number): number {\n return addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : fallback\n}\n\n/**\n * Joins a host and port into a URL authority, bracketing an IPv6 literal.\n *\n * `http://::1:4242` is not a URL; `http://[::1]:4242` is. A hostname or IPv4\n * address passes through untouched.\n */\nfunction format_authority(host: string, port: number): string {\n return `${isIPv6(host) ? `[${host}]` : host}:${port}`\n}\n\n/**\n * Whether `host` is a loopback name, which keeps a server bound to it on this\n * machine.\n */\nexport function is_loopback_host(host: string): boolean {\n return LOOPBACK_HOSTS.has(host)\n}\n\n/**\n * The hostname a `Host` header names, lowercased, with an IPv6 literal's\n * brackets and any port taken off.\n */\nfunction host_name(header: string): string {\n const host = header.toLowerCase()\n if (host.startsWith('[')) return host.slice(1, host.indexOf(']'))\n const colon = host.indexOf(':')\n return colon === -1 ? host : host.slice(0, colon)\n}\n\n/**\n * Whether a server bound to `bound` answers a request whose `Host` header is\n * `header`.\n *\n * Bound to a loopback name, it answers only a `Host` that names loopback too,\n * whatever the port, because a page that rebinds a domain of its own to\n * 127.0.0.1 still sends that domain, and would otherwise read every prompt and\n * output in the trajectory. A request with no `Host` is refused as well. Bound\n * anywhere else, it checks nothing: whoever can reach it can read it, which\n * is what the CLI warns about before it binds.\n */\nfunction host_allowed(bound: string, header: string | undefined): boolean {\n if (!is_loopback_host(bound)) return true\n return header !== undefined && is_loopback_host(host_name(header))\n}\n\n/**\n * Writes the 403 for a request whose `Host` a loopback-bound server won't\n * answer, naming the names it will.\n */\nfunction send_forbidden_host(res: ServerResponse, bound: string): void {\n send_json(res, 403, {\n error: 'forbidden_host',\n message: `this viewer is bound to ${bound} and answers only a Host of localhost, 127.0.0.1, or ::1; open it by one of those names`,\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Resolves the path against the client's `Host` header when it parses, and\n * against the server's own `host`/`port` otherwise. A header can be present yet\n * malformed (`'in valid'`), which `??` cannot catch because it is neither null\n * nor undefined; fed to `new URL` it throws. Trying the header inside a\n * try/catch and falling back to the server's authority keeps route resolution\n * total for any header a client sends.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const method = req.method ?? 'GET'\n const path = req.url ?? '/'\n const header = req.headers.host\n if (header !== undefined) {\n try {\n return `${method} ${new URL(path, `http://${header}`).pathname}`\n } catch {\n // A malformed Host header falls through to the server's own authority.\n }\n }\n return `${method} ${new URL(path, `http://${format_authority(host, port)}`).pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n // `closeAllConnections` has existed since node 18.2 and `engines.node` is\n // `>=24`, so the call is unconditional.\n server.closeAllConnections()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Writes the JSON 404 that names the route that missed.\n */\nfunction send_not_found(res: ServerResponse, route: string): void {\n send_json(res, 404, { error: 'not_found', route })\n}\n\n/**\n * Handles `GET /api/trajectory` by streaming the whole run history as NDJSON,\n * one event per line, so the client folds the full run before it follows the\n * live tail.\n *\n * The tailed file is the source of truth: its bytes stream straight through,\n * which keeps memory bounded no matter how long the run grew, and a finished\n * `.jsonl` opened with no live producer becomes the same client path as live.\n * An ingest-fed server has no file, so it falls back to the ring buffer, the\n * only history it holds. Either way the response is stamped with the\n * broadcaster's newest id, the seam the client resumes SSE from; the client\n * still takes the larger of that and its own folded count, so a file that ran\n * ahead of the broadcaster is not re-folded.\n */\nfunction serve_trajectory(\n res: ServerResponse,\n broadcaster: Broadcaster,\n trajectory_path: string | undefined,\n): void {\n const ring = broadcaster.snapshot()\n res.statusCode = 200\n res.setHeader('content-type', 'application/x-ndjson; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader(CURSOR_HEADER, String(ring.at(-1)?.id ?? 0))\n\n // The two guards are nested rather than joined with `&&` on purpose: only a\n // present file reaches `createReadStream`, so a path that is undefined (ingest\n // mode) or set-but-uncreated (a run not yet started) falls through to the\n // ring, the only history such a server holds. `stat_file` returns null\n // for a missing path either way, which keeps the fallthrough total.\n if (trajectory_path !== undefined) {\n if (stat_file(trajectory_path) !== null) {\n stream_file(res, trajectory_path)\n return\n }\n }\n res.end(ring.map((entry) => `${JSON.stringify(entry.event)}\\n`).join(''))\n}\n\n/**\n * Where the compiled canvas can be, relative to this module.\n *\n * Published, `viewer.js` sits in `dist/` beside `dist/viewer-app/`. Running\n * from source, this module is `src/viewer/server.ts` and the same build output\n * is two levels up in the repo's `dist/`. The two candidates never both exist\n * for the same install, so probing them in order is unambiguous.\n */\nfunction app_dir_candidates(here: string): readonly string[] {\n return [resolve(here, 'viewer-app'), resolve(here, '..', '..', 'dist', 'viewer-app')]\n}\n\n/**\n * The compiled app directory, or `null` when the canvas has not been built.\n *\n * A directory only counts once its `index.html` is really there, so a\n * half-written build reads as absent rather than as a directory that 404s\n * every asset.\n */\nfunction resolve_app_dir(override: string | undefined): string | null {\n const candidates = override === undefined ? app_dir_candidates(HERE) : [override]\n return candidates.find((dir) => stat_file(resolve(dir, 'index.html')) !== null) ?? null\n}\n\n/**\n * The stats of an existing regular file, or `null` for anything else.\n *\n * One syscall answers both questions the asset route asks: whether to serve\n * the path at all, and what `content-length` to declare. Reading the stats\n * before the stream opens is what keeps a missing file a clean 404 rather\n * than a stream error raised after the headers have gone out.\n */\nfunction stat_file(path: string): Stats | null {\n try {\n const stats = statSync(path)\n return stats.isFile() ? stats : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolves a URL path inside the compiled app directory, or `null` when it\n * escapes it.\n *\n * The server is bound to localhost by default, but a browser will happily\n * send `/../../etc/passwd`, so containment is checked on the resolved path\n * rather than trusted from the URL text.\n */\nfunction resolve_app_file(dir: string, url_path: string): string | null {\n const file = resolve(dir, `.${url_path}`)\n if (file !== dir && !file.startsWith(dir + sep)) return null\n return file === dir ? resolve(dir, 'index.html') : file\n}\n\n/**\n * Streams one file of the compiled canvas as the response body.\n *\n * A missing app directory is a 500 naming the build step, because the server\n * is fine and the operator forgot to compile; a missing file inside a present\n * app is an ordinary 404.\n */\nfunction serve_app_asset(res: ServerResponse, route: string, override: string | undefined): void {\n const dir = resolve_app_dir(override)\n if (dir === null) {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer app not built; run `pnpm build`')\n return\n }\n\n // The route key is `\"<METHOD> <path>\"`; splitting on the space keeps the\n // path independent of which method got here, so the GET guard above stays\n // the only thing deciding whether a non-GET reaches the filesystem.\n const file = resolve_app_file(dir, route.slice(route.indexOf(' ') + 1))\n const stats = file === null ? null : stat_file(file)\n if (file === null || stats === null) {\n send_not_found(res, route)\n return\n }\n\n res.statusCode = 200\n res.setHeader('content-type', CONTENT_TYPES[extname(file)] ?? FALLBACK_CONTENT_TYPE)\n // A localhost dev tool is rebuilt while its tab is open, so nothing it\n // serves may be cached: a stale bundle would look like a broken canvas.\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(stats.size))\n stream_file(res, file)\n}\n\n/**\n * Streams a file as the response body, dropping the connection if the read\n * fails.\n *\n * A file can pass `stat_file` and still refuse to open (mode 000 answers\n * EACCES), and a bare `pipe` leaves that stream error unhandled, which ends the\n * process. `pipeline` handles it by destroying both ends, so the client sees a\n * dropped connection and the server keeps serving. It also closes the file when\n * a client leaves mid-stream.\n */\nfunction stream_file(res: ServerResponse, path: string): void {\n pipeline(createReadStream(path), res, () => {\n // Both streams are already destroyed on failure; nothing is left to undo.\n })\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its cursor, subscribes it to the\n * broadcaster for new events, and keeps the connection alive with a periodic\n * heartbeat comment. The cursor is the furthest the client can name: the\n * `Last-Event-ID` a reconnecting browser sends, or the `?since=` a fresh load\n * sets after folding `/api/trajectory`, because native `EventSource` cannot set\n * the header on a first connect. That same cursor guards the live subscription,\n * so an event the history dump already carried is never delivered twice when\n * the file ran ahead of the broadcaster at dump time.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Node holds the response head back until something is written, so a stream\n // that opens on an empty ring buffer would sit headerless until the first\n // heartbeat 15 seconds later, and `EventSource` would not raise `open` until\n // then. One comment frame flushes the head immediately and is ignored by\n // every SSE client.\n res.write(': connected\\n\\n')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const cursor = Math.max(\n parse_last_event_id(req.headers['last-event-id']),\n parse_since(req.url),\n )\n for (const entry of broadcaster.snapshot_after(cursor)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n // The live guard matters only when the cursor sits ahead of the ring: a fresh\n // load that folded a file the broadcaster had not caught up to. In the common\n // reconnect case every live id is already past the cursor, so nothing drops.\n const unsubscribe = broadcaster.subscribe((entry) => {\n if (entry.id > cursor) write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Parses the `?since=` cursor off a request URL, defaulting to 0.\n *\n * A fresh load sets it after folding `/api/trajectory`, since native\n * `EventSource` cannot send a `Last-Event-ID` header on a first connect. The\n * value reuses `parse_last_event_id`'s number rule, so a missing, absent, or\n * unusable `since` reads as \"no cursor\" exactly as the header does.\n */\nfunction parse_since(url: string | undefined): number {\n if (typeof url !== 'string') return 0\n const query = url.indexOf('?')\n if (query === -1) return 0\n return parse_last_event_id(new URLSearchParams(url.slice(query + 1)).get('since') ?? undefined)\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Whether a `content-type` header names NDJSON, whatever its case and its\n * parameters, so `application/x-ndjson; charset=utf-8` counts.\n */\nfunction is_ndjson(header: string | undefined): boolean {\n if (header === undefined) return false\n const semicolon = header.indexOf(';')\n const type = semicolon === -1 ? header : header.slice(0, semicolon)\n return type.trim().toLowerCase() === NDJSON\n}\n\n/**\n * Writes the 413 for an ingest body past the limit, closing the connection so\n * the rest of the body is never read.\n */\nfunction send_too_large(res: ServerResponse): void {\n res.setHeader('connection', 'close')\n send_json(res, 413, {\n error: 'payload_too_large',\n message: `an ingest body holds at most ${INGEST_LIMIT_BYTES} bytes; post the events in smaller batches`,\n })\n}\n\n/**\n * Answers an ingest request that won't be read, before any of its body is:\n * a 415 for a body that isn't NDJSON, and a 413 for one whose declared length\n * runs past the limit. Returns whether it answered.\n *\n * Requiring the content type is what keeps a web page out: a page can post a\n * `text/plain` body to any origin without a preflight, but not an NDJSON one.\n */\nfunction refuse_ingest(req: IncomingMessage, res: ServerResponse): boolean {\n if (!is_ndjson(req.headers['content-type'])) {\n send_json(res, 415, {\n error: 'unsupported_media_type',\n message: `post trajectory events as ${NDJSON}, one JSON event to a line`,\n })\n return true\n }\n if (Number(req.headers['content-length']) > INGEST_LIMIT_BYTES) {\n send_too_large(res)\n return true\n }\n return false\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error. A body sent without a length is counted\n * as it streams, and one that runs past the limit gets its 413 there, after\n * the lines before that point have gone out. Once a request is answered,\n * nothing more it sends is read or reported.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n if (refuse_ingest(req, res)) return\n let buf = ''\n let received = 0\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n if (res.writableEnded) return\n received += Buffer.byteLength(chunk)\n if (received > INGEST_LIMIT_BYTES) {\n send_too_large(res)\n return\n }\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n if (res.writableEnded) return\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (res.writableEnded) return\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = {\n SSE_HEARTBEAT_MS,\n CURSOR_HEADER,\n INGEST_LIMIT_BYTES,\n host_allowed,\n app_dir_candidates,\n resolve_app_dir,\n resolve_app_file,\n parse_last_event_id,\n parse_since,\n serve_trajectory,\n handle_sse,\n handle_ingest,\n}\n","/**\n * JSONL file tailer.\n *\n * Follows a path for appends and emits one parsed trajectory event per\n * complete line. Handles these pathological cases:\n *\n * - A file that doesn't exist yet: a missing file is a wait, not an\n * error. The tail reads it from its first line once it appears.\n * - Rotation: a file renamed away and recreated under the same name is a\n * new inode, so the tail starts the new file from its first line rather\n * than at the old file's offset.\n * - Truncation: a stat shorter than the current offset means the file\n * shrank in place. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `parse_trajectory_event` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * Two fs.watch watchers drive the reads. A watch on the file itself carries\n * every append, but it follows the file's inode, so it can't see a file\n * appear and after a rename it reports on the old one. So while the file is\n * missing, and from the moment that watch reports a rename, a second watch\n * on the parent directory waits for the file's name, and the first pass that\n * finds a file there moves the file watch onto it and drops the directory\n * watch. Appends never ride the directory watch, because macOS serves a\n * directory through FSEvents, whose stream starts asynchronously and drops\n * what happens before it is live, while a file watch is kqueue's and holds\n * from the moment it is made. Reads are serialized, and change events that arrive mid-read are coalesced\n * into one extra pass rather than dropped, so a burst of appends never starts\n * overlapping reads. Each pass re-stats and re-reads from the saved offset,\n * which also covers platforms where fs.watch misses some append\n * notifications: the next successful change event catches the file up\n * regardless.\n */\n\nimport { type FSWatcher, type WatchListener, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { basename, dirname } from 'node:path'\nimport { parse_trajectory_event, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailConfig = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * True for the error a stat or an open throws when nothing is at the path,\n * which the tail reads as waiting for the file rather than as a failure.\n */\nfunction is_missing(err: unknown): boolean {\n return Reflect.get(Object(err), 'code') === 'ENOENT'\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. A missing file is waited for through a watch on its directory,\n * and a new file at the path (a different inode) is read from its first\n * line. Overlapping change events are coalesced: a read already in flight\n * absorbs any events that fire while it runs instead of starting a second\n * concurrent read.\n */\nexport function start_tail(config: TailConfig): Tail {\n const { path, on_event, on_parse_error, on_io_error } = config\n const name = basename(path)\n let inode: number | null = null\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let file_watcher: FSWatcher | null = null\n let dir_watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n // A stat or open that finds nothing at the path is the wait for the file,\n // which the CLI has already warned about, so only other failures report.\n const report = (err: unknown): void => {\n if (on_io_error && !is_missing(err)) on_io_error(err)\n }\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = parse_trajectory_event(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n // Starts a watch, reporting one that can't start (a directory that doesn't\n // exist, say) rather than throwing out of a read pass. A pass that was in\n // flight when the tail stopped starts nothing, so stop() leaves no watch\n // holding the process open.\n const watch = (target: string, listener: WatchListener<string>): FSWatcher | null => {\n if (closed) return null\n try {\n return fs_watch(target, { persistent: true }, listener)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return null\n }\n }\n\n // Waits on the directory for the file's name. Arming the watch schedules\n // one more pass, which catches a file that appeared between the last stat\n // and the watch. A watch that fails to arm (its directory is missing too)\n // schedules nothing, or every pass would retry it and spin. A platform\n // that can't name the file in an event passes null, which schedules a pass\n // rather than risk missing one.\n const await_file = (): void => {\n if (dir_watcher !== null) return\n dir_watcher = watch(dirname(path), (_event, filename) => {\n if (filename === null || filename === name) schedule()\n })\n if (dir_watcher !== null) schedule()\n }\n\n // Follows the file now at the path from its first line. The file watch\n // moves onto it, and a rename it reports (the file moved away or was\n // deleted) sends the tail back to waiting on the directory.\n const adopt = (ino: number): void => {\n inode = ino\n offset = 0\n buffer = ''\n file_watcher?.close()\n file_watcher = watch(path, (event) => {\n if (event === 'rename') await_file()\n schedule()\n })\n dir_watcher?.close()\n dir_watcher = null\n }\n\n // Stats the path and returns the size to read up to, or null when nothing\n // is there. A missing file forgets its inode, so whatever appears next is\n // read from the top even if the filesystem reuses the number. A new inode\n // (the first sighting, or a file recreated after a rotation) is adopted,\n // and a file shorter than the offset was truncated in place, so both start\n // over at offset 0, since the saved offset means nothing in either.\n const locate = async (): Promise<number | null> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (is_missing(err)) {\n inode = null\n await_file()\n }\n report(err)\n return null\n }\n if (st.ino !== inode) {\n adopt(st.ino)\n } else if (st.size < offset) {\n offset = 0\n buffer = ''\n }\n return st.size\n }\n\n const read_more = async (): Promise<void> => {\n const size = await locate()\n if (size === null || size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n report(err)\n return null\n })\n if (!fh) return\n try {\n const length = size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } catch (err) {\n // A path that stats and opens can still refuse a read (a directory\n // answers EISDIR). The watcher starts read passes without awaiting\n // them, so the error is reported here rather than left to reject one.\n report(err)\n return\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n const stop = (): void => {\n closed = true\n file_watcher?.close()\n file_watcher = null\n dir_watcher?.close()\n dir_watcher = null\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n /** Whether the server takes `POST /api/ingest`, which `http_logger` posts to; default true. */\n readonly ingest?: boolean\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. SSE is always\n * available, HTTP ingest is on unless `ingest` is false, and tailing is opt-in\n * via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n ingest: options.ingest,\n // The tailed file is `/api/trajectory`'s full-history source; an\n // ingest-only viewer leaves it unset and that route serves the ring.\n ...(options.path !== undefined ? { trajectory_path: options.path } : {}),\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse. The port is the one\n * the server reports binding rather than the requested `port` option, since\n * a caller that passes `0` gets whatever port the OS actually bound.\n */\nfunction wrap_handle(server: ViewerServer, tail: Tail | null, host: string): ViewerHandle {\n return {\n url: server.url,\n host,\n port: server.port,\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * `POST /api/ingest` is mounted only under `--listen`, so a viewer that only\n * tails a file takes no posts from anything.\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the `fascicle-viewer` bin shim can drive it from the bundled\n * `dist/viewer.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { is_loopback_host } from './server.js'\nimport { start_viewer } from './start_viewer.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --listen accept HTTP push on /api/ingest (off unless set)\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; a non-loopback host warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nexport function parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port\n const buffer_raw = values.buffer\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(\n `fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\\n`,\n )\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host,\n port,\n buffer,\n listen,\n open: !values['no-open'] && values.open,\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nexport function open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is not loopback (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet, so the viewer will read it from its first line once it is created\\n`,\n )\n }\n if (!is_loopback_host(args.host)) {\n process.stderr.write(\n `fascicle-viewer: warning: binding ${args.host} reaches beyond this machine, and the dashboard has no auth, so anyone who can reach it reads your trajectory stream; pass --host 127.0.0.1 to keep it local\\n`,\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n ingest: args.listen,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`fascicle-viewer: watching ${args.path}\\n`)\n if (args.listen) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/viewer.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (for example, `tsx src/viewer/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBAAmB,QAAwC;CAGzE,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO,SAAS,CAAC;CACzC,MAAM,OAAyB,CAAC;CAChC,MAAM,8BAAc,IAAI,IAAgB;CACxC,IAAI,UAAU;CAEd,MAAM,QAAQ,UAAiD;EAC7D,MAAM,QAAwB;GAAE,IAAI;GAAW;EAAM;EACrD,KAAK,KAAK,KAAK;EACf,IAAI,KAAK,SAAS,KAAK,KAAK,OAAO,GAAG,KAAK,SAAS,GAAG;EAGvD,KAAK,MAAM,MAAM,MAAM,KAAK,WAAW,GACrC,IAAI;GACF,GAAG,KAAK;EACV,SAAS,KAAK;GACZ,YAAY,OAAO,EAAE;GACrB,IAAI,OAAO,qBAAqB,OAAO,oBAAoB,GAAG;EAChE;EAEF,OAAO;CACT;CAEA,MAAM,aAAa,OAAiC;EAClD,YAAY,I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K,QAAQ,QAAQ,OAAO,MAAM,+CAA+C,OAAO,IAAI,cAAc;CAC9G,QAAQ,OAAO,MAAM,8BAA8B,OAAO,IAAI,GAAG;CAEjE,IAAI,KAAK,MAAM,aAAa,OAAO,GAAG;CAEtC,MAAM,WAAW,YAA2B;EAC1C,QAAQ,OAAO,MAAM,oCAAoC;EACzD,MAAM,OAAO,MAAM;EACnB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,gBAAgB;EAAE,SAAc;CAAE,CAAC;CAC9C,QAAQ,GAAG,iBAAiB;EAAE,SAAc;CAAE,CAAC;AACjD;;;;AAKA,SAAS,eAAe,KAAsB;CAC5C,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG;CAC3B,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAYA,IAHE,QAAQ,KAAK,OAAO,KAAA,KACpB,QAAQ,KAAK,OAAO,cAAc,YAAY,GAAG,GAGjD,eAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,QAAiB;CACjE,QAAQ,OAAO,MAAM,oBAAoB,eAAe,GAAG,EAAE,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fascicle",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
5
5
  "keywords": [
6
6
  "agents",
@@ -35,8 +35,7 @@
35
35
  },
36
36
  "type": "module",
37
37
  "engines": {
38
- "node": ">=24.0.0",
39
- "pnpm": ">=10.13.0"
38
+ "node": ">=24.0.0"
40
39
  },
41
40
  "packageManager": "pnpm@11.28.5",
42
41
  "main": "./dist/index.js",
@@ -105,6 +104,7 @@
105
104
  "#acp": "./src/acp/index.ts",
106
105
  "#ui": "./src/ui/index.ts",
107
106
  "#policy": "./src/policy/index.ts",
107
+ "#process": "./src/process/index.ts",
108
108
  "#schema": "./src/schema/index.ts",
109
109
  "#testing": "./src/testing/index.ts"
110
110
  },
@@ -164,7 +164,7 @@
164
164
  "@opentelemetry/api": "^1.9.0",
165
165
  "ai": "^7.0.0",
166
166
  "ai-sdk-ollama": "^4.0.0",
167
- "zod": "4.4.3"
167
+ "zod": "^4.2.0"
168
168
  },
169
169
  "peerDependenciesMeta": {
170
170
  "@ai-sdk/amazon-bedrock": {
@@ -1 +0,0 @@
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,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;E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