fascicle 0.8.1 → 0.8.10

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,1834 +1,16 @@
1
- import { n as http_logger, r as filesystem_logger, t as tee_logger } from "./tee-B-MeNi7d.js";
2
- import { createHash, randomUUID } from "node:crypto";
1
+ import { A as timeout_error, C as describe, D as describe_cycle_error, E as aborted_error, O as resume_validation_error, S as sequence, T as run, _ as retry, a as trajectory_event_schema, b as branch, c as scope, d as suspend, f as checkpoint, g as fallback, h as timeout, i as span_start_event_schema, j as flow_schema_default, k as suspended_error, l as stash, m as loop, n as emit_event_schema, o as STEP_KINDS, p as compose, r as span_end_event_schema, s as is_step_kind, t as custom_event_schema, u as use, v as pipe, w as step, x as parallel, y as map } from "./core-dRSAN1Q2.js";
2
+ import { a as filesystem_logger, i as http_logger, n as tee_logger } from "./adapters-BS8cBOjL.js";
3
+ import { createHash } from "node:crypto";
3
4
  import { z } from "zod";
4
5
  import { mkdir, open, readFile, readdir, stat, writeFile } from "node:fs/promises";
5
6
  import { dirname, join, resolve } from "node:path";
6
7
  import { createReadStream, existsSync, mkdtempSync, statSync, watch, writeFileSync } from "node:fs";
7
8
  import { tmpdir } from "node:os";
8
9
  import { spawn } from "node:child_process";
9
- import { generateText, stepCountIs, streamText, tool } from "ai";
10
+ import { NoObjectGeneratedError, Output, generateText, stepCountIs, streamText, tool } from "ai";
10
11
  import { createServer } from "node:http";
11
12
  import { fileURLToPath } from "node:url";
12
13
  import { parseArgs } from "node:util";
