fascicle 0.12.1 → 0.12.3

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 (47) hide show
  1. package/CHANGELOG.md +79 -33
  2. package/README.md +13 -13
  3. package/dist/{adapters-hmnJOOgf.js → adapters-CutexJd3.js} +12 -12
  4. package/dist/adapters-CutexJd3.js.map +1 -0
  5. package/dist/adapters.d.ts +10 -10
  6. package/dist/adapters.js +1 -1
  7. package/dist/agents.d.ts +13 -3
  8. package/dist/agents.js +12 -5
  9. package/dist/agents.js.map +1 -1
  10. package/dist/{core-DDRhHu5P.js → core-DdJEhyQc.js} +122 -488
  11. package/dist/core-DdJEhyQc.js.map +1 -0
  12. package/dist/{engine-b4ZH8esY.js → engine-J4lIxpw5.js} +40 -357
  13. package/dist/engine-J4lIxpw5.js.map +1 -0
  14. package/dist/index.d.ts +85 -25
  15. package/dist/index.js +402 -48
  16. package/dist/index.js.map +1 -1
  17. package/dist/{invoke-CyKNhvBw.js → invoke-CH_eJZeS.js} +8 -8
  18. package/dist/{invoke-CyKNhvBw.js.map → invoke-CH_eJZeS.js.map} +1 -1
  19. package/dist/leading_system-BUCT-PwD.js +330 -0
  20. package/dist/leading_system-BUCT-PwD.js.map +1 -0
  21. package/dist/mcp.d.ts +5 -5
  22. package/dist/mcp.js +10 -9
  23. package/dist/mcp.js.map +1 -1
  24. package/dist/otel.d.ts +1 -1
  25. package/dist/otel.js +4 -4
  26. package/dist/otel.js.map +1 -1
  27. package/dist/stdio.d.ts +2 -2
  28. package/dist/stdio.js +2 -2
  29. package/dist/testing.d.ts +1 -1
  30. package/dist/testing.js +3 -2
  31. package/dist/testing.js.map +1 -1
  32. package/dist/{trajectory-cSLNlHzh.d.ts → trajectory-ByoOQZ6T.d.ts} +10 -10
  33. package/dist/trajectory-D1eq9eue.js +81 -0
  34. package/dist/trajectory-D1eq9eue.js.map +1 -0
  35. package/dist/{types-BCtKsxrX.d.ts → types-BK0UW28o.d.ts} +3 -3
  36. package/dist/{types-BqUY6nRX.d.ts → types-DBpU27sQ.d.ts} +7 -2
  37. package/dist/{types-CXBB4aIM.d.ts → types-DU6cvoA4.d.ts} +3 -3
  38. package/dist/ui.d.ts +1 -1
  39. package/dist/ui.js +1 -1
  40. package/dist/ui.js.map +1 -1
  41. package/dist/viewer.d.ts +8 -8
  42. package/dist/viewer.js +16 -15
  43. package/dist/viewer.js.map +1 -1
  44. package/package.json +5 -4
  45. package/dist/adapters-hmnJOOgf.js.map +0 -1
  46. package/dist/core-DDRhHu5P.js.map +0 -1
  47. package/dist/engine-b4ZH8esY.js.map +0 -1
