fascicle 0.10.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { A as aborted_error, C as map, D as describe, E as sequence, F as flow_schema_default, M as resume_validation_error, N as suspended_error, O as step, P as timeout_error, S as pipe, T as parallel, _ as timeout, a as parse_trajectory_event, b as compute_backoff, c as scope, d as suspend, f as format_schema_issues, g as loop, h as compose, i as is_span_start_event, j as describe_cycle_error, k as run, l as stash, m as checkpoint, n as is_emit_event, o as STEP_KINDS, p as validate_schema, r as is_span_end_event, s as is_step_kind, t as is_custom_trajectory_event, u as use, v as fallback, w as branch, x as wait_with_abort, y as retry } from "./core-DkuJqLwd.js";
1
+ import { A as aborted_error, C as map, D as describe, E as sequence, F as flow_schema_default, M as resume_validation_error, N as suspended_error, O as step, P as timeout_error, S as pipe, T as parallel, _ as timeout, a as parse_trajectory_event, b as compute_backoff, c as scope, d as suspend, f as format_schema_issues, g as loop, h as compose, i as is_span_start_event, j as describe_cycle_error, k as run, l as stash, m as checkpoint, n as is_emit_event, o as STEP_KINDS, p as validate_schema, r as is_span_end_event, s as is_step_kind, t as is_custom_trajectory_event, u as use, v as fallback, w as branch, x as wait_with_abort, y as retry } from "./core-Ww6An4CS.js";
2
2
  import { a as http_logger, n as tee_logger, o as filesystem_logger } from "./adapters-CJnu1687.js";
3
- import { _ as tool_approval_denied_error, a as claude_cli_error, c as incomplete_generation_error, d as provider_auth_error, f as provider_capability_error, g as schema_validation_error, h as rate_limit_error, i as resolve_transport, l as model_required_error, m as provider_not_configured_error, n as load_optional_peer, o as engine_config_error, p as provider_error, r as missing_peer_error, s as engine_disposed_error, t as default_normalize_usage, u as on_chunk_error, v as tool_error, y as turn_timeout_error } from "./types-kO1JoGNZ.js";
3
+ import { _ as tool_approval_denied_error, a as claude_cli_error, c as incomplete_generation_error, d as provider_auth_error, f as provider_capability_error, g as schema_validation_error, h as rate_limit_error, i as resolve_transport, l as model_required_error, m as provider_not_configured_error, n as load_optional_peer, o as engine_config_error, p as provider_error, r as missing_peer_error, s as engine_disposed_error, t as default_normalize_usage, u as on_chunk_error, v as tool_error, y as turn_timeout_error } from "./types-NnSvmpjg.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { mkdir, open, readFile, readdir, stat, writeFile } from "node:fs/promises";
6
6
  import { dirname, join, resolve } from "node:path";
