fascicle 0.3.3 → 0.3.8

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.
package/dist/index.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { z } from "zod";
3
- import { readFile, readdir } from "node:fs/promises";
4
- import { join } from "node:path";
3
+ import { mkdir, open, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { appendFileSync, createReadStream, existsSync, mkdirSync, statSync, watch } from "node:fs";
5
6
  import { spawn } from "node:child_process";
6
7
  import { generateText, stepCountIs, streamText, tool } from "ai";
8
+ import { createServer } from "node:http";
9
+ import { fileURLToPath } from "node:url";
10
+ import { parseArgs } from "node:util";
7
11
  //#region packages/core/src/flow-schema.json
8
12
  var flow_schema_default = {
9
13
  $schema: "https://json-schema.org/draft/2020-12/schema",
@@ -1945,7 +1949,7 @@ const trajectory_event_schema = z.union([
1945
1949
  ]);
1946
1950
  //#endregion
1947
1951
  //#region packages/core/src/version.ts
1948
- const version = "0.3.3";
1952
+ const version = "0.3.8";
1949
1953
  //#endregion
1950
1954
  //#region packages/core/src/index.ts
1951
1955
  /**
@@ -1953,7 +1957,9 @@ const version = "0.3.3";
1953
1957
  *
1954
1958
  * Side-effect imports ensure every composer registers itself with the runner
1955
1959
  * at module load. Importing anything from `@repo/core` populates the
1956
- * dispatch table with all 16 primitives.
1960
+ * dispatch table with the core primitives. Built-in composites
1961
+ * (adversarial, ensemble, tournament, consensus) live in @repo/composites
1962
+ * and surface through the umbrella package.
1957
1963
  */
1958
1964
  const flow_schema = flow_schema_default;
1959
1965
  //#endregion
@@ -2592,8 +2598,613 @@ function tournament(config) {
2592
2598
  return compose(config.name ?? "tournament", inner);
2593
2599
  }
2594
2600
  //#endregion
2601
+ //#region packages/observability/src/filesystem.ts
2602
+ /**
2603
+ * Filesystem JSONL trajectory logger.
2604
+ *
2605
+ * Appends one JSON object per line to a configured output file. `start_span`
2606
+ * and `end_span` each emit a line; `record` emits a line with the event as
2607
+ * written. Hierarchical span ids are tracked via an in-memory stack: when
2608
+ * `start_span` fires, the innermost still-open span's id is attached as
2609
+ * `parent_span_id` on the new span's record. This is best-effort for
2610
+ * concurrent children (two siblings spawned from the same parent will see
2611
+ * whichever opened most recently as their parent until proper async-context
2612
+ * propagation is wired). Two concurrent `run(...)` calls that pass distinct
2613
+ * logger instances (constructed with distinct `output_path`s) share nothing.
2614
+ *
2615
+ * Paths are accepted at construction; the logger never reads `process.env`.
2616
+ */
2617
+ function filesystem_logger(options) {
2618
+ const { output_path } = options;
2619
+ mkdirSync(dirname(output_path), { recursive: true });
2620
+ const stack = [];
2621
+ const write_line = (event) => {
2622
+ appendFileSync(output_path, `${JSON.stringify(event)}\n`);
2623
+ };
2624
+ const start_span = (name, meta) => {
2625
+ const span_id = `${name}:${randomUUID().slice(0, 8)}`;
2626
+ const parent_span_id = stack.length > 0 ? stack[stack.length - 1] : void 0;
2627
+ const event = {
2628
+ kind: "span_start",
2629
+ span_id,
2630
+ name,
2631
+ ...meta
2632
+ };
2633
+ if (parent_span_id !== void 0) event["parent_span_id"] = parent_span_id;
2634
+ write_line(event);
2635
+ stack.push(span_id);
2636
+ return span_id;
2637
+ };
2638
+ const end_span = (id, meta) => {
2639
+ write_line({
2640
+ kind: "span_end",
2641
+ span_id: id,
2642
+ ...meta
2643
+ });
2644
+ const idx = stack.lastIndexOf(id);
2645
+ if (idx !== -1) stack.splice(idx, 1);
2646
+ };
2647
+ const record = (event) => {
2648
+ write_line({ ...event });
2649
+ };
2650
+ return {
2651
+ record,
2652
+ start_span,
2653
+ end_span
2654
+ };
2655
+ }
2656
+ //#endregion
2657
+ //#region packages/observability/src/http.ts
2658
+ /**
2659
+ * HTTP push trajectory logger.
2660
+ *
2661
+ * Conforms to `TrajectoryLogger`. POSTs each event as a single line of
2662
+ * newline-delimited JSON to a configured URL. Pairs naturally with the
2663
+ * fascicle viewer's `/api/ingest` endpoint, but is a generic adapter — the
2664
+ * receiver can be anything that accepts NDJSON over HTTP.
2665
+ *
2666
+ * Failure policy: drop on transport error and invoke the optional `on_error`
2667
+ * callback. Never throws, never blocks the user's flow on a dev tool being
2668
+ * up. The flow always wins; the viewer is best-effort.
2669
+ *
2670
+ * Hierarchical span ids are tracked in-process, mirroring `filesystem_logger`
2671
+ * so the wire format is identical.
2672
+ */
2673
+ const default_fetch = async (url, init) => {
2674
+ const res = await fetch(url, init);
2675
+ return {
2676
+ ok: res.ok,
2677
+ status: res.status
2678
+ };
2679
+ };
2680
+ function http_logger(options) {
2681
+ const { url, on_error } = options;
2682
+ const send = options.fetch ?? default_fetch;
2683
+ const stack = [];
2684
+ const post = (event) => {
2685
+ send(url, {
2686
+ method: "POST",
2687
+ headers: { "content-type": "application/x-ndjson" },
2688
+ body: `${JSON.stringify(event)}\n`
2689
+ }).then((res) => {
2690
+ if (!res.ok && on_error) on_error(/* @__PURE__ */ new Error(`http_logger: POST ${url} -> ${res.status}`));
2691
+ }).catch((err) => {
2692
+ if (on_error) on_error(err);
2693
+ });
2694
+ };
2695
+ const start_span = (name, meta) => {
2696
+ const span_id = `${name}:${randomUUID().slice(0, 8)}`;
2697
+ const parent_span_id = stack.length > 0 ? stack[stack.length - 1] : void 0;
2698
+ const event = {
2699
+ kind: "span_start",
2700
+ span_id,
2701
+ name,
2702
+ ...meta
2703
+ };
2704
+ if (parent_span_id !== void 0) event["parent_span_id"] = parent_span_id;
2705
+ post(event);
2706
+ stack.push(span_id);
2707
+ return span_id;
2708
+ };
2709
+ const end_span = (id, meta) => {
2710
+ post({
2711
+ kind: "span_end",
2712
+ span_id: id,
2713
+ ...meta
2714
+ });
2715
+ const idx = stack.lastIndexOf(id);
2716
+ if (idx !== -1) stack.splice(idx, 1);
2717
+ };
2718
+ const record = (event) => {
2719
+ post({ ...event });
2720
+ };
2721
+ return {
2722
+ record,
2723
+ start_span,
2724
+ end_span
2725
+ };
2726
+ }
2727
+ //#endregion
2728
+ //#region packages/observability/src/tee.ts
2729
+ function tee_logger(...loggers) {
2730
+ if (loggers.length === 0) throw new Error("tee_logger: at least one logger required");
2731
+ const id_map = /* @__PURE__ */ new Map();
2732
+ const safe_each = (fn) => {
2733
+ for (let i = 0; i < loggers.length; i += 1) {
2734
+ const l = loggers[i];
2735
+ if (l === void 0) continue;
2736
+ try {
2737
+ fn(l, i);
2738
+ } catch {}
2739
+ }
2740
+ };
2741
+ return {
2742
+ record: (event) => {
2743
+ safe_each((l) => l.record(event));
2744
+ },
2745
+ start_span: (name, meta) => {
2746
+ const ids = [];
2747
+ safe_each((l) => {
2748
+ ids.push(l.start_span(name, meta));
2749
+ });
2750
+ const canonical = ids[0] ?? `${name}:tee`;
2751
+ if (loggers.length > 1) id_map.set(canonical, ids);
2752
+ return canonical;
2753
+ },
2754
+ end_span: (id, meta) => {
2755
+ const ids = id_map.get(id);
2756
+ if (ids === void 0) {
2757
+ safe_each((l) => l.end_span(id, meta));
2758
+ return;
2759
+ }
2760
+ id_map.delete(id);
2761
+ safe_each((l, idx) => l.end_span(ids[idx] ?? id, meta));
2762
+ }
2763
+ };
2764
+ }
2765
+ //#endregion
2766
+ //#region packages/composites/src/bench.ts
2767
+ /**
2768
+ * bench: run a flow against a fixture set, score each result, return a report.
2769
+ *
2770
+ * Online counterpart to `learn`: where `learn` reflects on past trajectories
2771
+ * after the fact, `bench` runs the flow live against fresh `cases`, judges
2772
+ * each output, and produces a `BenchReport` you can compare against a
2773
+ * committed baseline via `regression_compare`.
2774
+ *
2775
+ * Each case becomes one `run(flow, case.input, ...)`. Per-case observability:
2776
+ * - `trajectory_dir` writes `${dir}/${case.id}.jsonl` via filesystem_logger
2777
+ * - `live_url` POSTs each event via http_logger to a viewer's /api/ingest
2778
+ * - both can be combined; bench tees them with an internal cost tracker
2779
+ *
2780
+ * Cost is tracked per-case in-process by intercepting `kind: 'cost'` events
2781
+ * on the trajectory pipeline. The cost number matches what would be on disk
2782
+ * even when no trajectory_dir is set.
2783
+ *
2784
+ * Judges run as Steps after each case, with the same trajectory logger so
2785
+ * judge spans land in the case's trajectory file (or push). A judge that
2786
+ * throws or returns undefined abstains: the entry is omitted from
2787
+ * `case.scores` and the case does not contribute to that judge's mean.
2788
+ */
2789
+ async function bench(flow, cases, judges, options = {}) {
2790
+ const run_id = options.run_id ?? `bench-${String(Date.now())}-${random_suffix()}`;
2791
+ const flow_name = describe_flow_name(flow);
2792
+ const concurrency = resolve_concurrency(options.concurrency, cases.length);
2793
+ const install_signal_handlers = options.install_signal_handlers ?? false;
2794
+ if (options.trajectory_dir !== void 0) await mkdir(options.trajectory_dir, { recursive: true });
2795
+ const judge_entries = Object.entries(judges);
2796
+ const run_one = async (bc) => {
2797
+ const trajectory_path = options.trajectory_dir === void 0 ? void 0 : join(options.trajectory_dir, `${bc.id}.jsonl`);
2798
+ const sinks = [];
2799
+ if (trajectory_path !== void 0) sinks.push(filesystem_logger({ output_path: trajectory_path }));
2800
+ if (options.live_url !== void 0) sinks.push(http_logger({ url: options.live_url }));
2801
+ const cost_tracker = create_cost_tracker();
2802
+ const case_logger = sinks.length === 0 ? cost_tracker.logger : tee_logger(...sinks, cost_tracker.logger);
2803
+ const start = Date.now();
2804
+ let output;
2805
+ let error;
2806
+ let ok = false;
2807
+ try {
2808
+ output = await run(flow, bc.input, {
2809
+ trajectory: case_logger,
2810
+ install_signal_handlers
2811
+ });
2812
+ ok = true;
2813
+ } catch (err) {
2814
+ error = err instanceof Error ? err.message : String(err);
2815
+ ok = false;
2816
+ }
2817
+ const scores = {};
2818
+ if (ok && output !== void 0) {
2819
+ const judge_input = bc.meta === void 0 ? {
2820
+ input: bc.input,
2821
+ output
2822
+ } : {
2823
+ input: bc.input,
2824
+ output,
2825
+ meta: bc.meta
2826
+ };
2827
+ for (const [name, judge] of judge_entries) {
2828
+ let raw;
2829
+ try {
2830
+ raw = await run(judge, judge_input, {
2831
+ trajectory: case_logger,
2832
+ install_signal_handlers
2833
+ });
2834
+ } catch {
2835
+ continue;
2836
+ }
2837
+ const normalized = normalize_score(raw);
2838
+ if (normalized === void 0) continue;
2839
+ scores[name] = normalized;
2840
+ }
2841
+ }
2842
+ const duration_ms = Date.now() - start;
2843
+ const result = {
2844
+ case_id: bc.id,
2845
+ ok,
2846
+ ...output !== void 0 ? { output } : {},
2847
+ ...error !== void 0 ? { error } : {},
2848
+ scores,
2849
+ duration_ms,
2850
+ cost_usd: cost_tracker.total(),
2851
+ ...trajectory_path !== void 0 ? { trajectory_path } : {}
2852
+ };
2853
+ if (options.on_case) options.on_case(result);
2854
+ return result;
2855
+ };
2856
+ const cases_out = await run_with_concurrency(cases, concurrency, run_one);
2857
+ return {
2858
+ flow_name,
2859
+ run_id,
2860
+ cases: cases_out,
2861
+ summary: summarize(cases_out, judge_entries.map(([n]) => n))
2862
+ };
2863
+ }
2864
+ function summarize(cases, judge_names) {
2865
+ const total_duration_ms = cases.reduce((acc, c) => acc + c.duration_ms, 0);
2866
+ const total_cost_usd = cases.reduce((acc, c) => acc + c.cost_usd, 0);
2867
+ const ok_count = cases.filter((c) => c.ok).length;
2868
+ const pass_rate = cases.length === 0 ? 0 : ok_count / cases.length;
2869
+ const mean_cost_usd = cases.length === 0 ? 0 : total_cost_usd / cases.length;
2870
+ const mean_scores = {};
2871
+ for (const name of judge_names) {
2872
+ let sum = 0;
2873
+ let count = 0;
2874
+ for (const c of cases) {
2875
+ const n = score_value_of(c.scores[name]);
2876
+ if (n === void 0) continue;
2877
+ sum += n;
2878
+ count += 1;
2879
+ }
2880
+ if (count > 0) mean_scores[name] = sum / count;
2881
+ }
2882
+ return {
2883
+ pass_rate,
2884
+ mean_scores,
2885
+ total_duration_ms,
2886
+ total_cost_usd,
2887
+ mean_cost_usd
2888
+ };
2889
+ }
2890
+ function normalize_score(raw) {
2891
+ if (raw === void 0 || raw === null) return void 0;
2892
+ if (typeof raw === "number") return Number.isFinite(raw) ? { score: raw } : void 0;
2893
+ if (typeof raw === "object" && "score" in raw) {
2894
+ const r = raw;
2895
+ if (typeof r.score !== "number" || !Number.isFinite(r.score)) return void 0;
2896
+ if (r.reason !== void 0 && typeof r.reason !== "string") return { score: r.score };
2897
+ return r.reason === void 0 ? { score: r.score } : {
2898
+ score: r.score,
2899
+ reason: r.reason
2900
+ };
2901
+ }
2902
+ }
2903
+ function score_value_of(s) {
2904
+ if (s === void 0 || s === null) return void 0;
2905
+ if (typeof s === "number") return Number.isFinite(s) ? s : void 0;
2906
+ if (typeof s === "object" && "score" in s) {
2907
+ const raw = s["score"];
2908
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : void 0;
2909
+ }
2910
+ }
2911
+ function create_cost_tracker() {
2912
+ let total = 0;
2913
+ return {
2914
+ total: () => total,
2915
+ logger: {
2916
+ record: (event) => {
2917
+ if (event.kind !== "cost") return;
2918
+ const value = event["total_usd"];
2919
+ if (typeof value === "number" && Number.isFinite(value)) total += value;
2920
+ },
2921
+ start_span: (name) => `cost-tracker:${name}`,
2922
+ end_span: () => {}
2923
+ }
2924
+ };
2925
+ }
2926
+ async function run_with_concurrency(items, limit, fn) {
2927
+ if (items.length === 0) return [];
2928
+ if (limit >= items.length) return Promise.all(items.map((it) => fn(it)));
2929
+ const results = Array.from({ length: items.length });
2930
+ let next = 0;
2931
+ const worker = async () => {
2932
+ while (true) {
2933
+ const idx = next;
2934
+ next += 1;
2935
+ if (idx >= items.length) return;
2936
+ const item = items[idx];
2937
+ if (item === void 0) continue;
2938
+ results[idx] = await fn(item);
2939
+ }
2940
+ };
2941
+ const workers = [];
2942
+ for (let i = 0; i < limit; i += 1) workers.push(worker());
2943
+ await Promise.all(workers);
2944
+ return results;
2945
+ }
2946
+ function resolve_concurrency(value, n_cases) {
2947
+ if (value === void 0) return Math.max(1, n_cases);
2948
+ if (!Number.isFinite(value) || value <= 0) return Math.max(1, n_cases);
2949
+ return Math.max(1, Math.floor(value));
2950
+ }
2951
+ function describe_flow_name(flow) {
2952
+ const display = flow.config?.["display_name"];
2953
+ if (typeof display === "string" && display.length > 0) return display;
2954
+ return flow.id ?? flow.kind ?? "flow";
2955
+ }
2956
+ function random_suffix() {
2957
+ return Math.random().toString(36).slice(2, 8);
2958
+ }
2959
+ //#endregion
2960
+ //#region packages/composites/src/judges.ts
2961
+ /**
2962
+ * Stock judges for `bench`.
2963
+ *
2964
+ * A `Judge<I, O, S>` is a `Step<{ input, output, meta }, S>` — i.e. just a
2965
+ * step that scores a flow's input/output/metadata triple. Returning
2966
+ * `undefined` (or throwing) means the judge abstains; bench records the
2967
+ * absence as a missing key in `case.scores` and excludes the case from that
2968
+ * judge's `mean_scores` denominator.
2969
+ *
2970
+ * judge_equals — strict equality vs. `meta.expected`
2971
+ * judge_with — wrap a user-supplied scoring function
2972
+ * judge_llm — prompt a model + parse the rubric score out of the reply
2973
+ *
2974
+ * `judge_llm` is engine-agnostic: callers pass their already-configured
2975
+ * model_call step (Step<string, string>), which keeps composites decoupled
2976
+ * from @repo/engine. The user-facing wiring lives in their own code.
2977
+ */
2978
+ function is_record(v) {
2979
+ return v !== null && typeof v === "object" && !Array.isArray(v);
2980
+ }
2981
+ function deep_equal(a, b) {
2982
+ if (a === b) return true;
2983
+ if (a === null || b === null) return false;
2984
+ if (typeof a !== typeof b) return false;
2985
+ if (typeof a !== "object") return false;
2986
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
2987
+ if (Array.isArray(a) && Array.isArray(b)) {
2988
+ if (a.length !== b.length) return false;
2989
+ for (let i = 0; i < a.length; i += 1) if (!deep_equal(a[i], b[i])) return false;
2990
+ return true;
2991
+ }
2992
+ if (!is_record(a) || !is_record(b)) return false;
2993
+ const ak = Object.keys(a).toSorted();
2994
+ const bk = Object.keys(b).toSorted();
2995
+ if (ak.length !== bk.length) return false;
2996
+ for (let i = 0; i < ak.length; i += 1) {
2997
+ const ka = ak[i];
2998
+ const kb = bk[i];
2999
+ if (ka === void 0 || kb === void 0 || ka !== kb) return false;
3000
+ if (!deep_equal(a[ka], b[kb])) return false;
3001
+ }
3002
+ return true;
3003
+ }
3004
+ function judge_equals() {
3005
+ return step("judge_equals", (args) => {
3006
+ if (args.meta === void 0) return void 0;
3007
+ if (!("expected" in args.meta)) return void 0;
3008
+ const expected = args.meta["expected"];
3009
+ const matches = deep_equal(args.output, expected);
3010
+ return {
3011
+ score: matches ? 1 : 0,
3012
+ reason: matches ? "match" : "mismatch"
3013
+ };
3014
+ });
3015
+ }
3016
+ function judge_with(fn) {
3017
+ return step("judge_with", async (args) => {
3018
+ return normalize_score(await fn(args));
3019
+ });
3020
+ }
3021
+ function judge_llm(config) {
3022
+ const scale = config.scale ?? {
3023
+ min: 0,
3024
+ max: 1
3025
+ };
3026
+ const build_prompt = step("judge_llm_build_prompt", (args) => render_prompt(config.rubric, scale, args));
3027
+ const parse = step("judge_llm_parse", (reply) => parse_score(reply, scale));
3028
+ return compose("judge_llm", sequence([
3029
+ build_prompt,
3030
+ config.model,
3031
+ parse
3032
+ ]));
3033
+ }
3034
+ function render_prompt(rubric, scale, args) {
3035
+ return [
3036
+ `You are an evaluator. Score the model output against the rubric below.`,
3037
+ ``,
3038
+ `Rubric:`,
3039
+ rubric,
3040
+ ``,
3041
+ `Return a single line of JSON with exactly two keys: {"score": <number ${String(scale.min)}..${String(scale.max)}>, "reason": "<short>"}.`,
3042
+ `Do not include prose outside the JSON.`,
3043
+ ``,
3044
+ `Input:`,
3045
+ JSON.stringify(args.input),
3046
+ ``,
3047
+ `Output:`,
3048
+ JSON.stringify(args.output)
3049
+ ].join("\n");
3050
+ }
3051
+ function parse_score(reply, scale) {
3052
+ const candidate = extract_json_object(reply.trim());
3053
+ if (candidate === void 0) return void 0;
3054
+ let parsed;
3055
+ try {
3056
+ parsed = JSON.parse(candidate);
3057
+ } catch {
3058
+ return;
3059
+ }
3060
+ if (!is_record(parsed)) return void 0;
3061
+ const raw_score = parsed["score"];
3062
+ if (typeof raw_score !== "number" || !Number.isFinite(raw_score)) return void 0;
3063
+ const clamped = Math.max(scale.min, Math.min(scale.max, raw_score));
3064
+ const raw_reason = parsed["reason"];
3065
+ const reason = typeof raw_reason === "string" ? raw_reason : void 0;
3066
+ return reason === void 0 ? { score: clamped } : {
3067
+ score: clamped,
3068
+ reason
3069
+ };
3070
+ }
3071
+ function extract_json_object(text) {
3072
+ if (text.startsWith("{")) return text;
3073
+ const start = text.indexOf("{");
3074
+ const end = text.lastIndexOf("}");
3075
+ if (start === -1 || end === -1 || end < start) return void 0;
3076
+ return text.slice(start, end + 1);
3077
+ }
3078
+ //#endregion
3079
+ //#region packages/composites/src/regression.ts
3080
+ /**
3081
+ * regression_compare: diff two BenchReports for regressions.
3082
+ *
3083
+ * The contract: given a `current` report and a `baseline` report, produce a
3084
+ * `RegressionReport` whose `ok` flag is false when any tracked metric got
3085
+ * worse beyond a threshold. The function does NOT short-circuit on first
3086
+ * failure — every metric and every per-case delta is computed so callers can
3087
+ * print or assert against the whole report.
3088
+ *
3089
+ * Tracked metrics:
3090
+ * - pass_rate (any drop is a regression by default)
3091
+ * - mean_scores.<name> (per judge; any drop is a regression by default)
3092
+ * - total_cost_usd (a relative cost increase above cost_threshold
3093
+ * counts as a regression; default 10%)
3094
+ *
3095
+ * Baselines are plain JSON, written via `write_baseline` and read via
3096
+ * `read_baseline`. They live wherever the caller decides — typically
3097
+ * `bench/<flow>/baseline.json`, checked into git per spec/eval.md §3.
3098
+ */
3099
+ function regression_compare(current, baseline, options = {}) {
3100
+ const score_threshold = options.score_threshold ?? 0;
3101
+ const cost_threshold = options.cost_threshold ?? .1;
3102
+ const deltas = [];
3103
+ const pass_delta = current.summary.pass_rate - baseline.summary.pass_rate;
3104
+ deltas.push({
3105
+ metric: "pass_rate",
3106
+ baseline: baseline.summary.pass_rate,
3107
+ current: current.summary.pass_rate,
3108
+ delta: pass_delta,
3109
+ is_regression: pass_delta < -score_threshold
3110
+ });
3111
+ const judge_names = collect_judge_names(current, baseline);
3112
+ for (const name of judge_names) {
3113
+ const c = current.summary.mean_scores[name] ?? 0;
3114
+ const b = baseline.summary.mean_scores[name] ?? 0;
3115
+ const d = c - b;
3116
+ deltas.push({
3117
+ metric: `mean_scores.${name}`,
3118
+ baseline: b,
3119
+ current: c,
3120
+ delta: d,
3121
+ is_regression: d < -score_threshold
3122
+ });
3123
+ }
3124
+ const cb = baseline.summary.total_cost_usd;
3125
+ const cc = current.summary.total_cost_usd;
3126
+ const cost_delta = cc - cb;
3127
+ const cost_ratio = cb === 0 ? cc > 0 ? Infinity : 0 : cost_delta / cb;
3128
+ deltas.push({
3129
+ metric: "total_cost_usd",
3130
+ baseline: cb,
3131
+ current: cc,
3132
+ delta: cost_delta,
3133
+ is_regression: cost_ratio > cost_threshold
3134
+ });
3135
+ const per_case = compute_per_case(current, baseline, score_threshold, cost_threshold);
3136
+ return {
3137
+ ok: !deltas.some((d) => d.is_regression) && !per_case.some((c) => c.is_regression),
3138
+ deltas,
3139
+ per_case
3140
+ };
3141
+ }
3142
+ function compute_per_case(current, baseline, score_threshold, cost_threshold) {
3143
+ const by_id_current = index_by_case_id(current.cases);
3144
+ const by_id_baseline = index_by_case_id(baseline.cases);
3145
+ const all_ids = new Set([...by_id_current.keys(), ...by_id_baseline.keys()]);
3146
+ const out = [];
3147
+ for (const id of all_ids) {
3148
+ const c = by_id_current.get(id);
3149
+ const b = by_id_baseline.get(id);
3150
+ const score_deltas = {};
3151
+ let any_score_regression = false;
3152
+ const judge_names = new Set([...Object.keys(c?.scores ?? {}), ...Object.keys(b?.scores ?? {})]);
3153
+ for (const name of judge_names) {
3154
+ const delta = score_value(c?.scores[name]) - score_value(b?.scores[name]);
3155
+ score_deltas[name] = delta;
3156
+ if (delta < -score_threshold) any_score_regression = true;
3157
+ }
3158
+ const cost_delta = (c?.cost_usd ?? 0) - (b?.cost_usd ?? 0);
3159
+ const cost_ratio_regression = b?.cost_usd !== void 0 && b.cost_usd > 0 ? cost_delta / b.cost_usd > cost_threshold : (c?.cost_usd ?? 0) > 0 && (b?.cost_usd ?? 0) === 0 && cost_threshold < Infinity;
3160
+ const ok_regression = b?.ok === true && c?.ok !== true;
3161
+ out.push({
3162
+ case_id: id,
3163
+ ...b !== void 0 ? { baseline: b } : {},
3164
+ ...c !== void 0 ? { current: c } : {},
3165
+ score_deltas,
3166
+ cost_delta,
3167
+ is_regression: any_score_regression || cost_ratio_regression || ok_regression
3168
+ });
3169
+ }
3170
+ return out;
3171
+ }
3172
+ function score_value(s) {
3173
+ if (s === void 0 || s === null) return 0;
3174
+ if (typeof s === "number") return Number.isFinite(s) ? s : 0;
3175
+ if (typeof s === "object" && "score" in s) {
3176
+ const v = s["score"];
3177
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
3178
+ }
3179
+ return 0;
3180
+ }
3181
+ function index_by_case_id(cases) {
3182
+ const m = /* @__PURE__ */ new Map();
3183
+ for (const c of cases) m.set(c.case_id, c);
3184
+ return m;
3185
+ }
3186
+ function collect_judge_names(a, b) {
3187
+ return [...new Set([...Object.keys(a.summary.mean_scores), ...Object.keys(b.summary.mean_scores)])].toSorted();
3188
+ }
3189
+ async function read_baseline(path) {
3190
+ const text = await readFile(path, "utf8");
3191
+ const parsed = JSON.parse(text);
3192
+ validate_report(parsed, path);
3193
+ return parsed;
3194
+ }
3195
+ async function write_baseline(path, report) {
3196
+ await mkdir(dirname(path), { recursive: true });
3197
+ await writeFile(path, `${JSON.stringify(report, null, 2)}\n`, "utf8");
3198
+ }
3199
+ function validate_report(value, path) {
3200
+ if (value === null || typeof value !== "object") throw new Error(`baseline at ${path} is not an object`);
3201
+ const v = value;
3202
+ if (typeof v.flow_name !== "string" || typeof v.run_id !== "string") throw new Error(`baseline at ${path} missing flow_name/run_id`);
3203
+ if (!Array.isArray(v.cases) || typeof v.summary !== "object" || v.summary === null) throw new Error(`baseline at ${path} missing cases/summary`);
3204
+ }
3205
+ //#endregion
2595
3206
  //#region packages/engine/src/version.ts
2596
- const version$1 = "0.3.3";
3207
+ const version$1 = "0.3.8";
2597
3208
  //#endregion
2598
3209
  //#region packages/engine/src/errors.ts
2599
3210
  var rate_limit_error = class extends Error {
@@ -6093,6 +6704,544 @@ function forward_standard_env() {
6093
6704
  return out;
6094
6705
  }
6095
6706
  //#endregion
6096
- export { STEP_KINDS, aborted_error, adversarial, branch, checkpoint, compose, consensus, version as core_version, create_engine, custom_event_schema, describe, describe_cycle_error, emit_event_schema, engine_config_error, version$1 as engine_version, ensemble, ensemble_step, fallback, flow_schema, forward_standard_env, improve, is_step_kind, learn, loop, map, model_call, model_not_found_error, on_chunk_error, parallel, pipe, provider_capability_error, provider_error, provider_not_configured_error, rate_limit_error, resume_validation_error, retry, run, schema_validation_error, scope, sequence, span_end_event_schema, span_start_event_schema, stash, step, suspend, suspended_error, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, trajectory_event_schema, use };
6707
+ //#region packages/viewer/src/broadcast.ts
6708
+ function create_broadcaster(options) {
6709
+ const max = Math.max(1, options.buffer | 0);
6710
+ const ring = [];
6711
+ const subscribers = /* @__PURE__ */ new Set();
6712
+ let next_id = 1;
6713
+ const emit = (event) => {
6714
+ const entry = {
6715
+ id: next_id++,
6716
+ event
6717
+ };
6718
+ ring.push(entry);
6719
+ if (ring.length > max) ring.splice(0, ring.length - max);
6720
+ for (const fn of Array.from(subscribers)) try {
6721
+ fn(entry);
6722
+ } catch (err) {
6723
+ subscribers.delete(fn);
6724
+ if (options.on_subscriber_error) options.on_subscriber_error(err);
6725
+ }
6726
+ return entry;
6727
+ };
6728
+ const subscribe = (fn) => {
6729
+ subscribers.add(fn);
6730
+ return () => {
6731
+ subscribers.delete(fn);
6732
+ };
6733
+ };
6734
+ const snapshot = () => [...ring];
6735
+ const snapshot_after = (last_id) => ring.filter((e) => e.id > last_id);
6736
+ const size = () => ring.length;
6737
+ return {
6738
+ emit,
6739
+ subscribe,
6740
+ snapshot,
6741
+ snapshot_after,
6742
+ size
6743
+ };
6744
+ }
6745
+ //#endregion
6746
+ //#region packages/viewer/src/server.ts
6747
+ /**
6748
+ * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.
6749
+ *
6750
+ * GET / -> static viewer.html
6751
+ * GET /api/events -> text/event-stream replaying the ring buffer
6752
+ * GET /api/snapshot -> JSON dump of the ring buffer
6753
+ * POST /api/ingest -> newline-delimited trajectory events (http_logger)
6754
+ * GET /api/health -> { ok: true }
6755
+ *
6756
+ * The server owns nothing but the socket. The broadcaster owns the event
6757
+ * history; the static html lives on disk. SSE clients reconnect with
6758
+ * `Last-Event-ID` and the server replays anything past their cursor from
6759
+ * the ring buffer; older events are gone (bounded memory by design).
6760
+ */
6761
+ const SSE_HEARTBEAT_MS = 15e3;
6762
+ const STATIC_HTML = resolve(dirname(fileURLToPath(import.meta.url)), "static", "viewer.html");
6763
+ function start_server(options) {
6764
+ const { broadcaster, host, port, on_parse_error } = options;
6765
+ const handler = (req, res) => {
6766
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? `${host}:${port}`}`);
6767
+ const route = `${req.method ?? "GET"} ${url.pathname}`;
6768
+ if (route === "GET /" || route === "GET /index.html") {
6769
+ serve_static_html(res);
6770
+ return;
6771
+ }
6772
+ if (route === "GET /api/health") {
6773
+ send_json(res, 200, { ok: true });
6774
+ return;
6775
+ }
6776
+ if (route === "GET /api/snapshot") {
6777
+ send_json(res, 200, { events: broadcaster.snapshot() });
6778
+ return;
6779
+ }
6780
+ if (route === "GET /api/events") {
6781
+ handle_sse(req, res, broadcaster);
6782
+ return;
6783
+ }
6784
+ if (route === "POST /api/ingest") {
6785
+ handle_ingest(req, res, broadcaster, on_parse_error);
6786
+ return;
6787
+ }
6788
+ res.statusCode = 404;
6789
+ res.setHeader("content-type", "application/json");
6790
+ res.end(JSON.stringify({
6791
+ error: "not_found",
6792
+ route
6793
+ }));
6794
+ };
6795
+ const http_server = createServer(handler);
6796
+ return new Promise((res_ok, res_err) => {
6797
+ http_server.once("error", res_err);
6798
+ http_server.listen(port, host, () => {
6799
+ http_server.removeListener("error", res_err);
6800
+ const addr = http_server.address();
6801
+ res_ok({
6802
+ url: `http://${host}:${addr !== null && typeof addr === "object" && "port" in addr ? addr.port : port}`,
6803
+ close: () => close_server(http_server)
6804
+ });
6805
+ });
6806
+ });
6807
+ }
6808
+ function close_server(server) {
6809
+ return new Promise((res_ok, res_err) => {
6810
+ server.close((err) => {
6811
+ if (err) res_err(err);
6812
+ else res_ok();
6813
+ });
6814
+ server.closeAllConnections?.();
6815
+ });
6816
+ }
6817
+ function send_json(res, status, body) {
6818
+ res.statusCode = status;
6819
+ res.setHeader("content-type", "application/json");
6820
+ res.end(JSON.stringify(body));
6821
+ }
6822
+ function serve_static_html(res) {
6823
+ let size;
6824
+ try {
6825
+ size = statSync(STATIC_HTML).size;
6826
+ } catch {
6827
+ res.statusCode = 500;
6828
+ res.setHeader("content-type", "text/plain");
6829
+ res.end("viewer.html missing");
6830
+ return;
6831
+ }
6832
+ res.statusCode = 200;
6833
+ res.setHeader("content-type", "text/html; charset=utf-8");
6834
+ res.setHeader("cache-control", "no-store");
6835
+ res.setHeader("content-length", String(size));
6836
+ createReadStream(STATIC_HTML).pipe(res);
6837
+ }
6838
+ function handle_sse(req, res, broadcaster) {
6839
+ res.statusCode = 200;
6840
+ res.setHeader("content-type", "text/event-stream");
6841
+ res.setHeader("cache-control", "no-store");
6842
+ res.setHeader("connection", "keep-alive");
6843
+ res.setHeader("x-accel-buffering", "no");
6844
+ const last_event_id = parse_last_event_id(req.headers["last-event-id"]);
6845
+ for (const entry of broadcaster.snapshot_after(last_event_id)) write_event(res, entry.id, entry.event);
6846
+ const heartbeat = setInterval(() => {
6847
+ res.write(": heartbeat\n\n");
6848
+ }, SSE_HEARTBEAT_MS);
6849
+ const unsubscribe = broadcaster.subscribe((entry) => {
6850
+ write_event(res, entry.id, entry.event);
6851
+ });
6852
+ const close = () => {
6853
+ clearInterval(heartbeat);
6854
+ unsubscribe();
6855
+ if (!res.writableEnded) {
6856
+ res.write("event: close\ndata: {}\n\n");
6857
+ res.end();
6858
+ }
6859
+ };
6860
+ req.on("close", close);
6861
+ req.on("error", close);
6862
+ }
6863
+ function parse_last_event_id(value) {
6864
+ if (typeof value !== "string") return 0;
6865
+ const n = Number.parseInt(value, 10);
6866
+ return Number.isFinite(n) && n > 0 ? n : 0;
6867
+ }
6868
+ function write_event(res, id, event) {
6869
+ res.write(`id: ${id}\nevent: trajectory\ndata: ${JSON.stringify(event)}\n\n`);
6870
+ }
6871
+ function handle_ingest(req, res, broadcaster, on_parse_error) {
6872
+ let buf = "";
6873
+ let accepted = 0;
6874
+ let rejected = 0;
6875
+ const consume_line = (line) => {
6876
+ if (line.length === 0) return;
6877
+ let parsed;
6878
+ try {
6879
+ parsed = JSON.parse(line);
6880
+ } catch (err) {
6881
+ rejected++;
6882
+ if (on_parse_error) on_parse_error(err, line);
6883
+ return;
6884
+ }
6885
+ const result = trajectory_event_schema.safeParse(parsed);
6886
+ if (!result.success) {
6887
+ rejected++;
6888
+ if (on_parse_error) on_parse_error(result.error, line);
6889
+ return;
6890
+ }
6891
+ broadcaster.emit(result.data);
6892
+ accepted++;
6893
+ };
6894
+ req.setEncoding("utf8");
6895
+ req.on("data", (chunk) => {
6896
+ buf += chunk;
6897
+ let nl = buf.indexOf("\n");
6898
+ while (nl !== -1) {
6899
+ consume_line(buf.slice(0, nl));
6900
+ buf = buf.slice(nl + 1);
6901
+ nl = buf.indexOf("\n");
6902
+ }
6903
+ });
6904
+ req.on("end", () => {
6905
+ if (buf.length > 0) consume_line(buf);
6906
+ send_json(res, 200, {
6907
+ accepted,
6908
+ rejected
6909
+ });
6910
+ });
6911
+ req.on("error", (err) => {
6912
+ if (on_parse_error) on_parse_error(err, "");
6913
+ send_json(res, 400, { error: "bad_request" });
6914
+ });
6915
+ }
6916
+ //#endregion
6917
+ //#region packages/viewer/src/tail.ts
6918
+ /**
6919
+ * JSONL file tailer.
6920
+ *
6921
+ * Watches a file for appends and emits one parsed trajectory event per
6922
+ * complete line. Handles three pathological cases the spec calls out:
6923
+ *
6924
+ * - Truncation / rotation: a watcher event whose stat is shorter than the
6925
+ * current offset means the file shrunk. Reset offset to 0 and re-stream.
6926
+ * - Partial last line: if the trailing chunk has no `\n`, buffer it and
6927
+ * wait. Never parse a half-written line.
6928
+ * - Schema failures: a line that fails `trajectory_event_schema.parse` is
6929
+ * dropped and surfaced to `on_parse_error`. The stream keeps going.
6930
+ *
6931
+ * The watcher is fs.watch-based with a debounced re-read; on platforms where
6932
+ * fs.watch is flaky for appends we still catch up because the next tick
6933
+ * re-stats and re-reads from the saved offset.
6934
+ */
6935
+ function start_tail(options) {
6936
+ const { path, on_event, on_parse_error, on_io_error } = options;
6937
+ let offset = 0;
6938
+ let buffer = "";
6939
+ let busy = false;
6940
+ let pending = false;
6941
+ let closed = false;
6942
+ let watcher = null;
6943
+ let last_drain = Promise.resolve();
6944
+ const handle_line = (line) => {
6945
+ if (line.length === 0) return;
6946
+ let parsed;
6947
+ try {
6948
+ parsed = JSON.parse(line);
6949
+ } catch (err) {
6950
+ if (on_parse_error) on_parse_error(err, line);
6951
+ return;
6952
+ }
6953
+ const result = trajectory_event_schema.safeParse(parsed);
6954
+ if (!result.success) {
6955
+ if (on_parse_error) on_parse_error(result.error, line);
6956
+ return;
6957
+ }
6958
+ on_event(result.data);
6959
+ };
6960
+ const read_more = async () => {
6961
+ let st;
6962
+ try {
6963
+ st = await stat(path);
6964
+ } catch (err) {
6965
+ if (on_io_error) on_io_error(err);
6966
+ return;
6967
+ }
6968
+ if (st.size < offset) {
6969
+ offset = 0;
6970
+ buffer = "";
6971
+ }
6972
+ if (st.size === offset) return;
6973
+ const fh = await open(path, "r").catch((err) => {
6974
+ if (on_io_error) on_io_error(err);
6975
+ return null;
6976
+ });
6977
+ if (!fh) return;
6978
+ try {
6979
+ const length = st.size - offset;
6980
+ const buf = Buffer.alloc(length);
6981
+ const { bytesRead } = await fh.read(buf, 0, length, offset);
6982
+ offset += bytesRead;
6983
+ buffer += buf.subarray(0, bytesRead).toString("utf8");
6984
+ } finally {
6985
+ await fh.close();
6986
+ }
6987
+ let nl = buffer.indexOf("\n");
6988
+ while (nl !== -1) {
6989
+ const line = buffer.slice(0, nl);
6990
+ buffer = buffer.slice(nl + 1);
6991
+ handle_line(line);
6992
+ nl = buffer.indexOf("\n");
6993
+ }
6994
+ };
6995
+ const schedule = () => {
6996
+ if (closed) return;
6997
+ if (busy) {
6998
+ pending = true;
6999
+ return;
7000
+ }
7001
+ busy = true;
7002
+ last_drain = (async () => {
7003
+ try {
7004
+ let keep_going = true;
7005
+ while (keep_going) {
7006
+ pending = false;
7007
+ await read_more();
7008
+ keep_going = pending && !closed;
7009
+ }
7010
+ } finally {
7011
+ busy = false;
7012
+ }
7013
+ })();
7014
+ };
7015
+ schedule();
7016
+ try {
7017
+ watcher = watch(path, { persistent: true }, () => {
7018
+ schedule();
7019
+ });
7020
+ } catch (err) {
7021
+ if (on_io_error) on_io_error(err);
7022
+ }
7023
+ const stop = () => {
7024
+ closed = true;
7025
+ if (watcher) {
7026
+ watcher.close();
7027
+ watcher = null;
7028
+ }
7029
+ };
7030
+ const drain = async () => {
7031
+ schedule();
7032
+ await last_drain;
7033
+ };
7034
+ return {
7035
+ stop,
7036
+ drain
7037
+ };
7038
+ }
7039
+ //#endregion
7040
+ //#region packages/viewer/src/cli.ts
7041
+ /**
7042
+ * fascicle-viewer CLI.
7043
+ *
7044
+ * fascicle-viewer <path> # tail a JSONL file (primary)
7045
+ * fascicle-viewer --listen # accept HTTP push only
7046
+ * fascicle-viewer <path> --listen # both producers feed the same broadcaster
7047
+ *
7048
+ * Flags: --port <n> --host <h> --buffer <n> --no-open --help
7049
+ *
7050
+ * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT
7051
+ * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`
7052
+ * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.
7053
+ */
7054
+ const HELP = `\
7055
+ fascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.
7056
+
7057
+ Usage:
7058
+ fascicle-viewer <path> tail a JSONL file
7059
+ fascicle-viewer --listen accept HTTP push only
7060
+ fascicle-viewer <path> --listen both producers feed the same broadcaster
7061
+
7062
+ Options:
7063
+ --port <n> port (default 4242)
7064
+ --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)
7065
+ --buffer <n> ring-buffer size (default 1000)
7066
+ --no-open do not open the browser
7067
+ --help show this message
7068
+ `;
7069
+ function parse(argv) {
7070
+ const { values, positionals } = parseArgs({
7071
+ args: [...argv],
7072
+ allowPositionals: true,
7073
+ options: {
7074
+ port: {
7075
+ type: "string",
7076
+ default: "4242"
7077
+ },
7078
+ host: {
7079
+ type: "string",
7080
+ default: "127.0.0.1"
7081
+ },
7082
+ buffer: {
7083
+ type: "string",
7084
+ default: "1000"
7085
+ },
7086
+ listen: {
7087
+ type: "boolean",
7088
+ default: false
7089
+ },
7090
+ open: {
7091
+ type: "boolean",
7092
+ default: true
7093
+ },
7094
+ "no-open": {
7095
+ type: "boolean",
7096
+ default: false
7097
+ },
7098
+ help: {
7099
+ type: "boolean",
7100
+ default: false
7101
+ }
7102
+ }
7103
+ });
7104
+ if (values.help) {
7105
+ process.stdout.write(HELP);
7106
+ process.exit(0);
7107
+ }
7108
+ const port_raw = values.port ?? "4242";
7109
+ const buffer_raw = values.buffer ?? "1000";
7110
+ const port = Number.parseInt(port_raw, 10);
7111
+ const buffer = Number.parseInt(buffer_raw, 10);
7112
+ if (!Number.isFinite(port) || port <= 0) {
7113
+ process.stderr.write(`invalid --port: ${port_raw}\n`);
7114
+ process.exit(2);
7115
+ }
7116
+ if (!Number.isFinite(buffer) || buffer <= 0) {
7117
+ process.stderr.write(`invalid --buffer: ${buffer_raw}\n`);
7118
+ process.exit(2);
7119
+ }
7120
+ const path = positionals[0];
7121
+ const listen = values.listen ?? false;
7122
+ if (path === void 0 && !listen) {
7123
+ process.stderr.write("fascicle-viewer: a <path> is required unless --listen is set\n");
7124
+ process.stderr.write(HELP);
7125
+ process.exit(2);
7126
+ }
7127
+ return {
7128
+ ...path !== void 0 ? { path } : {},
7129
+ host: values.host ?? "127.0.0.1",
7130
+ port,
7131
+ buffer,
7132
+ listen,
7133
+ open: !values["no-open"] && (values.open ?? true)
7134
+ };
7135
+ }
7136
+ function open_browser(url) {
7137
+ const platform = process.platform;
7138
+ const cmd = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
7139
+ const args = platform === "win32" ? [
7140
+ "/c",
7141
+ "start",
7142
+ "\"\"",
7143
+ url
7144
+ ] : [url];
7145
+ try {
7146
+ const child = spawn(cmd, args, {
7147
+ stdio: "ignore",
7148
+ detached: true
7149
+ });
7150
+ child.on("error", () => {});
7151
+ child.unref();
7152
+ } catch {}
7153
+ }
7154
+ async function run_viewer_cli(argv) {
7155
+ const args = parse(argv);
7156
+ if (args.path !== void 0 && !existsSync(args.path)) process.stderr.write(`fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\n`);
7157
+ if (args.host === "0.0.0.0") process.stderr.write("fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\n");
7158
+ const handle = await start_viewer({
7159
+ ...args.path !== void 0 ? { path: args.path } : {},
7160
+ host: args.host,
7161
+ port: args.port,
7162
+ buffer: args.buffer,
7163
+ on_parse_error: (err, line) => {
7164
+ const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line;
7165
+ process.stderr.write(`fascicle-viewer: skipped malformed line: ${preview}\n ${describe_error(err)}\n`);
7166
+ },
7167
+ on_io_error: (err) => {
7168
+ process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\n`);
7169
+ }
7170
+ });
7171
+ if (args.path !== void 0) process.stderr.write(`watching ${args.path}\n`);
7172
+ if (args.listen || args.path === void 0) process.stderr.write(`listening for HTTP push on ${handle.url}/api/ingest\n`);
7173
+ process.stderr.write(`viewer at ${handle.url}\n`);
7174
+ if (args.open) open_browser(handle.url);
7175
+ const shutdown = async () => {
7176
+ process.stderr.write("\nfascicle-viewer: shutting down\n");
7177
+ await handle.close();
7178
+ process.exit(0);
7179
+ };
7180
+ process.on("SIGINT", () => {
7181
+ shutdown();
7182
+ });
7183
+ process.on("SIGTERM", () => {
7184
+ shutdown();
7185
+ });
7186
+ }
7187
+ function describe_error(err) {
7188
+ if (err instanceof Error) return err.message;
7189
+ try {
7190
+ return JSON.stringify(err);
7191
+ } catch {
7192
+ return String(err);
7193
+ }
7194
+ }
7195
+ if (typeof process.argv[1] === "string" && (process.argv[1].endsWith("/cli.ts") || process.argv[1].endsWith("/cli.js"))) run_viewer_cli(process.argv.slice(2)).catch((err) => {
7196
+ process.stderr.write(`fascicle-viewer: ${describe_error(err)}\n`);
7197
+ process.exit(1);
7198
+ });
7199
+ //#endregion
7200
+ //#region packages/viewer/src/index.ts
7201
+ /**
7202
+ * Public surface for @repo/viewer.
7203
+ *
7204
+ * `start_viewer({ ... })` is the programmatic embed: spin up the server,
7205
+ * optionally start tailing a JSONL file, and return a handle that can stop
7206
+ * both. `start_viewer` only depends on @repo/core's wire-format schema; it
7207
+ * never reaches into the engine, composites, or any provider.
7208
+ */
7209
+ async function start_viewer(options = {}) {
7210
+ const host = options.host ?? "127.0.0.1";
7211
+ const port = options.port ?? 4242;
7212
+ const broadcaster = create_broadcaster({
7213
+ buffer: options.buffer ?? 1e3,
7214
+ ...options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}
7215
+ });
7216
+ const server = await start_server({
7217
+ broadcaster,
7218
+ host,
7219
+ port,
7220
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
7221
+ });
7222
+ let tail = null;
7223
+ if (options.path !== void 0) tail = start_tail({
7224
+ path: options.path,
7225
+ on_event: (event) => {
7226
+ broadcaster.emit(event);
7227
+ },
7228
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {},
7229
+ ...options.on_io_error ? { on_io_error: options.on_io_error } : {}
7230
+ });
7231
+ return wrap_handle(server, tail, host, port);
7232
+ }
7233
+ function wrap_handle(server, tail, host, port) {
7234
+ return {
7235
+ url: server.url,
7236
+ host,
7237
+ port,
7238
+ close: async () => {
7239
+ if (tail) tail.stop();
7240
+ await server.close();
7241
+ }
7242
+ };
7243
+ }
7244
+ //#endregion
7245
+ export { STEP_KINDS, aborted_error, adversarial, bench, branch, checkpoint, compose, consensus, version as core_version, create_engine, custom_event_schema, describe, describe_cycle_error, emit_event_schema, engine_config_error, version$1 as engine_version, ensemble, ensemble_step, fallback, flow_schema, forward_standard_env, improve, is_step_kind, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_not_found_error, normalize_score, on_chunk_error, parallel, pipe, provider_capability_error, provider_error, provider_not_configured_error, rate_limit_error, read_baseline, regression_compare, resume_validation_error, retry, run, run_viewer_cli, schema_validation_error, scope, sequence, span_end_event_schema, span_start_event_schema, start_viewer, stash, step, suspend, suspended_error, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, trajectory_event_schema, use, write_baseline };
6097
7246
 
6098
7247
  //# sourceMappingURL=index.js.map