13
- //#region src/core/flow-schema.json
14
- var flow_schema_default = {
15
- $schema: "https://json-schema.org/draft/2020-12/schema",
16
- $id: "https://robmclarty.dev/schemas/flow-schema.json",
17
- title: "fascicle Flow DSL",
18
- description: "YAML/JSON representation of a composition tree. Documentation-only in v1. See spec.md §5.17.",
19
- type: "array",
20
- items: { "$ref": "#/$defs/compose_entry" },
21
- $defs: {
22
- "compose_entry": {
23
- "type": "object",
24
- "required": ["compose"],
25
- "properties": { "compose": { "type": "string" } },
26
- "allOf": [{ "$ref": "#/$defs/node" }]
27
- },
28
- "node": {
29
- "type": "object",
30
- "anyOf": [
31
- { "required": ["step"] },
32
- { "required": ["sequence"] },
33
- { "required": ["parallel"] },
34
- { "required": ["branch"] },
35
- { "required": ["map"] },
36
- { "required": ["pipe"] },
37
- { "required": ["retry"] },
38
- { "required": ["fallback"] },
39
- { "required": ["timeout"] },
40
- { "required": ["loop"] },
41
- { "required": ["compose_node"] },
42
- { "required": ["adversarial"] },
43
- { "required": ["ensemble"] },
44
- { "required": ["tournament"] },
45
- { "required": ["consensus"] },
46
- { "required": ["checkpoint"] },
47
- { "required": ["suspend"] },
48
- { "required": ["scope"] },
49
- { "required": ["ref"] }
50
- ],
51
- "properties": {
52
- "step": { "$ref": "#/$defs/step_config" },
53
- "sequence": { "$ref": "#/$defs/sequence_config" },
54
- "parallel": { "$ref": "#/$defs/parallel_config" },
55
- "branch": { "$ref": "#/$defs/branch_config" },
56
- "map": { "$ref": "#/$defs/map_config" },
57
- "pipe": { "$ref": "#/$defs/pipe_config" },
58
- "retry": { "$ref": "#/$defs/retry_config" },
59
- "fallback": { "$ref": "#/$defs/fallback_config" },
60
- "timeout": { "$ref": "#/$defs/timeout_config" },
61
- "loop": { "$ref": "#/$defs/loop_config" },
62
- "compose_node": { "$ref": "#/$defs/compose_node_config" },
63
- "adversarial": { "$ref": "#/$defs/adversarial_config" },
64
- "ensemble": { "$ref": "#/$defs/ensemble_config" },
65
- "tournament": { "$ref": "#/$defs/tournament_config" },
66
- "consensus": { "$ref": "#/$defs/consensus_config" },
67
- "checkpoint": { "$ref": "#/$defs/checkpoint_config" },
68
- "suspend": { "$ref": "#/$defs/suspend_config" },
69
- "scope": { "$ref": "#/$defs/scope_config" },
70
- "ref": { "type": "string" }
71
- }
72
- },
73
- "step_config": {
74
- "type": "object",
75
- "required": ["fn"],
76
- "properties": {
77
- "id": { "type": "string" },
78
- "fn": { "type": "string" }
79
- }
80
- },
81
- "sequence_config": {
82
- "type": "array",
83
- "items": { "$ref": "#/$defs/node" }
84
- },
85
- "parallel_config": {
86
- "type": "object",
87
- "additionalProperties": { "$ref": "#/$defs/node" }
88
- },
89
- "branch_config": {
90
- "type": "object",
91
- "required": [
92
- "when",
93
- "then",
94
- "otherwise"
95
- ],
96
- "properties": {
97
- "when": { "type": "string" },
98
- "then": { "$ref": "#/$defs/node" },
99
- "otherwise": { "$ref": "#/$defs/node" }
100
- }
101
- },
102
- "map_config": {
103
- "type": "object",
104
- "required": ["items", "do"],
105
- "properties": {
106
- "items": { "type": "string" },
107
- "do": { "$ref": "#/$defs/node" },
108
- "concurrency": {
109
- "type": "integer",
110
- "minimum": 1
111
- }
112
- }
113
- },
114
- "pipe_config": {
115
- "type": "object",
116
- "required": ["of", "fn"],
117
- "properties": {
118
- "of": { "$ref": "#/$defs/node" },
119
- "fn": { "type": "string" }
120
- }
121
- },
122
- "retry_config": {
123
- "type": "object",
124
- "required": ["do", "max_attempts"],
125
- "properties": {
126
- "do": { "$ref": "#/$defs/node" },
127
- "max_attempts": {
128
- "type": "integer",
129
- "minimum": 1
130
- },
131
- "backoff_ms": {
132
- "type": "integer",
133
- "minimum": 0
134
- }
135
- }
136
- },
137
- "fallback_config": {
138
- "type": "object",
139
- "required": ["primary", "backup"],
140
- "properties": {
141
- "primary": { "$ref": "#/$defs/node" },
142
- "backup": { "$ref": "#/$defs/node" }
143
- }
144
- },
145
- "timeout_config": {
146
- "type": "object",
147
- "required": ["do", "ms"],
148
- "properties": {
149
- "do": { "$ref": "#/$defs/node" },
150
- "ms": {
151
- "type": "integer",
152
- "minimum": 1
153
- }
154
- }
155
- },
156
- "compose_node_config": {
157
- "type": "object",
158
- "required": ["name", "do"],
159
- "properties": {
160
- "name": {
161
- "type": "string",
162
- "minLength": 1
163
- },
164
- "do": { "$ref": "#/$defs/node" }
165
- }
166
- },
167
- "loop_config": {
168
- "type": "object",
169
- "required": ["body", "max_rounds"],
170
- "properties": {
171
- "name": {
172
- "type": "string",
173
- "minLength": 1
174
- },
175
- "init": { "type": "string" },
176
- "body": { "$ref": "#/$defs/node" },
177
- "guard": { "$ref": "#/$defs/node" },
178
- "finish": { "type": "string" },
179
- "max_rounds": {
180
- "type": "integer",
181
- "minimum": 1
182
- }
183
- }
184
- },
185
- "adversarial_config": {
186
- "type": "object",
187
- "required": [
188
- "build",
189
- "critique",
190
- "accept",
191
- "max_rounds"
192
- ],
193
- "properties": {
194
- "build": { "$ref": "#/$defs/node" },
195
- "critique": { "$ref": "#/$defs/node" },
196
- "accept": { "type": "string" },
197
- "max_rounds": {
198
- "type": "integer",
199
- "minimum": 1
200
- }
201
- }
202
- },
203
- "ensemble_config": {
204
- "type": "object",
205
- "required": ["members", "score"],
206
- "properties": {
207
- "members": {
208
- "type": "object",
209
- "additionalProperties": { "$ref": "#/$defs/node" }
210
- },
211
- "score": { "type": "string" },
212
- "select": {
213
- "type": "string",
214
- "enum": ["max", "min"]
215
- }
216
- }
217
- },
218
- "tournament_config": {
219
- "type": "object",
220
- "required": ["members", "compare"],
221
- "properties": {
222
- "members": {
223
- "type": "object",
224
- "additionalProperties": { "$ref": "#/$defs/node" }
225
- },
226
- "compare": { "type": "string" }
227
- }
228
- },
229
- "consensus_config": {
230
- "type": "object",
231
- "required": [
232
- "members",
233
- "agree",
234
- "max_rounds"
235
- ],
236
- "properties": {
237
- "members": {
238
- "type": "object",
239
- "additionalProperties": { "$ref": "#/$defs/node" }
240
- },
241
- "agree": { "type": "string" },
242
- "max_rounds": {
243
- "type": "integer",
244
- "minimum": 1
245
- }
246
- }
247
- },
248
- "checkpoint_config": {
249
- "type": "object",
250
- "required": ["do", "key"],
251
- "properties": {
252
- "do": { "$ref": "#/$defs/node" },
253
- "key": { "type": "string" }
254
- }
255
- },
256
- "suspend_config": {
257
- "type": "object",
258
- "required": [
259
- "id",
260
- "on",
261
- "resume_schema",
262
- "combine"
263
- ],
264
- "properties": {
265
- "id": { "type": "string" },
266
- "on": { "type": "string" },
267
- "resume_schema": { "type": "string" },
268
- "combine": { "type": "string" }
269
- }
270
- },
271
- "scope_config": {
272
- "type": "array",
273
- "items": { "$ref": "#/$defs/scope_entry" }
274
- },
275
- "scope_entry": {
276
- "type": "object",
277
- "oneOf": [{
278
- "type": "object",
279
- "required": ["stash", "do"],
280
- "properties": {
281
- "stash": { "type": "string" },
282
- "do": { "$ref": "#/$defs/node" }
283
- }
284
- }, {
285
- "type": "object",
286
- "required": ["use", "do"],
287
- "properties": {
288
- "use": {
289
- "type": "array",
290
- "items": { "type": "string" }
291
- },
292
- "do": { "$ref": "#/$defs/node" }
293
- }
294
- }]
295
- }
296
- }
297
- };
298
- //#endregion
299
- //#region src/core/cleanup.ts
300
- const HANDLER_TIMEOUT_MS = 5e3;
301
- function create_cleanup_registry(trajectory) {
302
- const handlers = [];
303
- let ran = false;
304
- function register(fn) {
305
- if (ran) {
306
- trajectory.record({ kind: "cleanup_registered_after_flush" });
307
- return;
308
- }
309
- handlers.push(fn);
310
- }
311
- async function run_all() {
312
- if (ran) return;
313
- ran = true;
314
- for (let i = handlers.length - 1; i >= 0; i -= 1) {
315
- const fn = handlers[i];
316
- if (!fn) continue;
317
- await run_one(fn, trajectory);
318
- }
319
- }
320
- return {
321
- register,
322
- run_all
323
- };
324
- }
325
- async function run_one(fn, trajectory) {
326
- let timeout_id = null;
327
- try {
328
- await new Promise((resolve) => {
329
- timeout_id = setTimeout(() => {
330
- trajectory.record({
331
- kind: "cleanup_timeout",
332
- timeout_ms: HANDLER_TIMEOUT_MS
333
- });
334
- resolve();
335
- }, HANDLER_TIMEOUT_MS);
336
- Promise.resolve().then(() => fn()).then(() => {
337
- if (timeout_id) clearTimeout(timeout_id);
338
- resolve();
339
- }, (err) => {
340
- if (timeout_id) clearTimeout(timeout_id);
341
- trajectory.record({
342
- kind: "cleanup_error",
343
- error: err instanceof Error ? err.message : String(err)
344
- });
345
- resolve();
346
- });
347
- });
348
- } finally {
349
- if (timeout_id) clearTimeout(timeout_id);
350
- }
351
- }
352
- //#endregion
353
- //#region src/core/errors.ts
354
- /**
355
- * Typed errors for the composition layer.
356
- *
357
- * This is the only source file in packages/core/src/ that uses the `class`
358
- * keyword. `Error` is a built-in and `instanceof` branching is how composers
359
- * like `retry` and `fallback` distinguish failure modes. See constraints.md §2.
360
- */
361
- var timeout_error = class extends Error {
362
- kind = "timeout_error";
363
- timeout_ms;
364
- constructor(message, timeout_ms) {
365
- super(message);
366
- this.name = "timeout_error";
367
- this.timeout_ms = timeout_ms;
368
- }
369
- };
370
- var suspended_error = class extends Error {
371
- kind = "suspended_error";
372
- suspend_id;
373
- payload;
374
- constructor(suspend_id, payload, message) {
375
- super(message ?? `suspended at ${suspend_id}`);
376
- this.name = "suspended_error";
377
- this.suspend_id = suspend_id;
378
- this.payload = payload;
379
- }
380
- };
381
- var resume_validation_error = class extends Error {
382
- kind = "resume_validation_error";
383
- issues;
384
- constructor(message, issues) {
385
- super(message);
386
- this.name = "resume_validation_error";
387
- this.issues = issues;
388
- }
389
- };
390
- var describe_cycle_error = class extends Error {
391
- kind = "describe_cycle_error";
392
- step_id;
393
- constructor(step_id, message) {
394
- super(message ?? `describe: cycle detected at step id: ${step_id}`);
395
- this.name = "describe_cycle_error";
396
- this.step_id = step_id;
397
- }
398
- };
399
- var aborted_error = class extends Error {
400
- kind = "aborted_error";
401
- reason;
402
- step_index;
403
- tool_call_in_flight;
404
- constructor(message = "aborted", metadata = {}) {
405
- super(message);
406
- this.name = "aborted_error";
407
- if (metadata.reason !== void 0) this.reason = metadata.reason;
408
- this.step_index = metadata.step_index ?? 0;
409
- if (metadata.tool_call_in_flight !== void 0) this.tool_call_in_flight = metadata.tool_call_in_flight;
410
- }
411
- };
412
- /**
413
- * Control-flow signals are not application failures. `suspended_error` is a
414
- * human-approval gate pausing the run for later resume; `aborted_error` is
415
- * cancellation. Resilience composers (`retry`, `fallback`) must rethrow these
416
- * rather than retry past a suspend or run a backup under an aborted context.
417
- *
418
- * Kept internal to core: not re-exported by index.ts, so it does not
419
- * widen the public surface.
420
- */
421
- function is_control_flow_error(err) {
422
- return err instanceof suspended_error || err instanceof aborted_error;
423
- }
424
- //#endregion
425
- //#region src/core/streaming.ts
426
- const STREAMING_HIGH_WATER_MARK = 1e4;
427
- function create_streaming_channel(base, high_water_mark = STREAMING_HIGH_WATER_MARK) {
428
- const buffer = [];
429
- let dropped = 0;
430
- let closed = false;
431
- let marker_emitted = false;
432
- let waiter = null;
433
- function enqueue(event) {
434
- if (closed) return;
435
- if (waiter) {
436
- const resolve = waiter;
437
- waiter = null;
438
- resolve({
439
- value: event,
440
- done: false
441
- });
442
- return;
443
- }
444
- if (buffer.length >= high_water_mark) {
445
- buffer.shift();
446
- dropped += 1;
447
- return;
448
- }
449
- buffer.push(event);
450
- }
451
- function close() {
452
- if (closed) return;
453
- closed = true;
454
- if (dropped > 0 && !marker_emitted) {
455
- marker_emitted = true;
456
- buffer.push({
457
- kind: "events_dropped",
458
- count: dropped
459
- });
460
- }
461
- if (waiter) {
462
- const resolve = waiter;
463
- waiter = null;
464
- resolve({
465
- value: void 0,
466
- done: true
467
- });
468
- }
469
- }
470
- return {
471
- logger: {
472
- record: (event) => {
473
- base.record(event);
474
- enqueue(event);
475
- },
476
- start_span: (name, meta) => {
477
- const id = base.start_span(name, meta);
478
- enqueue({
479
- kind: "span_start",
480
- span_id: id,
481
- name,
482
- ...meta
483
- });
484
- return id;
485
- },
486
- end_span: (id, meta) => {
487
- base.end_span(id, meta);
488
- enqueue({
489
- kind: "span_end",
490
- span_id: id,
491
- ...meta
492
- });
493
- }
494
- },
495
- events: { [Symbol.asyncIterator]() {
496
- return {
497
- next() {
498
- if (buffer.length > 0) {
499
- const next_event = buffer.shift();
500
- if (next_event !== void 0) return Promise.resolve({
501
- value: next_event,
502
- done: false
503
- });
504
- }
505
- if (closed) return Promise.resolve({
506
- value: void 0,
507
- done: true
508
- });
509
- return new Promise((resolve) => {
510
- waiter = resolve;
511
- });
512
- },
513
- return() {
514
- close();
515
- return Promise.resolve({
516
- value: void 0,
517
- done: true
518
- });
519
- }
520
- };
521
- } },
522
- close
523
- };
524
- }
525
- //#endregion
526
- //#region src/core/runner.ts
527
- /**
528
- * Runner.
529
- *
530
- * Dispatches a step to its kind-specific handler. `runner.ts` contains no
531
- * composer-specific logic beyond a Map lookup on `step.kind`; each composer
532
- * file registers its handler at module load via `register_kind(...)`.
533
- *
534
- * `run(flow, input, options?)` constructs a fresh `RunContext` per top-level
535
- * call, installs process signal handlers (opt-out via options), and guarantees
536
- * cleanup handlers execute in LIFO order on success, failure, or abort.
537
- *
538
- * `run.stream(flow, input, options?)` is a secondary entry point returning
539
- * `{ events, result }`. Streaming is purely observational; the step graph is
540
- * identical to `run(...)`.
541
- */
542
- const dispatch = /* @__PURE__ */ new Map();
543
- function register_kind(kind, fn) {
544
- dispatch.set(kind, fn);
545
- }
546
- /**
547
- * Resolve the trajectory span label for a step. Prefers a non-empty
548
- * `display_name` from `flow.config`; otherwise falls back to the supplied
549
- * default (typically the step's `kind`).
550
- *
551
- * Dispatch handlers use this so that any composer carrying a user-supplied
552
- * `name` surfaces under that label in the trajectory, while unconfigured
553
- * composers retain their kind-based label.
554
- */
555
- function resolve_span_label(flow, fallback) {
556
- const display = flow.config?.["display_name"];
557
- return typeof display === "string" && display.length > 0 ? display : fallback;
558
- }
559
- /**
560
- * Register the standard span-wrapping dispatch handler for a composer kind.
561
- *
562
- * Every composer wraps `flow.run` in a span identically; this centralizes that
563
- * boilerplate and threads span parentage: the span opens with the current
564
- * `ctx.parent_span_id` as its parent, and `flow.run` receives a child context
565
- * whose `parent_span_id` is this span. Children dispatched from within
566
- * (including concurrent ones under `parallel`/`map`, which spread the context)
567
- * therefore nest correctly instead of leaving `parent_span_id` unpopulated.
568
- */
569
- function register_traced_kind(kind) {
570
- register_kind(kind, async (flow, input, ctx) => {
571
- const label = resolve_span_label(flow, kind);
572
- const span_meta = { id: flow.id };
573
- if (ctx.parent_span_id !== void 0) span_meta["parent_span_id"] = ctx.parent_span_id;
574
- const span_id = ctx.trajectory.start_span(label, span_meta);
575
- const child_ctx = {
576
- ...ctx,
577
- parent_span_id: span_id
578
- };
579
- try {
580
- const out = await flow.run(input, child_ctx);
581
- ctx.trajectory.end_span(span_id, { id: flow.id });
582
- return out;
583
- } catch (err) {
584
- ctx.trajectory.end_span(span_id, {
585
- id: flow.id,
586
- error: err instanceof Error ? err.message : String(err)
587
- });
588
- throw err;
589
- }
590
- });
591
- }
592
- const active_runs = /* @__PURE__ */ new Set();
593
- let signal_handler_installed = false;
594
- let sigint_handler = null;
595
- let sigterm_handler = null;
596
- function ensure_signal_handlers() {
597
- if (signal_handler_installed) return;
598
- signal_handler_installed = true;
599
- const abort_all = (signal_name) => () => {
600
- for (const controller of active_runs) controller.abort(new aborted_error(`received ${signal_name}`, { reason: { signal: signal_name } }));
601
- };
602
- sigint_handler = abort_all("SIGINT");
603
- sigterm_handler = abort_all("SIGTERM");
604
- process.on("SIGINT", sigint_handler);
605
- process.on("SIGTERM", sigterm_handler);
606
- }
607
- function release_signal_handlers() {
608
- if (!signal_handler_installed) return;
609
- if (active_runs.size > 0) return;
610
- signal_handler_installed = false;
611
- if (sigint_handler) process.off("SIGINT", sigint_handler);
612
- if (sigterm_handler) process.off("SIGTERM", sigterm_handler);
613
- sigint_handler = null;
614
- sigterm_handler = null;
615
- }
616
- const noop_logger = {
617
- record: () => {},
618
- start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,
619
- end_span: () => {}
620
- };
621
- /**
622
- * Wrap a logger so every emitted event automatically carries `run_id` and a
623
- * `ts` (epoch milliseconds) stamped at emission.
624
- *
625
- * Studios and other downstream consumers multiplex events across runs by
626
- * `run_id` and reconstruct real timing from `ts` instead of fabricating it at
627
- * ingest. Either field already present on an event or its meta is preserved;
628
- * we never overwrite a caller-supplied value.
629
- */
630
- function decorate_logger(inner, run_id) {
631
- const stamp_meta = (meta) => {
632
- const out = { ...meta };
633
- if (!("run_id" in out)) out["run_id"] = run_id;
634
- if (!("ts" in out)) out["ts"] = Date.now();
635
- return out;
636
- };
637
- return {
638
- record: (event) => {
639
- if ("run_id" in event && "ts" in event) {
640
- inner.record(event);
641
- return;
642
- }
643
- const extra = {};
644
- if (!("run_id" in event)) extra["run_id"] = run_id;
645
- if (!("ts" in event)) extra["ts"] = Date.now();
646
- inner.record({
647
- ...event,
648
- ...extra
649
- });
650
- },
651
- start_span: (name, meta) => inner.start_span(name, stamp_meta(meta)),
652
- end_span: (id, meta) => {
653
- inner.end_span(id, stamp_meta(meta));
654
- }
655
- };
656
- }
657
- async function dispatch_step(flow, input, ctx) {
658
- const handler = dispatch.get(flow.kind);
659
- if (!handler) throw new Error(`unknown step kind: ${flow.kind} (step id: ${flow.id})`);
660
- try {
661
- return await handler(flow, input, ctx);
662
- } catch (err) {
663
- prepend_path(err, flow.id);
664
- throw err;
665
- }
666
- }
667
- function prepend_path(err, id) {
668
- if (err === null || typeof err !== "object") return;
669
- const existing = Reflect.get(err, "path");
670
- const next = Array.isArray(existing) ? [id, ...existing.filter((v) => typeof v === "string")] : [id];
671
- Reflect.set(err, "path", next);
672
- }
673
- /**
674
- * Throw the abort reason if the context has been cancelled. Composers that
675
- * iterate over children (`sequence`, `scope`, `loop`) call this between steps
676
- * so a pending abort is honored before the next child starts, not only when a
677
- * downstream dispatch happens to observe it.
678
- */
679
- function throw_if_aborted$2(ctx) {
680
- if (!ctx.abort.aborted) return;
681
- const reason = ctx.abort.reason;
682
- throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
683
- }
684
- function start_run(flow, input, options, high_water_mark) {
685
- const install_signal_handlers = options.install_signal_handlers !== false;
686
- const base_logger = options.trajectory ?? noop_logger;
687
- const streaming = high_water_mark !== null;
688
- const controller = new AbortController();
689
- const run_id = randomUUID();
690
- let stream_events = empty_async_iterable();
691
- let close_stream = null;
692
- let inner = base_logger;
693
- if (streaming) {
694
- const channel = create_streaming_channel(base_logger, high_water_mark);
695
- inner = channel.logger;
696
- stream_events = channel.events;
697
- close_stream = channel.close;
698
- }
699
- const logger = decorate_logger(inner, run_id);
700
- const cleanup = create_cleanup_registry(logger);
701
- const ctx = {
702
- run_id,
703
- trajectory: logger,
704
- state: /* @__PURE__ */ new Map(),
705
- abort: controller.signal,
706
- emit: (event) => {
707
- logger.record({
708
- ...event,
709
- kind: "emit"
710
- });
711
- },
712
- on_cleanup: (fn) => {
713
- cleanup.register(fn);
714
- },
715
- checkpoint_store: options.checkpoint_store,
716
- resume_data: options.resume_data,
717
- streaming
718
- };
719
- active_runs.add(controller);
720
- if (install_signal_handlers) ensure_signal_handlers();
721
- const result = (async () => {
722
- try {
723
- return await dispatch_step(flow, input, ctx);
724
- } catch (err) {
725
- if (controller.signal.aborted && !(err instanceof aborted_error)) {
726
- const reason = controller.signal.reason;
727
- if (reason instanceof aborted_error) throw reason;
728
- }
729
- throw err;
730
- } finally {
731
- try {
732
- await cleanup.run_all();
733
- } finally {
734
- active_runs.delete(controller);
735
- release_signal_handlers();
736
- if (close_stream) close_stream();
737
- }
738
- }
739
- })();
740
- return {
741
- events: stream_events,
742
- result
743
- };
744
- }
745
- function empty_async_iterable() {
746
- return { [Symbol.asyncIterator]() {
747
- return { next: () => Promise.resolve({
748
- value: void 0,
749
- done: true
750
- }) };
751
- } };
752
- }
753
- async function run_impl(flow, input, options = {}) {
754
- const { result } = start_run(flow, input, options, null);
755
- return result;
756
- }
757
- function run_stream(flow, input, options = {}) {
758
- const { events, result } = start_run(flow, input, options, STREAMING_HIGH_WATER_MARK);
759
- return {
760
- events,
761
- result
762
- };
763
- }
764
- const run = Object.assign(run_impl, { stream: run_stream });
765
- //#endregion
766
- //#region src/core/step.ts
767
- /**
768
- * step() factory.
769
- *
770
- * Three forms:
771
- * step(id, fn) — named step. id is rendered in trajectory spans and describe().
772
- * step(id, fn, meta) — named step with optional human-readable metadata for studio,
773
- * codegen, and similar consumers. `meta` is purely descriptive
774
- * and never affects runtime semantics.
775
- * step(fn) — anonymous step. id is `anon_<counter>`; cannot be checkpointed.
776
- *
777
- * Anonymous steps carry an internal `anonymous: true` flag so checkpoint can
778
- * reject them synchronously at flow construction time (spec.md §9 F6 / §7 invariant 8).
779
- */
780
- let anon_counter = 0;
781
- function next_anon_id() {
782
- anon_counter += 1;
783
- return `anon_${anon_counter}`;
784
- }
785
- function step(id_or_fn, maybe_fn, meta) {
786
- if (typeof id_or_fn === "function") return {
787
- id: next_anon_id(),
788
- kind: "step",
789
- run: id_or_fn,
790
- anonymous: true
791
- };
792
- if (typeof maybe_fn !== "function") throw new TypeError("step(id, fn): fn must be a function");
793
- if (meta) return {
794
- id: id_or_fn,
795
- kind: "step",
796
- run: maybe_fn,
797
- meta
798
- };
799
- return {
800
- id: id_or_fn,
801
- kind: "step",
802
- run: maybe_fn
803
- };
804
- }
805
- register_traced_kind("step");
806
- //#endregion
807
- //#region src/core/describe.ts
808
- /**
809
- * describe(step) and describe.json(step) — composition introspection.
810
- *
811
- * `describe(step)` is the text-tree renderer. Multi-line string with
812
- * hierarchical indentation. Function values render as `<fn>` (or
813
- * `<fn:name>` when the function has a non-empty `name`); zod schemas
814
- * render as `<schema>`.
815
- *
816
- * `describe.json(step)` returns a `FlowNode` tree (kind, id, config, children)
817
- * for tooling (Studio UI, Mermaid renderers, diff tools). Function values
818
- * serialize as `{ kind: '<fn>', name? }` and schemas as `{ kind: '<schema>' }`.
819
- *
820
- * Both forms detect cycles. Under the default (loose) mode, back-references
821
- * render as `<cycle>(id)` in text and `{ kind: '<cycle>', id }` in JSON. Under
822
- * `{ strict: true }`, cycles throw `describe_cycle_error`.
823
- */
824
- const INDENT = " ";
825
- function describe_text(root, options) {
826
- const lines = [];
827
- const strict = Boolean(options?.strict);
828
- render_text(root, 0, lines, /* @__PURE__ */ new Set(), strict);
829
- return lines.join("\n");
830
- }
831
- function describe_json(root, options) {
832
- const strict = Boolean(options?.strict);
833
- return render_json(root, /* @__PURE__ */ new Set(), strict);
834
- }
835
- const describe = Object.assign(describe_text, { json: describe_json });
836
- function render_text(node, depth, lines, path, strict) {
837
- const prefix = INDENT.repeat(depth);
838
- if (path.has(node)) {
839
- if (strict) throw new describe_cycle_error(node.id);
840
- lines.push(`${prefix}<cycle>(${node.id})`);
841
- return;
842
- }
843
- path.add(node);
844
- try {
845
- const display = node.config?.["display_name"];
846
- const label = typeof display === "string" && display.length > 0 ? display : node.kind;
847
- lines.push(`${prefix}${label}(${node.id})`);
848
- if (node.config) for (const [key, value] of Object.entries(node.config)) {
849
- if (key === "display_name") continue;
850
- lines.push(`${prefix}${INDENT}${key}: ${render_value_text(value, path, strict)}`);
851
- }
852
- if (node.children && node.children.length > 0) for (const child of node.children) render_text(child, depth + 1, lines, path, strict);
853
- } finally {
854
- path.delete(node);
855
- }
856
- }
857
- function render_value_text(value, path, strict) {
858
- if (typeof value === "function") {
859
- const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
860
- return name ? `<fn:${name}>` : "<fn>";
861
- }
862
- if (value === null) return "null";
863
- if (value === void 0) return "undefined";
864
- if (is_zod_schema(value)) return "<schema>";
865
- if (is_step$1(value)) {
866
- if (path.has(value)) {
867
- if (strict) throw new describe_cycle_error(value.id);
868
- return `<cycle>(${value.id})`;
869
- }
870
- return `${value.kind}(${value.id})`;
871
- }
872
- if (Array.isArray(value)) return `[${value.map((item) => render_value_text(item, path, strict)).join(", ")}]`;
873
- if (typeof value === "object") return `{ ${Object.entries({ ...value }).map(([k, v]) => `${k}: ${render_value_text(v, path, strict)}`).join(", ")} }`;
874
- if (typeof value === "string") return JSON.stringify(value);
875
- if (typeof value === "bigint") return `${value.toString()}n`;
876
- if (typeof value === "symbol") return value.toString();
877
- if (typeof value === "number" || typeof value === "boolean") return String(value);
878
- return JSON.stringify(value);
879
- }
880
- function render_json(node, path, strict) {
881
- if (path.has(node)) {
882
- if (strict) throw new describe_cycle_error(node.id);
883
- return {
884
- kind: "<cycle>",
885
- id: node.id
886
- };
887
- }
888
- path.add(node);
889
- try {
890
- const result = {
891
- kind: node.kind,
892
- id: node.id
893
- };
894
- if (node.config) {
895
- const config = {};
896
- for (const [key, value] of Object.entries(node.config)) config[key] = render_value_json(value, path, strict);
897
- result.config = config;
898
- }
899
- if (node.children && node.children.length > 0) result.children = node.children.map((child) => render_json(child, path, strict));
900
- if (node.meta) result.meta = node.meta;
901
- return result;
902
- } finally {
903
- path.delete(node);
904
- }
905
- }
906
- function render_value_json(value, path, strict) {
907
- if (typeof value === "function") {
908
- const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
909
- return name ? {
910
- kind: "<fn>",
911
- name
912
- } : { kind: "<fn>" };
913
- }
914
- if (value === null) return null;
915
- if (value === void 0) return null;
916
- if (is_zod_schema(value)) return { kind: "<schema>" };
917
- if (is_step$1(value)) {
918
- if (path.has(value)) {
919
- if (strict) throw new describe_cycle_error(value.id);
920
- return {
921
- kind: "<cycle>",
922
- id: value.id
923
- };
924
- }
925
- return {
926
- kind: value.kind,
927
- id: value.id
928
- };
929
- }
930
- if (Array.isArray(value)) return value.map((item) => render_value_json(item, path, strict));
931
- if (typeof value === "object") {
932
- const out = {};
933
- for (const [k, v] of Object.entries({ ...value })) out[k] = render_value_json(v, path, strict);
934
- return out;
935
- }
936
- if (typeof value === "string") return value;
937
- if (typeof value === "number" || typeof value === "boolean") return value;
938
- if (typeof value === "bigint") return `${value.toString()}n`;
939
- if (typeof value === "symbol") return value.toString();
940
- return JSON.stringify(value);
941
- }
942
- function is_step$1(value) {
943
- if (typeof value !== "object" || value === null) return false;
944
- if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
945
- const { id, kind, run } = value;
946
- return typeof id === "string" && typeof kind === "string" && typeof run === "function";
947
- }
948
- function is_zod_schema(value) {
949
- if (typeof value !== "object" || value === null) return false;
950
- return "_zod" in value || "_def" in value;
951
- }
952
- //#endregion
953
- //#region src/core/sequence.ts
954
- /**
955
- * sequence: chain child outputs.
956
- *
957
- * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence
958
- * is passed to the first child; each subsequent child receives the previous
959
- * child's output. The composer returns the last child's output.
960
- *
961
- * See spec.md §5.2 and §6.1.
962
- */
963
- let sequence_counter = 0;
964
- function next_id$10() {
965
- sequence_counter += 1;
966
- return `sequence_${sequence_counter}`;
967
- }
968
- function sequence(children, options) {
969
- const id = next_id$10();
970
- const children_ref = children;
971
- const run_fn = async (input, ctx) => {
972
- let acc = input;
973
- for (const child of children_ref) {
974
- throw_if_aborted$2(ctx);
975
- acc = await dispatch_step(child, acc, ctx);
976
- }
977
- return acc;
978
- };
979
- const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
980
- return {
981
- id,
982
- kind: "sequence",
983
- children,
984
- ...config_meta ? { config: config_meta } : {},
985
- run: run_fn
986
- };
987
- }
988
- register_traced_kind("sequence");
989
- //#endregion
990
- //#region src/core/parallel.ts
991
- /**
992
- * parallel: concurrent execution of named children.
993
- *
994
- * `parallel({ a, b })` runs a and b concurrently with the same input. Output
995
- * is an object keyed by the child name; all children must accept the same
996
- * input type.
997
- *
998
- * Cancellation (constraints.md §5.1, spec.md §6.8): each child runs with a
999
- * composed abort signal — `AbortSignal.any([ctx.abort, child_local])`. On
1000
- * abort the composer awaits all in-flight children (success, failure, or
1001
- * aborted) before rethrowing `ctx.abort.reason`. This matches the
1002
- * "agent-pattern" composer contract in spec.md §6.8.
1003
- *
1004
- * When several children fail, a `suspended_error` is preferred over an
1005
- * application error so a human-approval gate inside a branch stays resumable
1006
- * rather than being masked by a sibling's failure. Otherwise the first error
1007
- * in declared order propagates.
1008
- */
1009
- let parallel_counter = 0;
1010
- function next_id$9() {
1011
- parallel_counter += 1;
1012
- return `parallel_${parallel_counter}`;
1013
- }
1014
- function parallel(members, options) {
1015
- const id = next_id$9();
1016
- const entries = Object.entries(members);
1017
- const child_list = entries.map(([, s]) => s);
1018
- const keys = entries.map(([k]) => k);
1019
- const run_fn = async (input, ctx) => {
1020
- const controllers = entries.map(() => new AbortController());
1021
- const on_parent_abort = () => {
1022
- for (const c of controllers) c.abort(ctx.abort.reason);
1023
- };
1024
- if (ctx.abort.aborted) on_parent_abort();
1025
- else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
1026
- try {
1027
- const settled = await Promise.all(entries.map(async ([key, child], idx) => {
1028
- const local = controllers[idx];
1029
- if (!local) throw new Error("parallel: missing controller");
1030
- const composed = AbortSignal.any([ctx.abort, local.signal]);
1031
- const child_ctx = {
1032
- ...ctx,
1033
- abort: composed
1034
- };
1035
- try {
1036
- return {
1037
- status: "ok",
1038
- key,
1039
- value: await dispatch_step(child, input, child_ctx)
1040
- };
1041
- } catch (err) {
1042
- return {
1043
- status: "err",
1044
- key,
1045
- err
1046
- };
1047
- }
1048
- }));
1049
- if (ctx.abort.aborted) {
1050
- const reason = ctx.abort.reason;
1051
- throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1052
- }
1053
- let first_err;
1054
- let has_err = false;
1055
- let suspended;
1056
- let has_suspended = false;
1057
- for (const s of settled) {
1058
- if (s.status !== "err") continue;
1059
- if (!has_err) {
1060
- first_err = s.err;
1061
- has_err = true;
1062
- }
1063
- if (!has_suspended && s.err instanceof suspended_error) {
1064
- suspended = s.err;
1065
- has_suspended = true;
1066
- }
1067
- }
1068
- if (has_suspended) throw suspended;
1069
- if (has_err) throw first_err;
1070
- const out = {};
1071
- for (const s of settled) if (s.status === "ok") out[s.key] = s.value;
1072
- return out;
1073
- } finally {
1074
- ctx.abort.removeEventListener("abort", on_parent_abort);
1075
- }
1076
- };
1077
- const config_meta = { keys };
1078
- if (options?.name !== void 0) config_meta["display_name"] = options.name;
1079
- return {
1080
- id,
1081
- kind: "parallel",
1082
- children: child_list,
1083
- config: config_meta,
1084
- run: run_fn
1085
- };
1086
- }
1087
- register_traced_kind("parallel");
1088
- //#endregion
1089
- //#region src/core/branch.ts
1090
- /**
1091
- * branch: conditional routing.
1092
- *
1093
- * `branch({ when, then, otherwise })` evaluates `when(input)`; if truthy, runs
1094
- * `then`, else runs `otherwise`. Both branches must return the same output
1095
- * type.
1096
- *
1097
- * See spec.md §5.4.
1098
- */
1099
- let branch_counter = 0;
1100
- function next_id$8() {
1101
- branch_counter += 1;
1102
- return `branch_${branch_counter}`;
1103
- }
1104
- function branch(config) {
1105
- const id = next_id$8();
1106
- const { when, then: then_step, otherwise: otherwise_step, name } = config;
1107
- const run_fn = async (input, ctx) => {
1108
- return dispatch_step(await when(input) ? then_step : otherwise_step, input, ctx);
1109
- };
1110
- const config_meta = {
1111
- when,
1112
- then: then_step,
1113
- otherwise: otherwise_step
1114
- };
1115
- if (name !== void 0) config_meta["display_name"] = name;
1116
- return {
1117
- id,
1118
- kind: "branch",
1119
- children: [then_step, otherwise_step],
1120
- config: config_meta,
1121
- run: run_fn
1122
- };
1123
- }
1124
- register_traced_kind("branch");
1125
- //#endregion
1126
- //#region src/core/map.ts
1127
- /**
1128
- * map: per-item execution.
1129
- *
1130
- * `map({ items, do, concurrency? })` extracts an array via `items(input)`,
1131
- * runs `do` once per element, returns an array in the same order as inputs.
1132
- * `concurrency` caps simultaneous in-flight items; omitted means full
1133
- * parallelism.
1134
- *
1135
- * Cancellation (constraints.md §5.1, spec.md §6.8): each in-flight item runs
1136
- * with a composed abort signal via `AbortSignal.any([ctx.abort, child_local])`.
1137
- * On abort no new items start. The composer awaits all in-flight items before
1138
- * rethrowing `ctx.abort.reason`.
1139
- */
1140
- let map_counter = 0;
1141
- function next_id$7() {
1142
- map_counter += 1;
1143
- return `map_${map_counter}`;
1144
- }
1145
- function map(config) {
1146
- const id = next_id$7();
1147
- const { items, do: per_item, concurrency, name } = config;
1148
- const run_fn = async (input, ctx) => {
1149
- const list = await items(input);
1150
- if (list.length === 0) return [];
1151
- const results = Array.from({ length: list.length });
1152
- const limit = concurrency === void 0 ? list.length : Math.max(1, concurrency);
1153
- const controllers = [];
1154
- const on_parent_abort = () => {
1155
- for (const c of controllers) c.abort(ctx.abort.reason);
1156
- };
1157
- if (ctx.abort.aborted) on_parent_abort();
1158
- else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
1159
- let cursor = 0;
1160
- let worker_error = void 0;
1161
- const run_one = async (idx) => {
1162
- const local = new AbortController();
1163
- controllers.push(local);
1164
- const composed = AbortSignal.any([ctx.abort, local.signal]);
1165
- const child_ctx = {
1166
- ...ctx,
1167
- abort: composed
1168
- };
1169
- const item_value = list[idx];
1170
- results[idx] = await dispatch_step(per_item, item_value, child_ctx);
1171
- };
1172
- const worker = async () => {
1173
- while (true) {
1174
- if (ctx.abort.aborted || worker_error !== void 0) return;
1175
- const idx = cursor;
1176
- cursor += 1;
1177
- if (idx >= list.length) return;
1178
- try {
1179
- await run_one(idx);
1180
- } catch (err) {
1181
- if (worker_error === void 0) worker_error = err;
1182
- return;
1183
- }
1184
- }
1185
- };
1186
- try {
1187
- const worker_count = Math.min(limit, list.length);
1188
- const workers = [];
1189
- for (let w = 0; w < worker_count; w += 1) workers.push(worker());
1190
- await Promise.all(workers);
1191
- if (ctx.abort.aborted) {
1192
- const reason = ctx.abort.reason;
1193
- throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1194
- }
1195
- if (worker_error !== void 0) throw worker_error;
1196
- return results;
1197
- } finally {
1198
- ctx.abort.removeEventListener("abort", on_parent_abort);
1199
- }
1200
- };
1201
- const config_meta = { items };
1202
- if (concurrency !== void 0) config_meta["concurrency"] = concurrency;
1203
- if (name !== void 0) config_meta["display_name"] = name;
1204
- return {
1205
- id,
1206
- kind: "map",
1207
- children: [per_item],
1208
- config: config_meta,
1209
- run: run_fn
1210
- };
1211
- }
1212
- register_traced_kind("map");
1213
- //#endregion
1214
- //#region src/core/pipe.ts
1215
- /**
1216
- * pipe: transform output.
1217
- *
1218
- * `pipe(inner, fn)` runs `inner`, passes its output to `fn`, returns `fn`'s
1219
- * result. Use for shape adaptation when composing heterogeneous steps.
1220
- *
1221
- * See spec.md §5.6.
1222
- */
1223
- let pipe_counter = 0;
1224
- function next_id$6() {
1225
- pipe_counter += 1;
1226
- return `pipe_${pipe_counter}`;
1227
- }
1228
- function pipe(inner, fn, options) {
1229
- const id = next_id$6();
1230
- const run_fn = async (input, ctx) => {
1231
- return fn(await dispatch_step(inner, input, ctx));
1232
- };
1233
- const config_meta = { fn };
1234
- if (options?.name !== void 0) config_meta["display_name"] = options.name;
1235
- return {
1236
- id,
1237
- kind: "pipe",
1238
- children: [inner],
1239
- config: config_meta,
1240
- run: run_fn
1241
- };
1242
- }
1243
- register_traced_kind("pipe");
1244
- //#endregion
1245
- //#region src/core/retry.ts
1246
- /**
1247
- * retry: re-run on failure.
1248
- *
1249
- * `retry(inner, { max_attempts, backoff_ms?, on_error? })` runs `inner`. If it
1250
- * throws an application error, retries up to `max_attempts - 1` more times with
1251
- * exponential backoff (`backoff_ms * 2^(attempt-1)`). `on_error` is called on
1252
- * every such failure. The last error is rethrown if all attempts fail.
1253
- *
1254
- * Control-flow signals (`suspended_error`, `aborted_error`) are not failures:
1255
- * they propagate immediately without consuming an attempt, firing `on_error`,
1256
- * or scheduling a backoff. A suspend's `on()` side effect therefore runs once
1257
- * per run, not once per attempt.
1258
- *
1259
- * Cancellation / cleanup (constraints.md §5.2, spec.md §6.8): cleanup handlers
1260
- * registered by the inner step accumulate across attempts. The parent
1261
- * `ctx.abort` is honored between attempts — a pending abort short-circuits
1262
- * the backoff and propagates. See spec.md §5.7 and §9 F11.
1263
- */
1264
- const DEFAULT_BACKOFF_MS = 1e3;
1265
- let retry_counter = 0;
1266
- function next_id$5() {
1267
- retry_counter += 1;
1268
- return `retry_${retry_counter}`;
1269
- }
1270
- async function abortable_wait(ms, ctx) {
1271
- if (ms <= 0) return;
1272
- await new Promise((resolve, reject) => {
1273
- if (ctx.abort.aborted) {
1274
- const reason = ctx.abort.reason;
1275
- reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
1276
- return;
1277
- }
1278
- const timer = setTimeout(() => {
1279
- ctx.abort.removeEventListener("abort", on_abort);
1280
- resolve();
1281
- }, ms);
1282
- const on_abort = () => {
1283
- clearTimeout(timer);
1284
- const reason = ctx.abort.reason;
1285
- reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
1286
- };
1287
- ctx.abort.addEventListener("abort", on_abort, { once: true });
1288
- });
1289
- }
1290
- function retry(inner, config) {
1291
- const id = next_id$5();
1292
- const max_attempts = Math.max(1, Math.floor(config.max_attempts));
1293
- const backoff_ms = config.backoff_ms ?? DEFAULT_BACKOFF_MS;
1294
- const on_error = config.on_error;
1295
- const run_fn = async (input, ctx) => {
1296
- let last_err = void 0;
1297
- for (let attempt = 1; attempt <= max_attempts; attempt += 1) {
1298
- if (ctx.abort.aborted) {
1299
- const reason = ctx.abort.reason;
1300
- throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1301
- }
1302
- try {
1303
- return await dispatch_step(inner, input, ctx);
1304
- } catch (err) {
1305
- if (is_control_flow_error(err)) throw err;
1306
- last_err = err;
1307
- if (on_error) on_error(err, attempt);
1308
- if (attempt >= max_attempts) break;
1309
- await abortable_wait(backoff_ms * 2 ** (attempt - 1), ctx);
1310
- }
1311
- }
1312
- throw last_err;
1313
- };
1314
- const config_meta = {
1315
- max_attempts,
1316
- backoff_ms
1317
- };
1318
- if (on_error) config_meta["on_error"] = on_error;
1319
- if (config.name !== void 0) config_meta["display_name"] = config.name;
1320
- return {
1321
- id,
1322
- kind: "retry",
1323
- children: [inner],
1324
- config: config_meta,
1325
- run: run_fn
1326
- };
1327
- }
1328
- register_traced_kind("retry");
1329
- //#endregion
1330
- //#region src/core/fallback.ts
1331
- /**
1332
- * fallback: primary-or-backup.
1333
- *
1334
- * `fallback(primary, backup)` runs `primary`. If it throws an application
1335
- * error, runs `backup` with the same input. If `backup` also throws, the
1336
- * `backup` error propagates. Control-flow signals (`suspended_error`,
1337
- * `aborted_error`) are not failures: they propagate instead of triggering the
1338
- * backup, so a human-approval gate is never silently bypassed and the backup
1339
- * never runs under an aborted context. See spec.md §5.8.
1340
- */
1341
- let fallback_counter = 0;
1342
- function next_id$4() {
1343
- fallback_counter += 1;
1344
- return `fallback_${fallback_counter}`;
1345
- }
1346
- function fallback(primary, backup, options) {
1347
- const id = next_id$4();
1348
- const run_fn = async (input, ctx) => {
1349
- try {
1350
- return await dispatch_step(primary, input, ctx);
1351
- } catch (err) {
1352
- if (is_control_flow_error(err)) throw err;
1353
- return dispatch_step(backup, input, ctx);
1354
- }
1355
- };
1356
- const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
1357
- return {
1358
- id,
1359
- kind: "fallback",
1360
- children: [primary, backup],
1361
- ...config_meta ? { config: config_meta } : {},
1362
- run: run_fn
1363
- };
1364
- }
1365
- register_traced_kind("fallback");
1366
- //#endregion
1367
- //#region src/core/timeout.ts
1368
- /**
1369
- * timeout: bound execution.
1370
- *
1371
- * `timeout(inner, ms)` runs `inner` with a composed `AbortSignal` that fires
1372
- * at `ms` milliseconds. If the inner step does not complete in time, throws
1373
- * `timeout_error`. The inner step is responsible for honoring `ctx.abort`;
1374
- * a step that ignores the signal still triggers `timeout_error` on schedule
1375
- * but continues running in the background (spec.md §9 F4).
1376
- *
1377
- * Cancellation (constraints.md §5.1, spec.md §6.8): the inner step runs with
1378
- * `AbortSignal.any([ctx.abort, timeout_local])`. On timer expiry, the local
1379
- * controller aborts with a `timeout_error` as its reason; on parent abort
1380
- * the parent reason flows through. The timer is always cleared in a finally
1381
- * block so it does not leak across retries.
1382
- */
1383
- let timeout_counter = 0;
1384
- function next_id$3() {
1385
- timeout_counter += 1;
1386
- return `timeout_${timeout_counter}`;
1387
- }
1388
- function timeout(inner, ms, options) {
1389
- const id = next_id$3();
1390
- const run_fn = async (input, ctx) => {
1391
- const local = new AbortController();
1392
- const composed = AbortSignal.any([ctx.abort, local.signal]);
1393
- const child_ctx = {
1394
- ...ctx,
1395
- abort: composed
1396
- };
1397
- let timed_out = false;
1398
- const timer = setTimeout(() => {
1399
- timed_out = true;
1400
- local.abort(new timeout_error(`timeout after ${ms}ms`, ms));
1401
- }, ms);
1402
- const deadline = new Promise((_, reject) => {
1403
- const on_local_abort = () => {
1404
- if (timed_out) reject(new timeout_error(`timeout after ${ms}ms`, ms));
1405
- else {
1406
- const reason = ctx.abort.reason;
1407
- reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
1408
- }
1409
- };
1410
- if (composed.aborted) {
1411
- on_local_abort();
1412
- return;
1413
- }
1414
- composed.addEventListener("abort", on_local_abort, { once: true });
1415
- });
1416
- try {
1417
- return await Promise.race([dispatch_step(inner, input, child_ctx), deadline]);
1418
- } finally {
1419
- clearTimeout(timer);
1420
- }
1421
- };
1422
- const config_meta = { ms };
1423
- if (options?.name !== void 0) config_meta["display_name"] = options.name;
1424
- return {
1425
- id,
1426
- kind: "timeout",
1427
- children: [inner],
1428
- config: config_meta,
1429
- run: run_fn
1430
- };
1431
- }
1432
- register_traced_kind("timeout");
1433
- //#endregion
1434
- //#region src/core/loop.ts
1435
- /**
1436
- * loop: bounded iteration with carry-state.
1437
- *
1438
- * `loop({ init, body, guard?, finish, max_rounds, name? })` runs `body` up to
1439
- * `max_rounds` times, threading `state` through each iteration. After every
1440
- * `body` call, an optional `guard` step inspects (and may transform) the state
1441
- * and decides whether to stop. When `guard.stop` is true, the loop exits
1442
- * "converged"; otherwise it continues until `max_rounds`. `finish` projects
1443
- * the final state to the loop's output value.
1444
- *
1445
- * Non-convergence is data, not error: when `max_rounds` is exhausted without
1446
- * `guard` returning stop, the loop returns `{ value, converged: false, rounds }`.
1447
- * This matches the existing convention from adversarial/consensus.
1448
- *
1449
- * Cancellation: between rounds the parent `ctx.abort` is honored — a pending
1450
- * abort short-circuits and propagates `ctx.abort.reason`. The body and guard
1451
- * receive the parent context unchanged; their own dispatch routes already
1452
- * thread cancellation per the runner contract.
1453
- */
1454
- let loop_counter = 0;
1455
- function next_id$2(name) {
1456
- loop_counter += 1;
1457
- return `${name ?? "loop"}_${loop_counter}`;
1458
- }
1459
- function loop(config) {
1460
- const { init, body, guard, finish, name } = config;
1461
- const rounds_limit = Math.max(1, Math.floor(config.max_rounds));
1462
- const id = next_id$2(name);
1463
- const run_fn = async (input, ctx) => {
1464
- let state = init(input);
1465
- let round = 0;
1466
- let converged = false;
1467
- while (round < rounds_limit) {
1468
- throw_if_aborted$2(ctx);
1469
- round += 1;
1470
- state = await dispatch_step(body, state, ctx);
1471
- if (guard) {
1472
- throw_if_aborted$2(ctx);
1473
- const guard_out = await dispatch_step(guard, state, ctx);
1474
- state = guard_out.state;
1475
- if (guard_out.stop) {
1476
- converged = true;
1477
- break;
1478
- }
1479
- }
1480
- }
1481
- return {
1482
- value: finish(state, round),
1483
- converged,
1484
- rounds: round
1485
- };
1486
- };
1487
- const config_meta = { max_rounds: rounds_limit };
1488
- if (name !== void 0) config_meta["display_name"] = name;
1489
- return {
1490
- id,
1491
- kind: "loop",
1492
- children: guard ? [body, guard] : [body],
1493
- config: config_meta,
1494
- run: run_fn
1495
- };
1496
- }
1497
- register_traced_kind("loop");
1498
- //#endregion
1499
- //#region src/core/compose.ts
1500
- /**
1501
- * compose: name a composite step.
1502
- *
1503
- * `compose(name, inner)` wraps any step and labels its trajectory span with
1504
- * `name`. The inner step's own span (e.g. a `sequence`) appears as a child of
1505
- * the compose span — the implementation tree is preserved while the user's
1506
- * intent ("this whole thing is an ensemble") is surfaced in observability.
1507
- *
1508
- * Used by the composites package to make built-in patterns appear under
1509
- * their familiar names, and available to library consumers who want their own
1510
- * named composites to show up in logs as first-class components.
1511
- *
1512
- * The primitive's `kind` is always `'compose'`; the user-supplied label lives
1513
- * in `config.display_name` and is the span name the dispatcher opens.
1514
- */
1515
- let compose_counter = 0;
1516
- function next_id$1(name) {
1517
- compose_counter += 1;
1518
- return `${name}_${compose_counter}`;
1519
- }
1520
- function compose(name, inner) {
1521
- if (typeof name !== "string" || name.length === 0) throw new TypeError("compose(name, inner): name must be a non-empty string");
1522
- const id = next_id$1(name);
1523
- const run_fn = (input, ctx) => dispatch_step(inner, input, ctx);
1524
- return {
1525
- id,
1526
- kind: "compose",
1527
- children: [inner],
1528
- config: { display_name: name },
1529
- run: run_fn
1530
- };
1531
- }
1532
- register_traced_kind("compose");
1533
- //#endregion
1534
- //#region src/core/checkpoint.ts
1535
- /**
1536
- * checkpoint: persist and resume.
1537
- *
1538
- * `checkpoint(inner, { key })` checks a persistent store for a completed
1539
- * result at `key` before running `inner`. On a hit, returns the stored
1540
- * value. On a miss, runs `inner`, persists its result at `key`, and returns
1541
- * it. Corrupted reads (store throws on `get`) are treated as a miss.
1542
- *
1543
- * Fail-fast (constraints.md §7 invariant 8, spec.md §9 F6): wrapping an
1544
- * anonymous inner step throws synchronously at construction time with the
1545
- * message `checkpoint requires a named step; got anonymous`.
1546
- *
1547
- * See spec.md §5.14, §6.3.
1548
- */
1549
- let checkpoint_counter = 0;
1550
- function next_id() {
1551
- checkpoint_counter += 1;
1552
- return `checkpoint_${checkpoint_counter}`;
1553
- }
1554
- function checkpoint(inner, config) {
1555
- if (inner.anonymous === true) throw new Error("checkpoint requires a named step; got anonymous");
1556
- const id = next_id();
1557
- const key_spec = config.key;
1558
- const run_fn = async (input, ctx) => {
1559
- const key = typeof key_spec === "function" ? key_spec(input) : key_spec;
1560
- const store = ctx.checkpoint_store;
1561
- if (store) {
1562
- let cached = void 0;
1563
- let hit = false;
1564
- try {
1565
- cached = await store.get(key);
1566
- hit = cached !== null && cached !== void 0;
1567
- } catch {
1568
- hit = false;
1569
- }
1570
- if (hit) return cached;
1571
- }
1572
- const result = await dispatch_step(inner, input, ctx);
1573
- if (store) await store.set(key, result);
1574
- return result;
1575
- };
1576
- const config_meta = { key: key_spec };
1577
- if (config.name !== void 0) config_meta["display_name"] = config.name;
1578
- return {
1579
- id,
1580
- kind: "checkpoint",
1581
- children: [inner],
1582
- config: config_meta,
1583
- run: run_fn
1584
- };
1585
- }
1586
- register_traced_kind("checkpoint");
1587
- //#endregion
1588
- //#region src/core/suspend.ts
1589
- /**
1590
- * suspend: human-in-the-loop pause.
1591
- *
1592
- * `suspend({ id, on, resume_schema, combine })` pauses a flow waiting on
1593
- * external input (a notification, an approval, an uploaded file). On first
1594
- * encounter with no resume data, it calls `on(input, ctx)` (side effect) and
1595
- * throws `suspended_error` carrying the run state. On resume (re-invocation
1596
- * with `run_options.resume_data[id]` populated), the provided value is
1597
- * validated against `resume_schema` and passed to `combine(input, resume,
1598
- * ctx)`; the result is returned. Invalid resume data throws
1599
- * `resume_validation_error` built from zod 4's `.flatten()` (spec.md §9 F5).
1600
- *
1601
- * See spec.md §5.15, §6.4.
1602
- */
1603
- function is_step(value) {
1604
- if (typeof value !== "object" || value === null) return false;
1605
- if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
1606
- const { id, kind, run } = value;
1607
- return typeof id === "string" && typeof kind === "string" && typeof run === "function";
1608
- }
1609
- function suspend(config) {
1610
- const suspend_id = config.id;
1611
- const on_fn = config.on;
1612
- const resume_schema = config.resume_schema;
1613
- const combine_fn = config.combine;
1614
- const run_fn = async (input, ctx) => {
1615
- const resume_value = ctx.resume_data?.[suspend_id];
1616
- if (resume_value === void 0) {
1617
- await on_fn(input, ctx);
1618
- throw new suspended_error(suspend_id, { input });
1619
- }
1620
- const parsed = resume_schema.safeParse(resume_value);
1621
- if (!parsed.success) {
1622
- const issues = z.flattenError(parsed.error);
1623
- throw new resume_validation_error(`resume data for ${suspend_id} failed validation`, issues);
1624
- }
1625
- const result = await combine_fn(input, parsed.data, ctx);
1626
- if (is_step(result)) return dispatch_step(result, input, ctx);
1627
- return result;
1628
- };
1629
- const config_meta = { id: suspend_id };
1630
- if (config.name !== void 0) config_meta["display_name"] = config.name;
1631
- return {
1632
- id: suspend_id,
1633
- kind: "suspend",
1634
- config: config_meta,
1635
- run: run_fn
1636
- };
1637
- }
1638
- register_traced_kind("suspend");
1639
- //#endregion
1640
- //#region src/core/scope.ts
1641
- /**
1642
- * scope / stash / use: named state.
1643
- *
1644
- * `scope([...children])` introduces a scope-local `Map<string, unknown>` and
1645
- * runs its children in order, chaining outputs like `sequence`. `stash(key,
1646
- * source)` runs `source`, writes its output to the scope's state at `key`,
1647
- * and passes the value through. `use(keys, fn)` reads the named values from
1648
- * state and runs `fn` with the projection. Inner scopes inherit outer state;
1649
- * writes only affect the inner map.
1650
- *
1651
- * Using `stash` or `use` outside a `scope` is a runtime error with a clear
1652
- * message (spec.md §9 F1).
1653
- *
1654
- * See spec.md §5.16.
1655
- */
1656
- const scope_states = /* @__PURE__ */ new WeakSet();
1657
- function is_scope_state(state) {
1658
- return scope_states.has(state);
1659
- }
1660
- let scope_counter = 0;
1661
- let stash_counter = 0;
1662
- let use_counter = 0;
1663
- function next_scope_id() {
1664
- scope_counter += 1;
1665
- return `scope_${scope_counter}`;
1666
- }
1667
- function next_stash_id() {
1668
- stash_counter += 1;
1669
- return `stash_${stash_counter}`;
1670
- }
1671
- function next_use_id() {
1672
- use_counter += 1;
1673
- return `use_${use_counter}`;
1674
- }
1675
- function scope(children, options) {
1676
- const id = next_scope_id();
1677
- const children_ref = children;
1678
- const run_fn = async (input, ctx) => {
1679
- const local = new Map(ctx.state);
1680
- scope_states.add(local);
1681
- const scope_ctx = {
1682
- ...ctx,
1683
- state: local
1684
- };
1685
- let acc = input;
1686
- for (const child of children_ref) {
1687
- throw_if_aborted$2(scope_ctx);
1688
- acc = await dispatch_step(child, acc, scope_ctx);
1689
- }
1690
- return acc;
1691
- };
1692
- const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
1693
- return {
1694
- id,
1695
- kind: "scope",
1696
- children,
1697
- ...config_meta ? { config: config_meta } : {},
1698
- run: run_fn
1699
- };
1700
- }
1701
- function stash(key, source, options) {
1702
- const id = next_stash_id();
1703
- const run_fn = async (input, ctx) => {
1704
- if (!is_scope_state(ctx.state)) throw new Error("stash() may only appear inside scope(); got: top-level");
1705
- const value = await dispatch_step(source, input, ctx);
1706
- ctx.state.set(key, value);
1707
- return value;
1708
- };
1709
- const config_meta = { key };
1710
- if (options?.name !== void 0) config_meta["display_name"] = options.name;
1711
- return {
1712
- id,
1713
- kind: "stash",
1714
- children: [source],
1715
- config: config_meta,
1716
- run: run_fn
1717
- };
1718
- }
1719
- function use(keys, fn, options) {
1720
- const id = next_use_id();
1721
- const run_fn = async (input, ctx) => {
1722
- if (!is_scope_state(ctx.state)) throw new Error("use() may only appear inside scope(); got: top-level");
1723
- const projection = {};
1724
- for (const k of keys) projection[k] = ctx.state.get(k);
1725
- return fn(projection, input, ctx);
1726
- };
1727
- const config_meta = { keys: [...keys] };
1728
- if (options?.name !== void 0) config_meta["display_name"] = options.name;
1729
- return {
1730
- id,
1731
- kind: "use",
1732
- config: config_meta,
1733
- run: run_fn
1734
- };
1735
- }
1736
- register_traced_kind("scope");
1737
- register_traced_kind("stash");
1738
- register_traced_kind("use");
1739
- //#endregion
1740
- //#region src/core/step_kinds.ts
1741
- /**
1742
- * Closed registry of every `Step.kind` produced by the composition layer.
1743
- *
1744
- * Studio (and any other consumer that needs to enumerate primitives — palette,
1745
- * docs, code generation) can rely on this being the exhaustive set. New
1746
- * primitives must add their kind here. The `step_kinds_cover_runner` contract
1747
- * test in `step_kinds.test.ts` asserts every dispatch handler corresponds to a
1748
- * kind listed here.
1749
- */
1750
- const STEP_KINDS = [
1751
- "step",
1752
- "sequence",
1753
- "parallel",
1754
- "branch",
1755
- "map",
1756
- "pipe",
1757
- "retry",
1758
- "fallback",
1759
- "timeout",
1760
- "loop",
1761
- "compose",
1762
- "adversarial",
1763
- "ensemble",
1764
- "tournament",
1765
- "consensus",
1766
- "checkpoint",
1767
- "suspend",
1768
- "scope",
1769
- "stash",
1770
- "use"
1771
- ];
1772
- function is_step_kind(value) {
1773
- return typeof value === "string" && STEP_KINDS.includes(value);
1774
- }
1775
- //#endregion
1776
- //#region src/core/trajectory.ts
1777
- /**
1778
- * Wire-format schema for trajectory events.
1779
- *
1780
- * `TrajectoryEvent` (in `types.ts`) is the loose internal type — any code that
1781
- * calls `trajectory.record(event)` or `start_span(name, meta)` produces values
1782
- * conforming to it. This file defines the *narrower* shapes that the studio
1783
- * (and any other downstream consumer) can parse out of the wire stream:
1784
- *
1785
- * span_start — composer span open
1786
- * span_end — composer span close
1787
- * emit — user-emitted event from inside a step (ctx.emit)
1788
- * <other> — falls through `custom_event_schema`, which only requires a
1789
- * string `kind` and tolerates any extra fields
1790
- *
1791
- * The discriminated union is **ordered**: well-known shapes are tried before
1792
- * the permissive `custom` schema, so a `{ kind: 'span_start', ... }` event
1793
- * always parses as `SpanStartEvent`, never as `CustomTrajectoryEvent`.
1794
- *
1795
- * Every well-known schema and `custom_event_schema` use `.passthrough()` so
1796
- * additional fields (e.g. `run_id`, `id`, provider-specific metadata) survive
1797
- * a parse / re-serialize round-trip without loss.
1798
- */
1799
- const span_start_event_schema = z.object({
1800
- kind: z.literal("span_start"),
1801
- span_id: z.string(),
1802
- name: z.string()
1803
- }).passthrough();
1804
- const span_end_event_schema = z.object({
1805
- kind: z.literal("span_end"),
1806
- span_id: z.string()
1807
- }).passthrough();
1808
- const emit_event_schema = z.object({ kind: z.literal("emit") }).passthrough();
1809
- const custom_event_schema = z.object({ kind: z.string() }).passthrough();
1810
- const trajectory_event_schema = z.union([
1811
- span_start_event_schema,
1812
- span_end_event_schema,
1813
- emit_event_schema,
1814
- custom_event_schema
1815
- ]);
1816
- //#endregion
1817
- //#region src/core/version.ts
1818
- const version = "0.8.1";
1819
- //#endregion
1820
- //#region src/core/index.ts
1821
- /**
1822
- * Public surface for core.
1823
- *
1824
- * Side-effect imports ensure every composer registers itself with the runner
1825
- * at module load. Importing anything from `core` populates the
1826
- * dispatch table with the core primitives. Built-in composites
1827
- * (adversarial, ensemble, tournament, consensus) live in composites
1828
- * and surface through the umbrella package.
1829
- */
1830
- const flow_schema = flow_schema_default;
1831
- //#endregion
1832
14
  //#region src/composites/adversarial.ts