@@ -31,13 +31,18 @@ var schema_not_convertible_error = class extends Error {
31
31
  /**
32
32
  * JSON Schema emission for schemas that reach a model.
33
33
  *
34
- * Standard JSON Schema exposes two directions, `input` and `output`. fascicle
35
- * emits the output direction because that is what `z.toJSONSchema` produced
36
- * before this zone existed, and provider payloads must stay byte-identical
37
- * across the migration. Which direction is semantically right for a tool
38
- * definition (input un-requires defaulted fields, which is arguably what a
39
- * model should be told) is a deliberate follow-up, not a change to smuggle in
40
- * behind a refactor.
34
+ * Standard JSON Schema exposes two directions, `input` and `output`. A tool
35
+ * definition describes what the model should *produce*, so fascicle emits the
36
+ * input direction: a field with a default is one the model may omit, and
37
+ * saying otherwise asks it to supply a value the schema already supplies.
38
+ *
39
+ * The input direction alone is too loose, though. A vendor describes what it
40
+ * will accept, and accepting unknown keys is the common default (zod's
41
+ * `z.object` strips them, ArkType ignores them), so nothing in the emitted
42
+ * schema stops a model inventing one. `close_objects` supplies that guard,
43
+ * which is also what the strict and constrained-decode modes require. The AI
44
+ * SDK composes the same two halves for every `kind: 'ai_sdk'` provider, so
45
+ * this is what the majority of fascicle's transports already send.
41
46
  */
42
47
  const DEFAULT_TARGET = "draft-2020-12";
43
48
  /**
@@ -51,10 +56,86 @@ const DEFAULT_TARGET = "draft-2020-12";
51
56
  */
52
57
  function to_json_schema(schema, options = {}) {
53
58
  const props = schema["~standard"];
54
- if (typeof props.jsonSchema?.output !== "function") throw new schema_not_convertible_error(props.vendor);
55
- const json = props.jsonSchema.output({ target: options.target ?? DEFAULT_TARGET });
59
+ if (typeof props.jsonSchema?.input !== "function") throw new schema_not_convertible_error(props.vendor);
60
+ const json = close_objects(props.jsonSchema.input({ target: options.target ?? DEFAULT_TARGET }));
56
61
  return options.strip_meta === true ? strip_meta_keys(json) : json;
57
62
  }
63
+ /** Keys whose value is a bag of nested schemas, one per name. */
64
+ const SCHEMA_BAGS = [
65
+ "properties",
66
+ "patternProperties",
67
+ "$defs",
68
+ "definitions"
69
+ ];
70
+ /** Keys whose value is a nested schema, or a list of them. */
71
+ const SCHEMA_SLOTS = [
72
+ "items",
73
+ "additionalItems",
74
+ "additionalProperties",
75
+ "propertyNames",
76
+ "not",
77
+ "anyOf",
78
+ "allOf",
79
+ "oneOf",
80
+ "prefixItems"
81
+ ];
82
+ /**
83
+ * Add `additionalProperties: false` to every object node that does not already
84
+ * constrain it, so the model is told which keys exist rather than left to
85
+ * invent them.
86
+ *
87
+ * Two restraints keep this from asserting more than the vendor did. An
88
+ * existing `additionalProperties` is never overwritten, so a deliberately open
89
+ * schema (zod's `looseObject`, a `record`'s value schema, a server that
90
+ * published `true`) stays open. And a node is only closed if it declares
91
+ * `properties`: a bare `{ type: 'object' }` is how a freeform payload is
92
+ * described, most visibly by an MCP server, and closing it would forbid every
93
+ * key rather than constrain the listed ones. Every zod object emits
94
+ * `properties`, `z.object({})` included, so the guard costs nothing there.
95
+ *
96
+ * The tree is rebuilt rather than mutated. The spec does not promise a fresh
97
+ * object per call, and a vendor handing back a cached one would be corrupted
98
+ * by an in-place stamp. Recursion terminates on any schema: a self-referential
99
+ * schema emits `$ref`, which is a string, not a nested node.
100
+ */
101
+ function close_objects(node) {
102
+ const closed = close_nested(node);
103
+ return needs_closing(closed) ? {
104
+ ...closed,
105
+ additionalProperties: false
106
+ } : closed;
107
+ }
108
+ /** Rebuild `node` with every schema it holds closed, leaving its own keys alone. */
109
+ function close_nested(node) {
110
+ const closed = { ...node };
111
+ for (const key of SCHEMA_BAGS) {
112
+ const bag = closed[key];
113
+ if (is_node(bag)) closed[key] = close_bag(bag);
114
+ }
115
+ for (const key of SCHEMA_SLOTS) if (key in closed) closed[key] = close_value(closed[key]);
116
+ return closed;
117
+ }
118
+ /** Rebuild a name-to-schema bag with each of its schemas closed. */
119
+ function close_bag(bag) {
120
+ const closed = {};
121
+ for (const [name, value] of Object.entries(bag)) closed[name] = close_value(value);
122
+ return closed;
123
+ }
124
+ /** Recurse into a schema or a list of them, leaving anything else alone. */
125
+ function close_value(value) {
126
+ if (Array.isArray(value)) return value.map(close_value);
127
+ return is_node(value) ? close_objects(value) : value;
128
+ }
129
+ /** True for an object node listing its keys but not saying whether more are allowed. */
130
+ function needs_closing(node) {
131
+ if ("additionalProperties" in node || !("properties" in node)) return false;
132
+ const type = node["type"];
133
+ return type === "object" || Array.isArray(type) && type.includes("object");
134
+ }
135
+ /** A JSON Schema node, as opposed to a boolean schema, a list, or a scalar. */
136
+ function is_node(value) {
137
+ return typeof value === "object" && value !== null && !Array.isArray(value);
138
+ }
58
139
  /**
59
140
  * Drop the top-level `$schema` and `$id` keys.
60
141
  *
@@ -108,7 +189,7 @@ function build_input_from_state(s) {
108
189
  */
109
190
  function adversarial(config) {
110
191
  const { build, critique, accept, max_rounds } = config;
111
- const inner = pipe(loop({
192
+ const inner = loop({
112
193
  init: (input) => ({ input }),
113
194
  body: scope([
114
195
  stash("state", step("snapshot", (s) => s)),
@@ -140,16 +221,16 @@ function adversarial(config) {
140
221
  };
141
222
  })
142
223
  ]),
143
- finish: (s) => {
224
+ finish: (s, { converged, rounds }) => {
144
225
  if (s.candidate === void 0) throw new Error("adversarial: finished without a candidate");
145
- return s.candidate;
226
+ return {
227
+ candidate: s.candidate,
228
+ converged,
229
+ rounds
230
+ };
146
231
  },
147
232
  max_rounds
148
- }), (result) => ({
149
- candidate: result.value,
150
- converged: result.converged,
151
- rounds: result.rounds
152
- }));
233
+ });
153
234
  return compose(config.name ?? "adversarial", inner);
154
235
  }