@@ -0,0 +1,81 @@
1
+ //#region src/core/trajectory.ts
2
+ /**
3
+ * The wire gate: a non-array object carrying a string `kind`.
4
+ *
5
+ * True for every well-known kind as well, since `custom` is the fallback shape
6
+ * rather than a disjoint case.
7
+ */
8
+ function is_custom_trajectory_event(value) {
9
+ if (typeof value !== "object" || value === null) return false;
10
+ if (Array.isArray(value)) return false;
11
+ return typeof value.kind === "string";
12
+ }
13
+ /** A composer span open: both `span_id` and `name` must be present as strings. */
14
+ function is_span_start_event(value) {
15
+ if (!is_custom_trajectory_event(value)) return false;
16
+ if (value.kind !== "span_start") return false;
17
+ return typeof value["span_id"] === "string" && typeof value["name"] === "string";
18
+ }
19
+ /** A composer span close: `span_id` must be present as a string, `name` need not be. */
20
+ function is_span_end_event(value) {
21
+ if (!is_custom_trajectory_event(value)) return false;
22
+ return value.kind === "span_end" && typeof value["span_id"] === "string";
23
+ }
24
+ /** A `ctx.emit` event: the kind alone identifies it, the payload is the caller's. */
25
+ function is_emit_event(value) {
26
+ return is_custom_trajectory_event(value) && value.kind === "emit";
27
+ }
28
+ const RUN_END_STATUSES = /* @__PURE__ */ new Set([
29
+ "done",
30
+ "failed",
31
+ "aborted",
32
+ "suspended"
33
+ ]);
34
+ /**
35
+ * A terminal run event: `status` must be one of the known run outcomes, so the
36
+ * narrowed type's `status` union is truthful. An unknown future status still
37
+ * passes the wire gate as a custom event.
38
+ */
39
+ function is_run_end_event(value) {
40
+ if (!is_custom_trajectory_event(value)) return false;
41
+ if (value.kind !== "run_end") return false;
42
+ const status = value["status"];
43
+ return typeof status === "string" && RUN_END_STATUSES.has(status);
44
+ }
45
+ const CHECKPOINT_STATUSES = /* @__PURE__ */ new Set([
46
+ "hit",
47
+ "miss",
48
+ "read_error"
49
+ ]);
50
+ /**
51
+ * A checkpoint lookup event: `status` must be a known lookup outcome and `key`
52
+ * the store key that was consulted, for the same truthful-narrowing reason as
53
+ * `is_run_end_event`.
54
+ */
55
+ function is_checkpoint_event(value) {
56
+ if (!is_custom_trajectory_event(value)) return false;
57
+ if (value.kind !== "checkpoint") return false;
58
+ const status = value["status"];
59
+ if (typeof status !== "string" || !CHECKPOINT_STATUSES.has(status)) return false;
60
+ return typeof value["key"] === "string";
61
+ }
62
+ /**
63
+ * Parse one wire value into a trajectory event, `safeParse`-shaped.
64
+ *
65
+ * On success `data` is the value itself, not a copy, so nothing on the line is
66
+ * dropped or reordered on the way through.
67
+ */
68
+ function parse_trajectory_event(value) {
69
+ if (!is_custom_trajectory_event(value)) return {
70
+ success: false,
71
+ error: /* @__PURE__ */ new Error("not a trajectory event: expected an object with a string 'kind'")
72
+ };
73
+ return {
74
+ success: true,
75
+ data: value
76
+ };
77
+ }
78
+ //#endregion
79
+ export { is_span_end_event as a, is_run_end_event as i, is_custom_trajectory_event as n, is_span_start_event as o, is_emit_event as r, parse_trajectory_event as s, is_checkpoint_event as t };
80
+
81
+ //# sourceMappingURL=trajectory-D1eq9eue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trajectory-D1eq9eue.js","names":[],"sources":["../src/core/trajectory.ts"],"sourcesContent":["/**\n * Wire-format guards for trajectory events.\n *\n * `TrajectoryEvent` (in `types.ts`) is the loose internal type — any code that\n * calls `trajectory.record(event)` or `start_span(name, meta)` produces values\n * conforming to it. This file defines the *narrower* shapes that the studio\n * (and any other downstream consumer) can recognize in the wire stream:\n *\n * span_start: composer span open\n * span_end: composer span close\n * emit: user-emitted event from inside a step (ctx.emit)\n * run_end: terminal run event carrying the run's status, so a consumer\n * distinguishes done / failed / aborted / suspended without\n * inferring from silence\n * checkpoint: checkpoint store lookup outcome (hit / miss / read_error)\n * <other>: anything else, recognized by `is_custom_trajectory_event`,\n * which only requires a string `kind`\n *\n * `parse_trajectory_event` is the wire gate, and it is deliberately permissive:\n * a value is a trajectory event iff it is a non-array object carrying a string\n * `kind`. The well-known guards layered on top are *recognizers*, not gates — a\n * `{ kind: 'span_start' }` line missing its `span_id` is still a valid event on\n * the wire, just not a `SpanStartEvent`. Anything stricter would have a viewer\n * drop lines a newer producer emits, which is the opposite of what a\n * forward-compatible wire format is for. `is_custom_trajectory_event` therefore\n * answers `true` for well-known kinds too: it is the fallback shape, not a\n * fifth disjoint case.\n *\n * Extra fields (`run_id`, `id`, provider-specific metadata) are neither\n * required nor stripped: a successful parse hands the value straight back, so a\n * parse / re-serialize round trip is lossless.\n */\n\nexport type SpanStartEvent = {\n readonly kind: 'span_start'\n readonly span_id: string\n readonly name: string\n} & { readonly [key: string]: unknown }\n\nexport type SpanEndEvent = {\n readonly kind: 'span_end'\n readonly span_id: string\n} & { readonly [key: string]: unknown }\n\nexport type EmitEvent = {\n readonly kind: 'emit'\n} & { readonly [key: string]: unknown }\n\nexport type RunEndStatus = 'done' | 'failed' | 'aborted' | 'suspended'\n\nexport type RunEndEvent = {\n readonly kind: 'run_end'\n readonly status: RunEndStatus\n} & { readonly [key: string]: unknown }\n\nexport type CheckpointStatus = 'hit' | 'miss' | 'read_error'\n\nexport type CheckpointEvent = {\n readonly kind: 'checkpoint'\n readonly status: CheckpointStatus\n readonly key: string\n} & { readonly [key: string]: unknown }\n\nexport type CustomTrajectoryEvent = {\n readonly kind: string\n} & { readonly [key: string]: unknown }\n\nexport type ParsedTrajectoryEvent =\n | SpanStartEvent\n | SpanEndEvent\n | EmitEvent\n | RunEndEvent\n | CheckpointEvent\n | CustomTrajectoryEvent\n\nexport type TrajectoryParseResult =\n | { readonly success: true; readonly data: ParsedTrajectoryEvent }\n | { readonly success: false; readonly error: Error }\n\n/**\n * The wire gate: a non-array object carrying a string `kind`.\n *\n * True for every well-known kind as well, since `custom` is the fallback shape\n * rather than a disjoint case.\n */\nexport function is_custom_trajectory_event(value: unknown): value is CustomTrajectoryEvent {\n if (typeof value !== 'object' || value === null) return false\n if (Array.isArray(value)) return false\n return typeof (value as { kind?: unknown }).kind === 'string'\n}\n\n/** A composer span open: both `span_id` and `name` must be present as strings. */\nexport function is_span_start_event(value: unknown): value is SpanStartEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'span_start') return false\n return typeof value['span_id'] === 'string' && typeof value['name'] === 'string'\n}\n\n/** A composer span close: `span_id` must be present as a string, `name` need not be. */\nexport function is_span_end_event(value: unknown): value is SpanEndEvent {\n if (!is_custom_trajectory_event(value)) return false\n return value.kind === 'span_end' && typeof value['span_id'] === 'string'\n}\n\n/** A `ctx.emit` event: the kind alone identifies it, the payload is the caller's. */\nexport function is_emit_event(value: unknown): value is EmitEvent {\n return is_custom_trajectory_event(value) && value.kind === 'emit'\n}\n\nconst RUN_END_STATUSES: ReadonlySet<string> = new Set(['done', 'failed', 'aborted', 'suspended'])\n\n/**\n * A terminal run event: `status` must be one of the known run outcomes, so the\n * narrowed type's `status` union is truthful. An unknown future status still\n * passes the wire gate as a custom event.\n */\nexport function is_run_end_event(value: unknown): value is RunEndEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'run_end') return false\n const status = value['status']\n return typeof status === 'string' && RUN_END_STATUSES.has(status)\n}\n\nconst CHECKPOINT_STATUSES: ReadonlySet<string> = new Set(['hit', 'miss', 'read_error'])\n\n/**\n * A checkpoint lookup event: `status` must be a known lookup outcome and `key`\n * the store key that was consulted, for the same truthful-narrowing reason as\n * `is_run_end_event`.\n */\nexport function is_checkpoint_event(value: unknown): value is CheckpointEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'checkpoint') return false\n const status = value['status']\n if (typeof status !== 'string' || !CHECKPOINT_STATUSES.has(status)) return false\n return typeof value['key'] === 'string'\n}\n\n/**\n * Parse one wire value into a trajectory event, `safeParse`-shaped.\n *\n * On success `data` is the value itself, not a copy, so nothing on the line is\n * dropped or reordered on the way through.\n */\nexport function parse_trajectory_event(value: unknown): TrajectoryParseResult {\n if (!is_custom_trajectory_event(value)) {\n return {\n success: false,\n error: new Error(\"not a trajectory event: expected an object with a string 'kind'\"),\n }\n }\n return { success: true, data: value }\n}\n"],"mappings":";;;;;;;AAqFA,SAAgB,2BAA2B,OAAgD;CACzF,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,OAAQ,MAA6B,SAAS;AACvD;;AAGA,SAAgB,oBAAoB,OAAyC;CAC3E,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,cAAc,OAAO;CACxC,OAAO,OAAO,MAAM,eAAe,YAAY,OAAO,MAAM,YAAY;AAC1E;;AAGA,SAAgB,kBAAkB,OAAuC;CACvE,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,OAAO,MAAM,SAAS,cAAc,OAAO,MAAM,eAAe;AAClE;;AAGA,SAAgB,cAAc,OAAoC;CAChE,OAAO,2BAA2B,KAAK,KAAK,MAAM,SAAS;AAC7D;AAEA,MAAM,mCAAwC,IAAI,IAAI;CAAC;CAAQ;CAAU;CAAW;AAAW,CAAC;;;;;;AAOhG,SAAgB,iBAAiB,OAAsC;CACrE,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,WAAW,OAAO;CACrC,MAAM,SAAS,MAAM;CACrB,OAAO,OAAO,WAAW,YAAY,iBAAiB,IAAI,MAAM;AAClE;AAEA,MAAM,sCAA2C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAY,CAAC;;;;;;AAOtF,SAAgB,oBAAoB,OAA0C;CAC5E,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,cAAc,OAAO;CACxC,MAAM,SAAS,MAAM;CACrB,IAAI,OAAO,WAAW,YAAY,CAAC,oBAAoB,IAAI,MAAM,GAAG,OAAO;CAC3E,OAAO,OAAO,MAAM,WAAW;AACjC;;;;;;;AAQA,SAAgB,uBAAuB,OAAuC;CAC5E,IAAI,CAAC,2BAA2B,KAAK,GACnC,OAAO;EACL,SAAS;EACT,uBAAO,IAAI,MAAM,iEAAiE;CACpF;CAEF,OAAO;EAAE,SAAS;EAAM,MAAM;CAAM;AACtC"}
@@ -117,10 +117,10 @@ declare namespace StandardJSONSchemaV1 {
117
117
  //#endregion
118
118
  //#region src/schema/types.d.ts
119
119
  /**
120
- * Any Standard Schema implementation, used where fascicle only ever validates.
120
+ * Any Standard Schema implementation, used where Fascicle only ever validates.
121
121
  *
122
122
  * `t` is the validated output type, which is what callers care about; the input
123
- * side stays `unknown` because fascicle validates values arriving from a model,
123
+ * side stays `unknown` because Fascicle validates values arriving from a model,
124
124
  * a resume payload, or stdin, none of which are typed at the boundary.
125
125
  */
126
126
  type AnySchema<t = unknown> = StandardSchemaV1<unknown, t>;
@@ -146,4 +146,4 @@ type SchemaIssue = {
146
146
  };
147
147
  //#endregion
148
148
  export { SchemaIssue as n, ToolSchema as r, AnySchema as t };
149
- //# sourceMappingURL=types-BCtKsxrX.d.ts.map
149
+ //# sourceMappingURL=types-BK0UW28o.d.ts.map
@@ -42,8 +42,13 @@ type RunContext = {
42
42
  readonly streaming: boolean;
43
43
  };
44
44
  type StepFn<i, o> = (input: i, ctx: RunContext) => Promise<o> | o;
45
+ /**
46
+ * Descriptive metadata for a step. `name` is the display channel: it labels
47
+ * trajectory spans and `describe` output, and changing it is always safe
48
+ * because nothing keys off it. The step's `id` stays the identity channel.
49
+ */
45
50
  type StepMetadata = {
46
- readonly display_name?: string;
51
+ readonly name?: string;
47
52
  readonly description?: string;
48
53
  readonly port_labels?: Readonly<{
49
54
  readonly in?: string;
@@ -81,4 +86,4 @@ type StepInput<s> = s extends Step<infer i, unknown> ? i : never;
81
86
  type StepOutput<s> = s extends Step<never, infer o> ? o : unknown;
82
87
  //#endregion
83
88
  export { Step as a, StepMetadata as c, TrajectoryLogger as d, RunContext as i, StepOutput as l, CheckpointStore as n, StepFn as o, CleanupFn as r, StepInput as s, AnyStep as t, TrajectoryEvent as u };
84
- //# sourceMappingURL=types-BqUY6nRX.d.ts.map
89
+ //# sourceMappingURL=types-DBpU27sQ.d.ts.map
@@ -1,5 +1,5 @@
1
- import { d as TrajectoryLogger } from "./types-BqUY6nRX.js";
2
- import { r as ToolSchema } from "./types-BCtKsxrX.js";
1
+ import { d as TrajectoryLogger } from "./types-DBpU27sQ.js";
2
+ import { r as ToolSchema } from "./types-BK0UW28o.js";
3
3
 
4
4
  //#region src/engine/providers/claude_cli/types.d.ts
5
5
  /**
@@ -602,4 +602,4 @@ type Engine = {
602
602
  };
603
603
  //#endregion
604
604
  export { TurnResult as A, ProviderTransport as B, StreamChunk as C, ToolCallRecord as D, ToolApprovalRequest as E, ExternalAgentAdapter as F, default_normalize_usage as H, NativeProviderAdapter as I, ProviderAdapter as L, UserContentPart as M, AiSdkProviderAdapter as N, ToolExecContext as O, EffortTranslation as P, ProviderCapability as R, StepRecord as S, ToolApprovalHandler as T, RawProviderUsage as V, ProviderConfigMap as _, Engine as a, RetryFailureKind as b, FinishReason as c, Message as d, PrepareStepContext as f, PricingTable as g, Pricing as h, EffortLevel as i, UsageTotals as j, TurnRequest as k, GenerateOptions as l, PrepareStepResult as m, AssistantContentPart as n, EngineConfig as o, PrepareStepHook as p, CostBreakdown as r, EngineDefaults as s, AiSdkTelemetrySettings as t, GenerateResult as u, ProviderInit as v, Tool as w, RetryPolicy as x, ResolvedModel as y, ProviderFactory as z };
605
- //# sourceMappingURL=types-CXBB4aIM.d.ts.map
605
+ //# sourceMappingURL=types-DU6cvoA4.d.ts.map
package/dist/ui.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { u as TrajectoryEvent } from "./types-BqUY6nRX.js";
1
+ import { u as TrajectoryEvent } from "./types-DBpU27sQ.js";
2
2
  import { UIMessageChunk } from "ai";
3
3
  import { ServerResponse } from "node:http";
4
4
 
package/dist/ui.js CHANGED
@@ -6,7 +6,7 @@ import { createUIMessageStream, createUIMessageStreamResponse, pipeUIMessageStre
6
6
  * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,
7
7
  * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.
8
8
  * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a
9
- * fascicle flow can back a `useChat` endpoint rendered by AI Elements /
9
+ * Fascicle flow can back a `useChat` endpoint rendered by AI Elements /
10
10
  * Streamdown, with zero bespoke glue.
11
11
  *
12
12
  * It is the outbound inverse of the engine's inbound provider->StreamChunk
package/dist/ui.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui: bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\n/**\n * Create an empty `UiMapperState` for a new stream.\n */\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\n/**\n * Build the UI message chunk id for a step's text block.\n */\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\n/**\n * Build the UI message chunk id for a step's reasoning block.\n */\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\n/**\n * Close the text/reasoning blocks open for one step, returning the\n * `*-end` chunks needed and updating `state` in place.\n *\n * Called on a `step_finish` chunk, so only that step's blocks close; blocks\n * open for other steps are untouched.\n */\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\n/**\n * Close every text/reasoning block still open in `state`, returning the\n * `*-end` chunks needed.\n *\n * Used on stream `finish` and to flush any blocks still open when the\n * underlying event iterable ends.\n */\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\n/**\n * Map a single engine `StreamChunk` to the `UIMessageChunk`s it produces,\n * opening and closing text/reasoning blocks in `state` as needed.\n */\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\n/**\n * Narrow an untyped `TrajectoryEvent['chunk']` payload to a `StreamChunk`\n * when it looks like one (an object with a string `kind`), otherwise\n * return `undefined`.\n */\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\n/**\n * Build the `ReadableStream<UIMessageChunk>` that drives a `run.stream(...)`\n * handle through `to_ui_message_chunks`, used by both the `Response` and\n * Node `ServerResponse` entry points below.\n */\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): void {\n pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;;;;AAKA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;;;;AAKA,SAAS,aAAa,YAA4B;CAChD,OAAO,aAAa;AACtB;;;;;;;;AASA,SAAS,kBAAkB,YAAoB,OAAwC;CACrF,MAAM,QAA0B,CAAC;CACjC,IAAI,MAAM,UAAU,OAAO,UAAU,GACnC,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,IAAI,MAAM,eAAe,OAAO,UAAU,GACxC,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAEpE,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,OAAwC;CACxE,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,cAAc,MAAM,WAC7B,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,KAAK,MAAM,cAAc,MAAM,gBAC7B,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAEpE,MAAM,UAAU,MAAM;CACtB,MAAM,eAAe,MAAM;CAC3B,OAAO;AACT;;;;;AAMA,SAAS,UAAU,OAAoB,OAAwC;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QAAQ;GACX,MAAM,KAAK,QAAQ,MAAM,UAAU;GACnC,MAAM,QAA0B,CAAC;GACjC,IAAI,CAAC,MA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AChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CAExD,IAAI,OADS,QAAQ,IAAI,OAAO,MAClB,MAAM,UAAU,OAAO,KAAA;CAKrC,OAAO;AACT;;;;;AAMA,SAAgB,qBACd,OACA,OACkB;CAClB,IAAI,MAAM,SAAS,eAAe,OAAO,CAAC;CAC1C,MAAM,QAAQ,gBAAgB,MAAM,QAAQ;CAC5C,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,UAAU,OAAO,KAAK;AAC1D;;;;;;AAOA,SAAS,aACP,QACA,SACgC;CAChC,MAAM,WAAW,QAAQ;CACzB,OAAO,sBAAsB;EAC3B,SAAS,OAAO,EAAE,aAAa;GAC7B,MAAM,QAAQ,uBAAuB;GACrC,WAAW,MAAM,SAAS,OAAO,QAC/B,KAAK,MAAM,QAAQ,qBAAqB,OAAO,KAAK,GAAG,OAAO,MAAM,IAAI;GAE1E,KAAK,MAAM,QAAQ,kBAAkB,KAAK,GAAG,OAAO,MAAM,IAAI;GAC9D,MAAM,OAAO;EACf;EACA,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,SAAS,IAAI,CAAC;CACxD,CAAC;AACH;;;;;AAMA,SAAgB,uBACd,QACA,UAA6B,CAAC,GACpB;CACV,OAAO,8BAA8B,EAAE,QAAQ,aAAa,QAAQ,OAAO,EAAE,CAAC;AAChF;;;;;;AAOA,SAAgB,mCACd,QACA,UACA,UAA6B,CAAC,GACxB;CACN,8BAA8B;EAAE;EAAU,QAAQ,aAAa,QAAQ,OAAO;CAAE,CAAC;AACnF"}
1
+ {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui: bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * Fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\n/**\n * Create an empty `UiMapperState` for a new stream.\n */\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\n/**\n * Build the UI message chunk id for a step's text block.\n */\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\n/**\n * Build the UI message chunk id for a step's reasoning block.\n */\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\n/**\n * Close the text/reasoning blocks open for one step, returning the\n * `*-end` chunks needed and updating `state` in place.\n *\n * Called on a `step_finish` chunk, so only that step's blocks close; blocks\n * open for other steps are untouched.\n */\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\n/**\n * Close every text/reasoning block still open in `state`, returning the\n * `*-end` chunks needed.\n *\n * Used on stream `finish` and to flush any blocks still open when the\n * underlying event iterable ends.\n */\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\n/**\n * Map a single engine `StreamChunk` to the `UIMessageChunk`s it produces,\n * opening and closing text/reasoning blocks in `state` as needed.\n */\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\n/**\n * Narrow an untyped `TrajectoryEvent['chunk']` payload to a `StreamChunk`\n * when it looks like one (an object with a string `kind`), otherwise\n * return `undefined`.\n */\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\n/**\n * Build the `ReadableStream<UIMessageChunk>` that drives a `run.stream(...)`\n * handle through `to_ui_message_chunks`, used by both the `Response` and\n * Node `ServerResponse` entry points below.\n */\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): void {\n pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;;;;AAKA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;;;;AAKA,SAAS,aAAa,YAA4B;CAChD,OAAO,aAAa;AACtB;;;;;;;;AASA,SAAS,kBAAkB,YAAoB,OAAwC;CACrF,MAAM,QAA0B,CAAC;CACjC,IAAI,MAAM,UAAU,OAAO,UAAU,GACnC,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,IAAI,MAAM,eAAe,OAAO,UAAU,GACxC,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAEpE,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,OAAwC;CACxE,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,cAAc,MAAM,WAC7B,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ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A,UAA6B,CAAC,GACxB;CACN,8BAA8B;EAAE;EAAU,QAAQ,aAAa,QAAQ,OAAO;CAAE,CAAC;AACnF"}
package/dist/viewer.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ParsedTrajectoryEvent } from "./trajectory-cSLNlHzh.js";
1
+ import { a as ParsedTrajectoryEvent } from "./trajectory-ByoOQZ6T.js";
2
2
 
3
3
  //#region src/viewer/start_viewer.d.ts
4
4
  /**
@@ -45,7 +45,7 @@ type Broadcaster = {
45
45
  readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[];
46
46
  readonly size: () => number;
47
47
  };
48
- type BroadcasterOptions = {
48
+ type BroadcasterConfig = {
49
49
  readonly buffer: number;
50
50
  readonly on_subscriber_error?: (err: unknown) => void;
51
51
  };
@@ -58,10 +58,10 @@ type BroadcasterOptions = {
58
58
  * that throws is unsubscribed, and the `on_subscriber_error` callback fires
59
59
  * once with the captured error so the server can log it.
60
60
  */
61
- declare function create_broadcaster(options: BroadcasterOptions): Broadcaster;
61
+ declare function create_broadcaster(config: BroadcasterConfig): Broadcaster;
62
62
  //#endregion
63
63
  //#region src/viewer/server.d.ts
64
- type ServerOptions = {
64
+ type ServerConfig = {
65
65
  readonly broadcaster: Broadcaster;
66
66
  readonly host: string;
67
67
  readonly port: number;
@@ -78,10 +78,10 @@ type ViewerServer = {
78
78
  * single request handler and resolves with the bound URL and a `close`
79
79
  * that shuts the socket down.
80
80
  */
81
- declare function start_server(options: ServerOptions): Promise<ViewerServer>;
81
+ declare function start_server(config: ServerConfig): Promise<ViewerServer>;
82
82
  //#endregion
83
83
  //#region src/viewer/tail.d.ts
84
- type TailOptions = {
84
+ type TailConfig = {
85
85
  readonly path: string;
86
86
  readonly on_event: (event: ParsedTrajectoryEvent) => void;
87
87
  readonly on_parse_error?: (err: unknown, line: string) => void;
@@ -100,7 +100,7 @@ type Tail = {
100
100
  * flight absorbs any events that fire while it runs instead of starting a
101
101
  * second concurrent read.
102
102
  */
103
- declare function start_tail(options: TailOptions): Tail;
103
+ declare function start_tail(config: TailConfig): Tail;
104
104
  //#endregion
105
105
  //#region src/viewer/cli.d.ts
106
106
  /**
@@ -113,5 +113,5 @@ declare function start_tail(options: TailOptions): Tail;
113
113
  */
114
114
  declare function run_viewer_cli(argv: readonly string[]): Promise<void>;
115
115
  //#endregion
116
- export { type BroadcastEvent, type Broadcaster, type BroadcasterOptions, type ServerOptions, type StartViewerOptions, type Subscriber, type Tail, type TailOptions, type ViewerHandle, type ViewerServer, create_broadcaster, run_viewer_cli, start_server, start_tail, start_viewer };
116
+ export { type BroadcastEvent, type Broadcaster, type BroadcasterConfig, type ServerConfig, type StartViewerOptions, type Subscriber, type Tail, type TailConfig, type ViewerHandle, type ViewerServer, create_broadcaster, run_viewer_cli, start_server, start_tail, start_viewer };
117
117
  //# sourceMappingURL=viewer.d.ts.map
package/dist/viewer.js CHANGED
@@ -1,4 +1,5 @@
1
- import { s as parse_trajectory_event } from "./core-DDRhHu5P.js";
1
+ import "./core-DdJEhyQc.js";
2
+ import { s as parse_trajectory_event } from "./trajectory-D1eq9eue.js";
2
3
  import { open, stat } from "node:fs/promises";
3
4
  import { dirname, resolve } from "node:path";
4
5
  import { createReadStream, existsSync, statSync, watch } from "node:fs";
@@ -16,8 +17,8 @@ import { parseArgs } from "node:util";
16
17
  * that throws is unsubscribed, and the `on_subscriber_error` callback fires
17
18
  * once with the captured error so the server can log it.
18
19
  */
19
- function create_broadcaster(options) {
20
- const max = Math.max(1, options.buffer | 0);
20
+ function create_broadcaster(config) {
21
+ const max = Math.max(1, config.buffer | 0);
21
22
  const ring = [];
22
23
  const subscribers = /* @__PURE__ */ new Set();
23
24
  let next_id = 1;
@@ -32,7 +33,7 @@ function create_broadcaster(options) {
32
33
  fn(entry);
33
34
  } catch (err) {
34
35
  subscribers.delete(fn);
35
- if (options.on_subscriber_error) options.on_subscriber_error(err);
36
+ if (config.on_subscriber_error) config.on_subscriber_error(err);
36
37
  }
37
38
  return entry;
38
39
  };
@@ -78,8 +79,8 @@ const STATIC_HTML = resolve(dirname(fileURLToPath(import.meta.url)), "static", "
78
79
  * single request handler and resolves with the bound URL and a `close`
79
80
  * that shuts the socket down.
80
81
  */
81
- function start_server(options) {
82
- const { broadcaster, host, port, on_parse_error } = options;
82
+ function start_server(config) {
83
+ const { broadcaster, host, port, on_parse_error } = config;
83
84
  const handler = (req, res) => {
84
85
  const route = resolve_route(req, host, port);
85
86
  if (route === "GET /" || route === "GET /index.html") {
@@ -306,8 +307,8 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
306
307
  * flight absorbs any events that fire while it runs instead of starting a
307
308
  * second concurrent read.
308
309
  */
309
- function start_tail(options) {
310
- const { path, on_event, on_parse_error, on_io_error } = options;
310
+ function start_tail(config) {
311
+ const { path, on_event, on_parse_error, on_io_error } = config;
311
312
  let offset = 0;
312
313
  let buffer = "";
313
314
  let busy = false;
@@ -474,7 +475,7 @@ function wrap_handle(server, tail, host) {
474
475
  /**
475
476
  * fascicle-viewer CLI.
476
477
  *
477
- * fascicle-viewer <path> # tail a JSONL file (primary)
478
+ * fascicle-viewer <path> # tail a JSONL file (primary)
478
479
  * fascicle-viewer --listen # accept HTTP push only
479
480
  * fascicle-viewer <path> --listen # both producers feed the same broadcaster
480
481
  *
@@ -495,7 +496,7 @@ Usage:
495
496
  Options:
496
497
  --port <n> port (default 4242)
497
498
  --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)
498
- --buffer <n> ring-buffer size (default 1000)
499
+ --buffer <n> ring-buffer size (default 1000)
499
500
  --no-open do not open the browser
500
501
  --help show this message
501
502
  `;
@@ -549,11 +550,11 @@ function parse(argv) {
549
550
  const port = Number.parseInt(port_raw, 10);
550
551
  const buffer = Number.parseInt(buffer_raw, 10);
551
552
  if (!Number.isFinite(port) || port <= 0) {
552
- process.stderr.write(`invalid --port: ${port_raw}\n`);
553
+ process.stderr.write(`fascicle-viewer: invalid --port '${port_raw}': expected a positive integer\n`);
553
554
  process.exit(2);
554
555
  }
555
556
  if (!Number.isFinite(buffer) || buffer <= 0) {
556
- process.stderr.write(`invalid --buffer: ${buffer_raw}\n`);
557
+ process.stderr.write(`fascicle-viewer: invalid --buffer '${buffer_raw}': expected a positive integer\n`);
557
558
  process.exit(2);
558
559
  }
559
560
  const path = positionals[0];
@@ -621,9 +622,9 @@ async function run_viewer_cli(argv) {
621
622
  process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\n`);
622
623
  }
623
624
  });
624
- if (args.path !== void 0) process.stderr.write(`watching ${args.path}\n`);
625
- if (args.listen || args.path === void 0) process.stderr.write(`listening for HTTP push on ${handle.url}/api/ingest\n`);
626
- process.stderr.write(`viewer at ${handle.url}\n`);
625
+ if (args.path !== void 0) process.stderr.write(`fascicle-viewer: watching ${args.path}\n`);
626
+ if (args.listen || args.path === void 0) process.stderr.write(`fascicle-viewer: listening for HTTP push on ${handle.url}/api/ingest\n`);
627
+ process.stderr.write(`fascicle-viewer: viewer at ${handle.url}\n`);
627
628
  if (args.open) open_browser(handle.url);
628
629
  const shutdown = async () => {
629
630
  process.stderr.write("\nfascicle-viewer: shutting down\n");
@@ -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 BroadcasterOptions = {\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(options: BroadcasterOptions): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, options.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 (options.on_subscriber_error) options.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 routes, SSE fan-out, NDJSON ingest.\n *\n * GET / -> static viewer.html\n * GET /api/events -> text/event-stream replaying the ring buffer\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 *\n * The server owns nothing but the socket. The broadcaster owns the event\n * history; the static html lives on disk. SSE clients reconnect with\n * `Last-Event-ID` and the server replays anything past their cursor from\n * the ring buffer; older events are gone (bounded memory by design).\n */\n\nimport { createReadStream, statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, resolve } 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))\nconst STATIC_HTML = resolve(HERE, 'static', 'viewer.html')\n\nexport type ServerOptions = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\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 five routes (static HTML, health, snapshot, SSE, ingest) to a\n * single request handler and resolves with the bound URL and a `close`\n * that shuts the socket down.\n */\nexport function start_server(options: ServerOptions): Promise<ViewerServer> {\n const { broadcaster, host, port, on_parse_error } = options\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /' || route === 'GET /index.html') {\n serve_static_html(res)\n return\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/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 res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify({ error: 'not_found', route }))\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (e.g. 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 // `address().port` is the port actually bound. It only differs from\n // the requested `port` when the caller passed 0 and asked the OS to\n // pick a free port.\n const addr = http_server.address()\n const bound_port =\n addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : port\n const url = `http://${host}:${bound_port}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Falls back to the server's own `host`/`port` when the request has no\n * `Host` header, so a malformed or missing header never throws inside\n * `new URL`.\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 url = new URL(req.url ?? '/', `http://${req.headers.host ?? `${host}:${port}`}`)\n return `${req.method ?? 'GET'} ${url.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 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 * Streams the bundled `viewer.html` as the response body.\n */\nfunction serve_static_html(res: ServerResponse): void {\n let size: number\n try {\n // Stat first so a missing file produces a clean 500 response instead\n // of a stream error after headers have already been sent.\n size = statSync(STATIC_HTML).size\n } catch {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer.html missing')\n return\n }\n res.statusCode = 200\n res.setHeader('content-type', 'text/html; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(size))\n createReadStream(STATIC_HTML).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 `Last-Event-ID` cursor,\n * subscribes it to the broadcaster for new events, and keeps the\n * connection alive with a periodic heartbeat comment.\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 // 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 last_event_id = parse_last_event_id(req.headers['last-event-id'])\n for (const entry of broadcaster.snapshot_after(last_event_id)) {\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 const unsubscribe = broadcaster.subscribe((entry) => {\n 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 * 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 = { STATIC_HTML, SSE_HEARTBEAT_MS, parse_last_event_id }\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 TailOptions = {\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(options: TailOptions): Tail {\n const { path, on_event, on_parse_error, on_io_error } = options\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 ...(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(`invalid --port: ${port_raw}\\n`)\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(`invalid --buffer: ${buffer_raw}\\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(`watching ${args.path}\\n`)\n if (args.listen || args.path === undefined) process.stderr.write(`listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`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 (e.g. `tsx packages/viewer/src/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,SAA0C;CAG3E,MAAM,MAAM,KAAK,IAAI,GAAG,QAAQ,SAAS,CAAC;CAC1C,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,M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G;CAC3E,IAAI,KAAK,UAAU,KAAK,SAAS,KAAA,GAAW,QAAQ,OAAO,MAAM,8BAA8B,OAAO,IAAI,cAAc;CACxH,QAAQ,OAAO,MAAM,aAAa,OAAO,IAAI,GAAG;CAEhD,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,OAAO,KAAK,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":["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 routes, SSE fan-out, NDJSON ingest.\n *\n * GET / -> static viewer.html\n * GET /api/events -> text/event-stream replaying the ring buffer\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 *\n * The server owns nothing but the socket. The broadcaster owns the event\n * history; the static html lives on disk. SSE clients reconnect with\n * `Last-Event-ID` and the server replays anything past their cursor from\n * the ring buffer; older events are gone (bounded memory by design).\n */\n\nimport { createReadStream, statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, resolve } 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))\nconst STATIC_HTML = resolve(HERE, 'static', 'viewer.html')\n\nexport type ServerConfig = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\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 five routes (static HTML, health, snapshot, SSE, ingest) to a\n * single request handler and resolves with the bound URL and a `close`\n * that shuts the socket down.\n */\nexport function start_server(config: ServerConfig): Promise<ViewerServer> {\n const { broadcaster, host, port, 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 /' || route === 'GET /index.html') {\n serve_static_html(res)\n return\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/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 res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify({ error: 'not_found', 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 // `address().port` is the port actually bound. It only differs from\n // the requested `port` when the caller passed 0 and asked the OS to\n // pick a free port.\n const addr = http_server.address()\n const bound_port =\n addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : port\n const url = `http://${host}:${bound_port}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Falls back to the server's own `host`/`port` when the request has no\n * `Host` header, so a malformed or missing header never throws inside\n * `new URL`.\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 url = new URL(req.url ?? '/', `http://${req.headers.host ?? `${host}:${port}`}`)\n return `${req.method ?? 'GET'} ${url.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 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 * Streams the bundled `viewer.html` as the response body.\n */\nfunction serve_static_html(res: ServerResponse): void {\n let size: number\n try {\n // Stat first so a missing file produces a clean 500 response instead\n // of a stream error after headers have already been sent.\n size = statSync(STATIC_HTML).size\n } catch {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer.html missing')\n return\n }\n res.statusCode = 200\n res.setHeader('content-type', 'text/html; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(size))\n createReadStream(STATIC_HTML).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 `Last-Event-ID` cursor,\n * subscribes it to the broadcaster for new events, and keeps the\n * connection alive with a periodic heartbeat comment.\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 // 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 last_event_id = parse_last_event_id(req.headers['last-event-id'])\n for (const entry of broadcaster.snapshot_after(last_event_id)) {\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 const unsubscribe = broadcaster.subscribe((entry) => {\n 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 * 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 = { STATIC_HTML, SSE_HEARTBEAT_MS, parse_last_event_id }\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 ...(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,UAA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AE,GAChF;EACF;EACA,cAAc,QAAQ;GACpB,QAAQ,OAAO,MAAM,8BAA8B,eAAe,GAAG,EAAE,GAAG;EAC5E;CACF,CAAC;CAED,IAAI,KAAK,SAAS,KAAA,GAAW,QAAQ,OAAO,MAAM,6BAA6B,KAAK,KAAK,GAAG;CAC5F,IAAI,KAAK,UAAU,KAAK,SAAS,KAAA,GAAW,QAAQ,OAAO,MAAM,+CAA+C,OAAO,IAAI,cAAc;CACzI,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,OAAO,KAAK,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.12.1",
3
+ "version": "0.12.3",
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",
@@ -132,7 +132,7 @@
132
132
  "check:fix": "pnpm exec oxlint --type-aware --fix && node scripts/strip-semicolons.mjs && pnpm exec fallow fix",
133
133
  "check:mutation": "stryker run",
134
134
  "check:publish": "checkride --only publint,attw,pack,smoke,snippets",
135
- "check:security": "pnpm audit --audit-level=high",
135
+ "check:security": "checkride --only security",
136
136
  "prepublishOnly": "pnpm check && pnpm build && pnpm check:publish",
137
137
  "test": "vitest run",
138
138
  "test:watch": "vitest",
@@ -198,19 +198,20 @@
198
198
  "devDependencies": {
199
199
  "@arethetypeswrong/cli": "0.18.4",
200
200
  "@ast-grep/cli": "0.44.1",
201
- "@modelcontextprotocol/sdk": "1.29.0",
201
+ "@modelcontextprotocol/sdk": "1.30.0",
202
202
  "@opentelemetry/sdk-trace-base": "2.9.0",
203
203
  "@standard-schema/spec": "1.1.0",
204
204
  "@stryker-mutator/core": "9.6.1",
205
205
  "@stryker-mutator/vitest-runner": "9.6.1",
206
206
  "@types/node": "26.1.0",
207
207
  "@vitest/coverage-v8": "4.1.10",
208
+ "@vvago/vale": "3.17.0",
208
209
  "ai": "7.0.17",
209
210
  "arktype": "2.2.3",
210
211
  "checkride": "0.12.1",
211
212
  "cspell": "10.0.1",
212
213
  "fallow": "3.6.0",
213
- "markdownlint-cli2": "0.23.0",
214
+ "markdownlint-cli2": "0.23.2",
214
215
  "oxlint": "1.73.0",
215
216
  "oxlint-tsgolint": "0.24.0",
216
217
  "publint": "0.3.21",