1833
15
  /**
1834
16
  * adversarial: build-and-critique loop.
@@ -2681,11 +863,8 @@ function is_record(v) {
2681
863
  }
2682
864
  function deep_equal(a, b) {
2683
865
  if (a === b) return true;
2684
- if (a === null || b === null) return false;
2685
- if (typeof a !== typeof b) return false;
2686
- if (typeof a !== "object") return false;
2687
- if (Array.isArray(a) !== Array.isArray(b)) return false;
2688
- if (Array.isArray(a) && Array.isArray(b)) {
866
+ if (Array.isArray(a) || Array.isArray(b)) {
867
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
2689
868
  if (a.length !== b.length) return false;
2690
869
  for (let i = 0; i < a.length; i += 1) if (!deep_equal(a[i], b[i])) return false;
2691
870
  return true;
@@ -2795,7 +974,8 @@ function extract_json_object(text) {
2795
974
  *
2796
975
  * Baselines are plain JSON, written via `write_baseline` and read via
2797
976
  * `read_baseline`. They live wherever the caller decides — typically
2798
- * `bench/<flow>/baseline.json`, checked into git per spec/eval.md §3.
977
+ * `bench/<flow>/baseline.json`, checked into git per
978
+ * `research/explorations/2026-04-eval-surface.md` §3.
2799
979
  */