155
236
  //#endregion
@@ -172,7 +253,7 @@ function adversarial(config) {
172
253
  function consensus(config) {
173
254
  const { members, agree, max_rounds } = config;
174
255
  const round_step = parallel(members);
175
- const inner = pipe(loop({
256
+ const inner = loop({
176
257
  init: (input) => ({
177
258
  input,
178
259
  results: {}
@@ -192,12 +273,12 @@ function consensus(config) {
192
273
  stop: agree(s.results),
193
274
  state: s
194
275
  })),
195
- finish: (s) => s.results,
276
+ finish: (s, { converged }) => ({
277
+ result: s.results,
278
+ converged
279
+ }),
196
280
  max_rounds
197
- }), (result) => ({
198
- result: result.value,
199
- converged: result.converged
200
- }));
281
+ });
201
282
  return compose(config.name ?? "consensus", inner);
202
283
  }
203
284
  //#endregion
@@ -508,14 +589,14 @@ function improve(config) {
508
589
  }),
509
590
  max_rounds
510
591
  }),
511
- step("improve_unwrap", (result, ctx) => {
592
+ step("improve_stop", (result, ctx) => {
512
593
  ctx.trajectory.record({
513
594
  kind: "improve.stop",
514
- stopped_by: result.value.stopped_by,
515
- rounds_used: result.value.rounds_used,
516
- final_score: result.value.best.score
595
+ stopped_by: result.stopped_by,
596
+ rounds_used: result.rounds_used,
597
+ final_score: result.best.score
517
598
  });
518
- return result.value;
599
+ return result;
519
600
  })
520
601
  ]);
521
602
  return compose(config.name ?? "improve", inner);
@@ -1554,6 +1635,24 @@ function is_retryable(kind, policy) {
1554
1635
  return policy.retry_on.includes(kind);
1555
1636
  }