2800
980
  function regression_compare(current, baseline, options = {}) {
2801
981
  const score_threshold = options.score_threshold ?? 0;
@@ -2904,9 +1084,6 @@ function validate_report(value, path) {
2904
1084
  if (!Array.isArray(v.cases) || typeof v.summary !== "object" || v.summary === null) throw new Error(`baseline at ${path} missing cases/summary`);
2905
1085
  }
2906
1086
  //#endregion
2907
- //#region src/engine/version.ts
2908
- const version$1 = "0.8.1";
2909
- //#endregion
2910
1087
  //#region src/engine/pricing.ts
2911
1088
  const FREE_PROVIDERS = new Set(["ollama", "lmstudio"]);
2912
1089
  const DEFAULT_PRICING = Object.freeze({
@@ -3034,9 +1211,9 @@ var rate_limit_error = class extends Error {
3034
1211
  constructor(message, metadata = {}) {
3035
1212
  super(message);
3036
1213
  this.name = "rate_limit_error";
3037
- if (metadata.retry_after_ms !== void 0) this.retry_after_ms = metadata.retry_after_ms;
1214
+ this.retry_after_ms = metadata.retry_after_ms;
3038
1215
  this.attempts = metadata.attempts ?? 0;
3039
- if (metadata.status !== void 0) this.status = metadata.status;
1216
+ this.status = metadata.status;
3040
1217
  }
3041
1218
  };
3042
1219
  var provider_error = class extends Error {
@@ -3047,9 +1224,9 @@ var provider_error = class extends Error {
3047
1224
  constructor(message, metadata = {}) {
3048
1225
  super(message);
3049
1226
  this.name = "provider_error";
3050
- if (metadata.status !== void 0) this.status = metadata.status;
3051
- if (metadata.body !== void 0) this.body = metadata.body;
3052
- if (metadata.cause_kind !== void 0) this.cause_kind = metadata.cause_kind;
1227
+ this.status = metadata.status;
1228
+ this.body = metadata.body;
1229
+ this.cause_kind = metadata.cause_kind;
3053
1230
  }
3054
1231
  };
3055
1232
  var schema_validation_error = class extends Error {
@@ -3111,7 +1288,7 @@ var engine_config_error = class extends Error {
3111
1288
  constructor(message, provider) {
3112
1289
  super(message);
3113
1290
  this.name = "engine_config_error";
3114
- if (provider !== void 0) this.provider = provider;
1291
+ this.provider = provider;
3115
1292
  }
3116
1293
  };
3117
1294
  var on_chunk_error = class extends Error {
@@ -3151,8 +1328,8 @@ var claude_cli_error = class extends Error {
3151
1328
  super(message);
3152
1329
  this.name = "claude_cli_error";
3153
1330
  this.reason = reason;
3154
- if (metadata.status !== void 0) this.status = metadata.status;
3155
- if (metadata.stderr_snippet !== void 0) this.stderr_snippet = metadata.stderr_snippet;
1331
+ this.status = metadata.status;
1332
+ this.stderr_snippet = metadata.stderr_snippet;
3156
1333
  }
3157
1334
  };
3158
1335
  var provider_auth_error = class extends Error {
@@ -3163,7 +1340,7 @@ var provider_auth_error = class extends Error {
3163
1340
  super(message);
3164
1341
  this.name = "provider_auth_error";
3165
1342
  this.provider = provider;
3166
- if (metadata.refresh_command !== void 0) this.refresh_command = metadata.refresh_command;
1343
+ this.refresh_command = metadata.refresh_command;
3167
1344
  }
3168
1345
  };
3169
1346
  //#endregion
@@ -3449,13 +1626,7 @@ function translate_google_effort(effort) {
3449
1626
  };
3450
1627
  }
3451
1628
  function normalize_google_usage(raw) {
3452
- if (raw === void 0) return {
3453
- input_tokens: 0,
3454
- output_tokens: 0
3455
- };
3456
- const base = default_normalize_usage(raw);
3457
- if (base.cache_write_tokens === void 0) delete base.cache_write_tokens;
3458
- return base;
1629
+ return default_normalize_usage(raw);
3459
1630
  }
3460
1631
  const SUPPORTED$5 = new Set([
3461
1632
  "text",
@@ -3492,10 +1663,6 @@ function translate_ollama_effort(effort) {
3492
1663
  };
3493
1664
  }
3494
1665
  function normalize_ollama_usage(raw) {
3495
- if (raw === void 0) return {
3496
- input_tokens: 0,
3497
- output_tokens: 0
3498
- };
3499
1666
  const base = default_normalize_usage(raw);
3500
1667
  delete base.cached_input_tokens;
3501
1668
  delete base.cache_write_tokens;
@@ -3506,7 +1673,8 @@ const SUPPORTED$4 = new Set([
3506
1673
  "text",
3507
1674
  "tools",
3508
1675
  "schema",
3509
- "streaming"
1676
+ "streaming",
1677
+ "structured_output"
3510
1678
  ]);
3511
1679
  const create_ollama_adapter = (init) => {
3512
1680
  const base_url = typeof init.base_url === "string" ? init.base_url : "";
@@ -3531,10 +1699,6 @@ function translate_lmstudio_effort(effort) {
3531
1699
  };
3532
1700
  }
3533
1701
  function normalize_lmstudio_usage(raw) {
3534
- if (raw === void 0) return {
3535
- input_tokens: 0,
3536
- output_tokens: 0
3537
- };
3538
1702
  const base = default_normalize_usage(raw);
3539
1703
  delete base.cached_input_tokens;
3540
1704
  delete base.cache_write_tokens;
@@ -3545,7 +1709,8 @@ const SUPPORTED$3 = new Set([
3545
1709
  "text",
3546
1710
  "tools",
3547
1711
  "schema",
3548
- "streaming"
1712
+ "streaming",
1713
+ "structured_output"
3549
1714
  ]);
3550
1715
  const create_lmstudio_adapter = (init) => {
3551
1716
  const base_url = typeof init.base_url === "string" ? init.base_url : "";
@@ -3623,7 +1788,7 @@ const BEDROCK_THINKING_BUDGETS = {
3623
1788
  };
3624
1789
  function translate_bedrock_effort(effort) {
3625
1790
  const budget = BEDROCK_THINKING_BUDGETS[effort];
3626
- if (effort === "none" || budget === 0) return {
1791
+ if (budget === 0) return {
3627
1792
  provider_options: {},
3628
1793
  effort_ignored: false
3629
1794
  };
@@ -3969,9 +2134,9 @@ function create_spawn_runtime() {
3969
2134
  spawn_error = err;
3970
2135
  });
3971
2136
  const clear_all_timers = () => {
3972
- if (startup_timer !== void 0) clearTimeout(startup_timer);
3973
- if (stall_timer !== void 0) clearTimeout(stall_timer);
3974
- if (sigkill_timer !== void 0) clearTimeout(sigkill_timer);
2137
+ clearTimeout(startup_timer);
2138
+ clearTimeout(stall_timer);
2139
+ clearTimeout(sigkill_timer);
3975
2140
  startup_timer = void 0;
3976
2141
  stall_timer = void 0;
3977
2142
  sigkill_timer = void 0;
@@ -3997,7 +2162,7 @@ function create_spawn_runtime() {
3997
2162
  }, args.startup_timeout_ms);
3998
2163
  const arm_stall_timer = () => {
3999
2164
  if (args.stall_timeout_ms <= 0) return;
4000
- if (stall_timer !== void 0) clearTimeout(stall_timer);
2165
+ clearTimeout(stall_timer);
4001
2166
  stall_timer = setTimeout(() => {
4002
2167
  stall_error = new claude_cli_error("stall_timeout", `no stdout for ${String(args.stall_timeout_ms)}ms`);
4003
2168
  escalate("timeout");
@@ -4956,7 +3121,7 @@ function create_option_ignored_dedup(trajectory) {
4956
3121
  } };
4957
3122
  }
4958
3123
  //#endregion
4959
- //#region src/engine/providers/claude_cli/index.ts
3124
+ //#region src/engine/providers/claude_cli/adapter.ts
4960
3125
  /**
4961
3126
  * claude_cli adapter factory (spec §5.5, §6, §8, §13).
4962
3127
  *
@@ -6112,7 +4277,14 @@ async function collect_stream(params, step_index, dispatcher, on_first_chunk, in
6112
4277
  };
6113
4278
  }
6114
4279
  async function collect_non_stream(params, adapter) {
6115
- const result = await generateText(params);
4280
+ let result;
4281
+ try {
4282
+ result = await generateText(params);
4283
+ } catch (err) {
4284
+ const recovered = recover_no_object_generated(err, adapter);
4285
+ if (recovered !== void 0) return recovered;
4286
+ throw err;
4287
+ }
6116
4288
  const tool_calls = [];
6117
4289
  for (const tc of result.toolCalls) tool_calls.push({
6118
4290
  id: tc.toolCallId,
@@ -6127,6 +4299,29 @@ async function collect_non_stream(params, adapter) {
6127
4299
  usage: adapter.normalize_usage(raw_usage)
6128
4300
  };
6129
4301
  }
4302
+ /**
4303
+ * When `experimental_output` is in play, `generateText` eagerly parses the
4304
+ * model's text against the schema and throws `NoObjectGeneratedError` if it
4305
+ * does not conform. That parse is the SDK's, not fascicle's: turning it into a
4306
+ * thrown error would skip the engine's own schema-parse + repair loop (and the
4307
+ * error is not a retryable transient, so it would surface raw). Instead we
4308
+ * recover the model's raw text from the error and hand it back as a normal
4309
+ * turn result, so `parse_with_schema` re-validates it and the repair loop
4310
+ * engages exactly as it does for the prompt-based path. Returns undefined for
4311
+ * any other error so the caller rethrows.
4312
+ */
4313
+ function recover_no_object_generated(err, adapter) {
4314
+ if (!NoObjectGeneratedError.isInstance(err)) return void 0;
4315
+ const text_field = Reflect.get(err, "text");
4316
+ const finish_field = Reflect.get(err, "finishReason");
4317
+ const raw_usage = to_raw_provider_usage(Reflect.get(err, "usage"));
4318
+ return {
4319
+ text: typeof text_field === "string" ? text_field : "",
4320
+ tool_calls: [],
4321
+ finish_reason: map_finish_reason(typeof finish_field === "string" ? finish_field : void 0),
4322
+ usage: adapter.normalize_usage(raw_usage)
4323
+ };
4324
+ }
6130
4325
  function classify_ai_sdk_error(err) {
6131
4326
  if (err === null || typeof err !== "object") return err;
6132
4327
  const existing_kind = Reflect.get(err, "kind");
@@ -6239,6 +4434,7 @@ async function generate(opts_in, engine) {
6239
4434
  return model_instance;
6240
4435
  };
6241
4436
  const sdk_tools = to_sdk_tools(tools_list);
4437
+ const output_spec = opts.schema !== void 0 && tools_list.length === 0 && adapter.supports("structured_output") ? Output.object({ schema: opts.schema }) : void 0;
6242
4438
  const invoke_once = async (args) => {
6243
4439
  let chunks_started = false;
6244
4440
  const call_once = async () => {
@@ -6258,6 +4454,7 @@ async function generate(opts_in, engine) {
6258
4454
  };
6259
4455
  if (hoisted_system !== void 0) base_params.system = hoisted_system;
6260
4456
  if (sdk_tools !== void 0) base_params.tools = sdk_tools;
4457
+ if (output_spec !== void 0) base_params.experimental_output = output_spec;
6261
4458
  if (provider_options !== void 0) base_params.providerOptions = provider_options;
6262
4459
  if (opts.temperature !== void 0) base_params.temperature = opts.temperature;
6263
4460
  if (opts.max_tokens !== void 0) base_params.maxOutputTokens = opts.max_tokens;
@@ -6548,14 +4745,13 @@ function stable_signature(input) {
6548
4745
  function model_call(cfg) {
6549
4746
  const has_tools = Boolean(cfg.tools && cfg.tools.length > 0);
6550
4747
  const has_schema = cfg.schema !== void 0;
6551
- const signature_input = {
4748
+ const step_id = cfg.id ?? `model_call:${stable_signature({
4749
+ model: cfg.model,
4750
+ provider: cfg.provider,
4751
+ system: cfg.system,
6552
4752
  has_tools,
6553
4753
  has_schema
6554
- };
6555
- if (cfg.model !== void 0) signature_input.model = cfg.model;
6556
- if (cfg.provider !== void 0) signature_input.provider = cfg.provider;
6557
- if (cfg.system !== void 0) signature_input.system = cfg.system;
6558
- const step_id = cfg.id ?? `model_call:${stable_signature(signature_input)}`;
4754
+ })}`;
6559
4755
  const describe_config = {
6560
4756
  has_tools,
6561
4757
  has_schema
@@ -6701,8 +4897,7 @@ const STATIC_HTML = resolve(dirname(fileURLToPath(import.meta.url)), "static", "
6701
4897
  function start_server(options) {
6702
4898
  const { broadcaster, host, port, on_parse_error } = options;
6703
4899
  const handler = (req, res) => {
6704
- const url = new URL(req.url ?? "/", `http://${req.headers.host ?? `${host}:${port}`}`);
6705
- const route = `${req.method ?? "GET"} ${url.pathname}`;
4900
+ const route = resolve_route(req, host, port);
6706
4901
  if (route === "GET /" || route === "GET /index.html") {
6707
4902
  serve_static_html(res);
6708
4903
  return;
@@ -6743,6 +4938,10 @@ function start_server(options) {
6743
4938
  });
6744
4939
  });
6745
4940
  }
4941
+ function resolve_route(req, host, port) {
4942
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? `${host}:${port}`}`);
4943
+ return `${req.method ?? "GET"} ${url.pathname}`;
4944
+ }
6746
4945
  function close_server(server) {
6747
4946
  return new Promise((res_ok, res_err) => {
6748
4947
  server.close((err) => {
@@ -6975,6 +5174,50 @@ function start_tail(options) {
6975
5174
  };
6976
5175
  }
6977
5176
  //#endregion
5177
+ //#region src/viewer/start_viewer.ts
5178
+ /**
5179
+ * `start_viewer` programmatic embed implementation.
5180
+ *
5181
+ * Spin up the server, optionally start tailing a JSONL file, and return a
5182
+ * handle that can stop both. `start_viewer` only depends on core's wire-format
5183
+ * schema; it never reaches into the engine, composites, or any provider.
5184
+ */
5185
+ async function start_viewer(options = {}) {
5186
+ const host = options.host ?? "127.0.0.1";
5187
+ const port = options.port ?? 4242;
5188
+ const broadcaster = create_broadcaster({
5189
+ buffer: options.buffer ?? 1e3,
5190
+ ...options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}
5191
+ });
5192
+ const server = await start_server({
5193
+ broadcaster,
5194
+ host,
5195
+ port,
5196
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
5197
+ });
5198
+ let tail = null;
5199
+ if (options.path !== void 0) tail = start_tail({
5200
+ path: options.path,
5201
+ on_event: (event) => {
5202
+ broadcaster.emit(event);
5203
+ },
5204
+ ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {},
5205
+ ...options.on_io_error ? { on_io_error: options.on_io_error } : {}
5206
+ });
5207
+ return wrap_handle(server, tail, host, port);
5208
+ }
5209
+ function wrap_handle(server, tail, host, port) {
5210
+ return {
5211
+ url: server.url,
5212
+ host,
5213
+ port,
5214
+ close: async () => {
5215
+ if (tail) tail.stop();
5216
+ await server.close();
5217
+ }
5218
+ };
5219
+ }
5220
+ //#endregion
6978
5221
  //#region src/viewer/cli.ts
6979
5222
  /**
6980
5223
  * fascicle-viewer CLI.
@@ -7135,51 +5378,6 @@ if (process.argv[1] !== void 0 && process.argv[1] === fileURLToPath(import.meta.
7135
5378
  process.exit(1);
7136
5379
  });
7137
5380
  //#endregion
7138
- //#region src/viewer/index.ts
7139
- /**
7140
- * Public surface for viewer.
7141
- *
7142
- * `start_viewer({ ... })` is the programmatic embed: spin up the server,
7143
- * optionally start tailing a JSONL file, and return a handle that can stop
7144
- * both. `start_viewer` only depends on core's wire-format schema; it
7145
- * never reaches into the engine, composites, or any provider.
7146
- */
7147
- async function start_viewer(options = {}) {
7148
- const host = options.host ?? "127.0.0.1";
7149
- const port = options.port ?? 4242;
7150
- const broadcaster = create_broadcaster({
7151
- buffer: options.buffer ?? 1e3,
7152
- ...options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}
7153
- });
7154
- const server = await start_server({
7155
- broadcaster,
7156
- host,
7157
- port,
7158
- ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}
7159
- });
7160
- let tail = null;
7161
- if (options.path !== void 0) tail = start_tail({
7162
- path: options.path,
7163
- on_event: (event) => {
7164
- broadcaster.emit(event);
7165
- },
7166
- ...options.on_parse_error ? { on_parse_error: options.on_parse_error } : {},
7167
- ...options.on_io_error ? { on_io_error: options.on_io_error } : {}
7168
- });
7169
- return wrap_handle(server, tail, host, port);
7170
- }
7171
- function wrap_handle(server, tail, host, port) {
7172
- return {
7173
- url: server.url,
7174
- host,
7175
- port,
7176
- close: async () => {
7177
- if (tail) tail.stop();
7178
- await server.close();
7179
- }
7180
- };
7181
- }
7182
- //#endregion
7183
- export { STEP_KINDS, aborted_error, adversarial, bench, branch, checkpoint, claude_cli_error, compose, consensus, version as core_version, create_engine, custom_event_schema, describe, describe_cycle_error, emit_event_schema, engine_config_error, engine_disposed_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_required_error, normalize_score, on_chunk_error, parallel, pipe, provider_auth_error, 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 };
5381
+ export { STEP_KINDS, aborted_error, adversarial, bench, branch, checkpoint, claude_cli_error, compose, consensus, create_engine, custom_event_schema, describe, describe_cycle_error, emit_event_schema, engine_config_error, engine_disposed_error, ensemble, ensemble_step, fallback, flow_schema_default as flow_schema, forward_standard_env, improve, is_step_kind, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_required_error, normalize_score, on_chunk_error, parallel, pipe, provider_auth_error, 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 };
7184
5382
 
7185
5383
  //# sourceMappingURL=index.js.map