1556
1637
  /**
1638
+ * Map an abort reason onto the error this layer rejects with, always wrapping
1639
+ * so an abort can only ever surface as `aborted_error` with the caller's
1640
+ * reason attached.
1641
+ *
1642
+ * The engine's convention, and the opposite of core's propagate-verbatim rule.
1643
+ * Two things depend on the wrap. A bare `controller.abort()` sets
1644
+ * `signal.reason` to a `DOMException`, which is an `Error` on Node, so
1645
+ * propagating would leak a non-fascicle error out of a boundary documented as
1646
+ * throwing `aborted_error`. And the engine's other abort sites (`generate`,
1647
+ * `tool_loop`, the adapters) wrap in order to attach `step_index` and
1648
+ * `tool_call_in_flight`, which only the construction site knows; propagating
1649
+ * would discard them. Wrapping a reason that is already an `aborted_error`
1650
+ * nests one inside the other, which is the accepted cost of that contract.
1651
+ */
1652
+ function to_abort_error(reason) {
1653
+ return new aborted_error("aborted", { reason });
1654
+ }
1655
+ /**
1557
1656
  * Retry `fn` under `policy`. `fn` must throw a RetryableError-shaped object to
1558
1657
  * trigger retry; any other thrown value short-circuits as a permanent failure.
1559
1658
  *
@@ -1572,7 +1671,7 @@ async function retry_with_policy(fn, policy = DEFAULT_RETRY, abort) {
1572
1671
  let attempt = 0;
1573
1672
  let last_rate_limit_after;
1574
1673
  while (true) {
1575
- if (abort?.aborted === true) throw new aborted_error("aborted", { reason: abort.reason });
1674
+ if (abort?.aborted === true) throw to_abort_error(abort.reason);
1576
1675
  try {
1577
1676
  return await fn(attempt);
1578
1677
  } catch (err) {
@@ -1600,7 +1699,7 @@ async function retry_with_policy(fn, policy = DEFAULT_RETRY, abort) {
1600
1699
  delay = Math.max(delay, retryable.retry_after_ms);
1601
1700
  last_rate_limit_after = retryable.retry_after_ms;
1602
1701
  }
1603
- await wait_with_abort(delay, signal, (reason) => new aborted_error("aborted", { reason }));
1702
+ await wait_with_abort(delay, signal, to_abort_error);
1604
1703
  }
1605
1704
  }
1606
1705
  }
@@ -2309,12 +2408,13 @@ const create_anthropic_native_adapter = (init) => {
2309
2408
  /**
2310
2409
  * Map an effort level to Anthropic's extended-thinking provider options.
2311
2410
  *
2312
- * `none` (a zero budget) sends no thinking config at all rather than an
2313
- * explicit "disabled" value, so non-reasoning models see a plain request.
2411
+ * A zero budget (which is what `none` maps to) sends no thinking config at all
2412
+ * rather than an explicit "disabled" value, so non-reasoning models see a plain
2413
+ * request.
2314
2414
  */
2315
2415
  function translate_anthropic_effort(effort) {
2316
2416
  const budget = ANTHROPIC_THINKING_BUDGETS[effort];
2317
- if (effort === "none" || budget === 0) return {
2417
+ if (budget === 0) return {
2318
2418
  provider_options: {},
2319
2419
  effort_ignored: false
2320
2420
  };
@@ -7365,7 +7465,7 @@ async function generate(opts_in, engine) {
7365
7465
  const provider_options = combined_provider_options !== void 0 && Object.keys(combined_provider_options).length > 0 ? combined_provider_options : void 0;
7366
7466
  let ai_sdk_invoke_mod;
7367
7467
  try {
7368
- ai_sdk_invoke_mod = await import("./invoke-D9pxbZcu.js");
7468
+ ai_sdk_invoke_mod = await import("./invoke-CWjm1Y_R.js");
7369
7469
  } catch (err) {
7370
7470
  throw missing_peer_error("ai", err);
7371
7471
  }