fascicle 0.10.2 → 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/CHANGELOG.md +52 -0
- package/README.md +9 -9
- package/dist/adapters.d.ts +1 -1
- package/dist/agents.d.ts +4 -4
- package/dist/agents.js +1 -1
- package/dist/agents.js.map +1 -1
- package/dist/{core-Dit3Rv9J.js → core-Ww6An4CS.js} +192 -96
- package/dist/core-Ww6An4CS.js.map +1 -0
- package/dist/index.d.ts +1124 -5
- package/dist/index.js +589 -961
- package/dist/index.js.map +1 -1
- package/dist/invoke-CWjm1Y_R.js +451 -0
- package/dist/invoke-CWjm1Y_R.js.map +1 -0
- package/dist/mcp.d.ts +25 -13
- package/dist/mcp.js +203 -121
- package/dist/mcp.js.map +1 -1
- package/dist/otel.d.ts +1 -1
- package/dist/stdio.d.ts +4 -4
- package/dist/stdio.js +30 -12
- package/dist/stdio.js.map +1 -1
- package/dist/{index-CHtfOfEF.d.ts → types-B3HIsBBD.d.ts} +7 -133
- package/dist/types-BCtKsxrX.d.ts +149 -0
- package/dist/types-BDSbSUAO.d.ts +63 -0
- package/dist/types-NnSvmpjg.js +253 -0
- package/dist/types-NnSvmpjg.js.map +1 -0
- package/dist/ui.d.ts +2 -2
- package/package.json +14 -3
- package/dist/core-Dit3Rv9J.js.map +0 -1
- package/dist/index-C2ayBpzS.d.ts +0 -993
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,57 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v0.11.0 — 2026-08-12
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- **A tool's JSON Schema no longer requires the fields that carry a default.** Provider payloads were emitted through Standard JSON Schema's *output* direction, which describes a value that has already been parsed: defaults are filled in by then, so `z.object({ city: z.string(), units: z.string().default('celsius') })` reached the model as `required: ["city","units"]`. That asked the model to supply a value the schema itself supplies, and made a defaulted field indistinguishable from a mandatory one. Emission now uses the *input* direction, which describes what the model should produce, so the same tool arrives as `required: ["city"]`. The input direction on its own also drops `additionalProperties: false` — the guard that stops a model inventing keys, and a prerequisite of several providers' strict and constrained-decode modes — so it is composed with a pass that closes every object node the vendor left open. This is the same pairing `@ai-sdk/provider-utils` applies to every `kind: 'ai_sdk'` provider (all seven fascicle configures by default), so the native adapters and `claude_cli` now send what the AI SDK path was already sending rather than a second, stricter shape for the same tool. Two restraints keep the closing pass from asserting more than the vendor did: an existing `additionalProperties` is never overwritten, so `z.looseObject`, a `z.record`'s value schema, and a server that published `true` all stay open (the AI SDK overwrites these); and a node is closed only if it declares `properties`, so a bare `{ type: 'object' }` — how a freeform payload is advertised — is left alone instead of being narrowed to "no keys permitted". One capability comes with it: `.output()` throws on a schema carrying a transform (`Transforms cannot be represented in JSON Schema`), so a tool whose schema contained one could not reach a native provider at all; the input direction emits it. **Breaking** on the wire for any tool or structured-output schema with a `.default()` or `.catch()` field: that field moves out of `required`, at every depth, including inside arrays and unions. Schemas without one are byte-identical to before, key order included. A knock-on for MCP: v0.10.3 made an inbound server's advertised schema reach the provider verbatim, and closing objects narrows that — a server that declares `properties` but says nothing about `additionalProperties` now has `additionalProperties: false` added on the native transports. The AI SDK path already did this to those same schemas, so the effect is that MCP tools now behave the same across all transports rather than differing by the one in use.
|
|
8
|
+
|
|
9
|
+
- **`loop` no longer wraps its output in a result envelope.** It returned `Step<i, LoopResult<o>>` — `{ value, converged, rounds }` — so anything that wanted the projected value had to strip `.value` first, and every one of the six in-repo call sites did: `adversarial` and `consensus` each carried a whole `pipe` for it, `improve` had an `improve_unwrap` step, the researcher agent wrapped its loop in a second `step` that called `inner.run` by hand (skipping the loop's own span) purely to return `result.value`, and both example apps hopped through `.value` at the read site. The envelope was a second projection channel layered over the one `loop` already had: `finish` is where the final state becomes the output, and it was already handed a piece of loop metadata (`round: number`) that no call site used. It now receives all of it — `finish: (state, outcome: LoopOutcome) => o`, with `LoopOutcome` being `{ converged, rounds }` — and `loop` returns `Step<i, o>`: exactly what `finish` projects, nothing around it. Non-convergence is still data rather than error; it arrives as an argument instead of a wrapper, which is why this shape was chosen over an `unwrap: true` flag (that would have needed two return types on one function, and would have discarded `converged` silently — the datum the whole convention rests on). Nothing is lost by dropping the envelope, because `finish` and the `loop({...})` call site always have the same author: the old shape is `finish: (state, outcome) => ({ value: state, ...outcome })`, opt-in in one line. Trajectories are unaffected: a traced composer's span records `{ id }` only, so `converged` and `rounds` were never in the trace to begin with. **Breaking:** `LoopResult` is gone from the published surface, replaced by `LoopOutcome`; a `loop` step's output type is now `o`; and a `finish` that declared a second parameter now receives the outcome object where the round count used to be. `docs/composition.md`, `docs/api-reference.md`, and `docs/deliberation-as-composition.md` state the new shape. In `examples/pr-improve` the `LOOP_RESULT` scope key becomes `FINAL_STATE`, since what the loop stashes is now the carry-state itself — whose own `round` field counts the same rounds the envelope reported.
|
|
10
|
+
|
|
11
|
+
### Internal
|
|
12
|
+
|
|
13
|
+
- **The two retry layers' different abort-rejection shapes are now recorded as deliberate, in the code and in `docs/concepts.md`.** The engine's retry always wraps an abort reason in `aborted_error`; core's propagates an `Error` reason verbatim and wraps anything else. Unifying them founders on a Node 24 fact now pinned by tests on both sides: a bare `controller.abort()` sets a `DOMException` reason, which *is* an `instanceof Error`, so adopting core's semantics in the engine would leak `DOMException` where callers expect `aborted_error`. Each retry module names its shape in a `to_abort_error` factory with the rationale attached.
|
|
14
|
+
- **The last un-hardened wire adapter is closed: the `ai_sdk` Anthropic adapter went from 66.1% to 100% mutation score.** Its config assembly (api key and base URL coercion, conditional `baseURL`) was covered only by a `toBeDefined()` against the real peer; a mock-the-peer test file now pins every field, and a redundant effort-guard clause was simplified away rather than annotated. Full-repo mutation score 88.4% → 89.0%.
|
|
15
|
+
- **The mutation break threshold ratchets 84 → 86**, sized from the measured flake surface (91 Timeout mutants of 10,677 scored = 0.85pt worst case) instead of the previous comment's ~5×-overstated guess.
|
|
16
|
+
|
|
17
|
+
## v0.10.3 — 2026-08-12
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- **`bench` no longer scores a suspended or cancelled run as a set of failed cases.** A `suspended_error` from a human-approval gate inside a benched flow was caught by the same handler as an application failure and recorded as `{ ok: false, error: 'suspended at ...' }`, so a paused case scored a zero and moved `pass_rate` without anything reporting that the flow never finished. `bench` has no resume path, so a suspend inside a benched flow is a usage error: it now rejects with `bench_suspend_error` (exported from `fascicle`), carrying `case_id` and `suspend_id` so the offending case is named rather than searched for. The judge loop's `catch { continue }` abstain path had the same hole and gets the same guard. **Breaking** for anyone benching a flow that suspends: those runs rejected nothing before and reject now, which is the point, since the old report was wrong.
|
|
22
|
+
|
|
23
|
+
- **The documented install for every `ai_sdk` provider was missing `ai`, and openrouter's named the wrong package.** `docs/configuration.md`'s seven per-provider snippets said `pnpm add @ai-sdk/anthropic` alone. The official `@ai-sdk/*` packages peer-depend on `zod` rather than on `ai`, so once `ai` became optional nothing pulled it in transitively and each of those lines produced an install that could not run a turn. Correcting them surfaced a second, older defect in the same block: openrouter was documented as `@ai-sdk/openai-compatible`, but the adapter loads `@openrouter/ai-sdk-provider`, so the documented install could never satisfy it. `docs/providers.md`'s peer table is the authority for both.
|
|
24
|
+
|
|
25
|
+
- **`fascicle/ui` never named the peer it requires.** The subpath imports `ai` statically (it speaks the AI SDK's UI message-stream protocol), but none of the places documenting it said so. With `ai` optional and `pnpm add fascicle` now the whole install line, following those docs produced a raw `ERR_MODULE_NOT_FOUND`. `docs/api-reference.md` now separates the two peer-bearing subpaths by failure mode: `fascicle/mcp` loads its SDK dynamically and reports `mcp_sdk_missing_error`, while `fascicle/ui` fails at module resolution.
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- **`ai` is now an optional peer dependency.** It was the last mandatory peer on a package whose own `dependencies` block is empty, so `pnpm add fascicle` forced an install of the AI SDK core even for a `transport: 'native'`-only or `claude_cli`-only setup that never imports it. `ai` is loaded lazily from the one `ai_sdk` turn seam (`src/engine/generate.ts`), same as every `@ai-sdk/*` provider package, so it drops to `peerDependenciesMeta: { ai: { optional: true } }` alongside them; a missing `ai` reports through the same `load_optional_peer` message step 7 named it in. `docs/providers.md` and `README.md` now show `ai` alongside each `ai_sdk`-kind provider's install snippet, since the official `@ai-sdk/*` packages only peer-depend on `zod`, not `ai` — installing just `@ai-sdk/anthropic` no longer pulls `ai` in transitively now that fascicle's own peer is optional.
|
|
30
|
+
|
|
31
|
+
- **`BenchOptions` gains `abort`, and a cancelled bench rejects instead of returning a report.** `bench` accepted no signal at all and defaulted `install_signal_handlers` to `false`, so there was no cancellation path through a bench run. The signal now forwards to every per-case `run` and is re-checked before each case is claimed, so an abort halts scheduling at the queue rather than only cancelling work already in flight, and it is checked once more before the report is built, so neither a full fan-out (no queue to halt) nor a flow that ignores `ctx.abort` can yield a report for a run the caller cancelled. An `aborted_error` raised inside a case or a judge propagates rather than being flattened into `ok: false`. Abort reasons follow core's shape: an `Error` reason propagates verbatim, anything else is wrapped in `aborted_error`.
|
|
32
|
+
|
|
33
|
+
### Changed
|
|
34
|
+
|
|
35
|
+
- **`zod` is now an optional peer dependency, and fascicle has zero mandatory peers.** It was the last one: `ai` went optional earlier in this release, and the Standard Schema migration removed every internal zod import from `src/` except the type-only one in `src/mcp/serve.ts` (`McpServer.registerTool` accepts nothing else). `zod` drops to `peerDependenciesMeta: { zod: { optional: true } }` alongside every other peer, so `pnpm add fascicle` alone builds and runs a flow against `transport: 'native'` or `claude_cli` — no AI SDK, no schema library. Schemas accept any Standard Schema implementation (zod, ArkType, Valibot, …); installing zod remains necessary only if that is the vendor you choose. The `no-core-npm-dep-except-zod` and `no-engine-npm-dep-except-ai-zod` ast-grep rules, which permitted an npm dependency neither zone still uses, are replaced by `no-core-npm-dep` and `no-engine-npm-dep`: core and engine (outside `providers/`) now depend on no npm package at all, matching the `#schema`/`#policy` bottom-of-DAG zones that already carry the vendor-specific code. `README.md`, `docs/getting-started.md`, `VALUES.md`, and `SECURITY.md` state the zero-mandatory-peers posture directly.
|
|
36
|
+
|
|
37
|
+
- **The trajectory wire format is now read through hand-written guards instead of zod schemas.** The five exported schemas — `trajectory_event_schema`, `span_start_event_schema`, `span_end_event_schema`, `emit_event_schema`, and `custom_event_schema` — put a zod object on the published surface of a package that is dropping zod to an optional peer, so a consumer who never writes a zod schema still resolved zod to read a trajectory file. They are replaced by `parse_trajectory_event(value)`, which returns the same `safeParse` shape (`{ success: true, data }` / `{ success: false, error }`), and four type guards: `is_span_start_event`, `is_span_end_event`, `is_emit_event`, `is_custom_trajectory_event`. What parses is unchanged, deliberately down to the permissiveness: an event is any non-array object carrying a string `kind`, so a `span_start` line missing its `span_id` is still accepted as an event (the old ordered union fell through to `custom_event_schema` for exactly that case) and the well-known guards are recognizers layered on top rather than gates. `is_custom_trajectory_event` therefore answers `true` for well-known kinds too, matching `custom_event_schema` before it. Two visible differences: a successful parse now hands the wire value straight back rather than a shallow zod clone, so nothing is dropped on the way through — including a literal `__proto__` key, which zod's clone silently swallowed and which now rides along as the inert own property `JSON.parse` produced (no prototype is mutated either way) — and the failure `error` is a plain `Error` rather than a `ZodError`, so code reading `.issues` off it needs the line itself instead (the viewer's `on_parse_error` already receives that as its second argument). The exported types keep their names (`SpanStartEvent`, `SpanEndEvent`, `EmitEvent`, `CustomTrajectoryEvent`, `ParsedTrajectoryEvent`) and shapes, joined by `TrajectoryParseResult`. **Breaking:** any of the five schema exports, or `ZodError`-shaped handling of a rejected line.
|
|
38
|
+
|
|
39
|
+
- **Every schema fascicle validates now runs through Standard Schema, so validation failures read the same whichever library produced them.** Tool inputs, structured-output parsing, `suspend` resume data, and both `run_stdio` IO checks called zod's `safeParse` directly and reported whatever zod handed back. They now go through the vendor-neutral `~standard.validate` interface, so an ArkType or Valibot schema validates on the same path a zod one does. Two things consumers can see change shape. The message fed back to a model on a rejected tool call (and the schema repair prompt, and `schema_validation_error.message`) was zod's own multi-line JSON dump of its issue objects; it is now one line of `path: message` clauses with dotted paths — `city: Invalid input: expected string, received number; opts.deep: Invalid input: expected boolean, received string`. And the `cause` on a `run_stdio` `validate_input` / `validate_output` failure now carries `{ message, path }` issues instead of zod's issue objects, so the `code` and `expected` fields are gone from that JSON. Nothing that was validated before validates differently: only the report changed.
|
|
40
|
+
|
|
41
|
+
- **Schema failures are now reported vendor-neutrally end to end, closing out the zod-shaped naming and reporting left over from the Standard Schema migration.** `schema_validation_error` (thrown by `generate` and the `claude_cli` adapter after repair attempts are exhausted) carried a field named `.zod_error`; it is renamed `.schema_issues` and now holds the vendor-neutral `{ message, path? }` issue list directly rather than an `Error` wrapping a pre-formatted string. The engine's `schema_validation_failed` trajectory event's `zod_issues` field is renamed `schema_issues` (same one-line formatted string as before). `suspend`'s `resume_validation_error.issues` — called out above as unchanged — now also carries the vendor-neutral issue list instead of a hand-rolled reproduction of zod's `{ formErrors, fieldErrors }` shape. The internal `format_zod_error` helper is gone; formatting goes through `format_schema_issues` everywhere. **Breaking:** code reading `schema_validation_error.zod_error`, `resume_validation_error.issues.formErrors` / `.fieldErrors`, or a trajectory consumer reading `schema_validation_failed.zod_issues` needs to move to the renamed fields and shapes.
|
|
42
|
+
|
|
43
|
+
- **An inbound MCP tool now reaches the model with the schema its server actually advertised.** The bridge converted a server's JSON Schema into a Zod schema so the tool loop could validate it, and the provider path then converted that Zod back into JSON Schema — a round trip the old file's own header conceded was lossy. It dropped every value constraint on the way through: `minLength`, `maxItems`, `format`, `pattern`, and `enum` descriptions were modeled as plain types, so a model calling an MCP tool was told less about its arguments than the server had published. The bridge now builds a Standard Schema directly over the advertised JSON Schema, and emission hands that schema back verbatim in both directions, so what the server declared is what the provider receives. Validation is unchanged in reach — structure, types, enums, const, unions, and required keys are checked, value constraints are not, extra keys still pass through to the server, and anything unrecognized still accepts — because the server re-validates its own arguments and is the authority on them. Two visible consequences of verbatim emission: a server that declares `additionalProperties: false` now has that reach the provider instead of being loosened away, and `$schema` / `$id` keys the server published now ride along on the transports that accept them. The MCP path no longer imports zod at all. **Breaking:** the `fascicle/mcp` export `json_schema_to_zod` is renamed `json_schema_to_standard` and returns a `ToolSchema` rather than a `z.ZodType`, so a caller using it directly validates through `~standard.validate` (async) instead of `safeParse`.
|
|
44
|
+
|
|
45
|
+
- **The `zod` peer dependency is pinned to exactly `4.4.3`, up from `^4.0.0`.** fascicle is moving to emit provider JSON Schema through Standard JSON Schema (`~standard.jsonSchema`) rather than `z.toJSONSchema`, and that interface does not exist before zod 4.2.0: on 4.1.12 `~standard.jsonSchema` is `undefined`, so the old `^4.0.0` range named a floor that cannot work. The pin is exact rather than a range so that the one version fascicle is tested against is the one version it promises; 4.2.0 and 4.4.3 emit byte-identical draft-2020-12 schemas, so this is a choice about which version is guaranteed, not about behaviour. **Breaking:** an install that resolves zod to any other version, including a later patch such as 4.4.4, now reports a peer dependency conflict, and a project whose other packages peer-depend on a zod range excluding 4.4.3 cannot satisfy both at once. zod is an optional peer as of this release, which lifts the requirement for anyone who never installs it, but a consumer using zod schemas with fascicle still has to be on 4.4.3.
|
|
46
|
+
|
|
47
|
+
- **`retry` (composition layer) now jitters its backoff by default and caps it at 30s.** `RetryConfig` gains `max_delay_ms` (defaults to 30_000, matching the engine retry layer's cap) and `jitter` (defaults to `true`), both now expressed through the `#policy` backoff algebra the engine retry layer already used. Un-jittered retries from concurrent callers stampede back onto a recovering dependency in lockstep, and jittering is cheapest to add now, before `retry` has callers depending on its old exact-doubling delays. **Breaking:** a `retry(...)` call with a large `backoff_ms` or high `max_attempts` now serves a longer, randomized delay per attempt and is capped at 30s where it was previously uncapped; pass `jitter: false` and an explicit `max_delay_ms` to keep the old behavior exactly. `retry.test.ts` pins the default-on jitter clamped to an explicit cap, and the old exact-doubling assertion now runs with `jitter: false`.
|
|
48
|
+
|
|
49
|
+
### Internal
|
|
50
|
+
|
|
51
|
+
- **Two new bottom-of-DAG zones carry what core and engine used to reach for directly.** `#policy` holds the shared backoff algebra both retry layers now compute delays through; `#schema` holds the Standard Schema helpers (`validate_schema`, `to_json_schema`) that replaced zod at the public surface. Each ships its own ast-grep npm-dependency rule, so the "no npm dependency below this line" invariant is enforced rather than intended, and `snake-case-exports.yml` now covers both.
|
|
52
|
+
- **`docs/concepts.md` documents what cooperative cancellation cannot do** — `timeout` and abort signal intent but cannot kill work that ignores `ctx.abort`, and abandoned work keeps spending tokens — and `docs/composition.md`'s `retry` summary picks up the new `max_delay_ms` / `jitter` options.
|
|
53
|
+
- **The `claude_cli` SIGTERM-to-SIGKILL escalation test no longer races the wall clock.** It sampled child liveness partway through the escalation window, which under parallel load overran past `SIGKILL_ESCALATION_MS` and reported a dead child on untouched code. The sample is removed rather than given a wider margin, which would have pushed it past SIGKILL instead of clear of it: `signalCode` already proves SIGTERM was survived and the elapsed floor proves the escalator waited, both robust under load.
|
|
54
|
+
|
|
3
55
|
## v0.10.2 — 2026-08-11
|
|
4
56
|
|
|
5
57
|
### Added
|
package/README.md
CHANGED
|
@@ -9,10 +9,10 @@ No framework lifecycle. No ambient state. No decorators. Adapters are passed in
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
-
pnpm add fascicle
|
|
12
|
+
pnpm add fascicle
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
fascicle is ESM-only and requires Node >= 24.
|
|
15
|
+
fascicle is ESM-only and requires Node >= 24. `ai`, `zod`, and every provider SDK are optional peers — install only the ones you use. `pnpm add fascicle` alone builds and runs a flow against `transport: 'native'` or `claude_cli`, with no AI SDK package and no schema library installed at all; schemas accept any [Standard Schema](https://standardschema.dev) — zod, ArkType, Valibot, whichever you already use. See [docs/providers.md](./docs/providers.md).
|
|
16
16
|
|
|
17
17
|
## A 60-second tour
|
|
18
18
|
|
|
@@ -152,13 +152,13 @@ serve_flow({
|
|
|
152
152
|
|
|
153
153
|
| Provider | Peer dep | Auth |
|
|
154
154
|
| ------------ | ----------------------------- | ------------------- |
|
|
155
|
-
| `anthropic` | `@ai-sdk/anthropic`, or none with `transport: 'native'` | API key |
|
|
156
|
-
| `openai` | `@ai-sdk/openai`, or none with `transport: 'native'` | API key
|
|
157
|
-
| `google` | `@ai-sdk/google`
|
|
158
|
-
| `openrouter` | `@openrouter/ai-sdk-provider`, or none with `transport: 'native'` | API key |
|
|
159
|
-
| `bedrock` | `@ai-sdk/amazon-bedrock`
|
|
160
|
-
| `ollama` | `ai-sdk-ollama`, or none with `transport: 'native'` | local `base_url` |
|
|
161
|
-
| `lmstudio` | `@ai-sdk/openai-compatible`, or none with `transport: 'native'` | local `base_url` |
|
|
155
|
+
| `anthropic` | `ai` + `@ai-sdk/anthropic`, or none with `transport: 'native'` | API key |
|
|
156
|
+
| `openai` | `ai` + `@ai-sdk/openai`, or none with `transport: 'native'` | API key |
|
|
157
|
+
| `google` | `ai` + `@ai-sdk/google` | API key |
|
|
158
|
+
| `openrouter` | `ai` + `@openrouter/ai-sdk-provider`, or none with `transport: 'native'` | API key |
|
|
159
|
+
| `bedrock` | `ai` + `@ai-sdk/amazon-bedrock` | `region` + AWS credentials |
|
|
160
|
+
| `ollama` | `ai` + `ai-sdk-ollama`, or none with `transport: 'native'` | local `base_url` |
|
|
161
|
+
| `lmstudio` | `ai` + `@ai-sdk/openai-compatible`, or none with `transport: 'native'` | local `base_url` |
|
|
162
162
|
| `claude_cli` | none (spawns `claude`) | OAuth or API key |
|
|
163
163
|
|
|
164
164
|
Full details: [docs/providers.md](./docs/providers.md). The `claude_cli` adapter has its own guide: [docs/cli.md](./docs/cli.md).
|
package/dist/adapters.d.ts
CHANGED
package/dist/agents.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { r as Step } from "./types-BDSbSUAO.js";
|
|
2
|
+
import { r as ToolSchema } from "./types-BCtKsxrX.js";
|
|
3
|
+
import { a as Engine } from "./types-B3HIsBBD.js";
|
|
4
4
|
|
|
5
5
|
//#region src/agents/define_agent.d.ts
|
|
6
6
|
type AgentBuiltPrompt = string | {
|
|
@@ -9,7 +9,7 @@ type AgentBuiltPrompt = string | {
|
|
|
9
9
|
};
|
|
10
10
|
type DefineAgentConfig<i, o> = {
|
|
11
11
|
readonly md_path: string | URL;
|
|
12
|
-
readonly schema:
|
|
12
|
+
readonly schema: ToolSchema<o>;
|
|
13
13
|
readonly engine: Engine;
|
|
14
14
|
readonly name?: string;
|
|
15
15
|
readonly build_prompt?: (input: i) => AgentBuiltPrompt;
|
package/dist/agents.js
CHANGED
package/dist/agents.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents.js","names":[],"sources":["../src/agents/define_agent.ts"],"sourcesContent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `temperature`) is parsed into the agent's\n * step name and engine call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model` and `config.schema_repair_attempts` shape the call from\n * code. An explicit `model` wins over frontmatter `model` (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent name,\n * resolved model id, and engine-reported usage. No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature` coerced to number. Anything\n * richer should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { Engine, GenerateOptions } from '#engine'\nimport type { z } from 'zod'\n\nexport type AgentBuiltPrompt =\n | string\n | { readonly user: string; readonly system?: string }\n\nexport type DefineAgentConfig<i, o> = {\n readonly md_path: string | URL\n readonly schema: z.ZodType<o>\n readonly engine: Engine\n readonly name?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly temperature?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, and `temperature`\n * (coerced to a number); unrecognized keys are ignored. A file without an\n * opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return { frontmatter: {}, body: content }\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n\n const out: { -readonly [K in keyof Frontmatter]: Frontmatter[K] } = {}\n const lines = yaml_block.split(/\\r?\\n/)\n for (const raw of lines) {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) continue\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model') {\n out[key] = value\n continue\n }\n if (key === 'temperature') {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: temperature must be a number, got: ${value_raw}`)\n }\n out.temperature = n\n continue\n }\n }\n return { frontmatter: out, body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n\n return step<i, o>(display_name, async (input, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n if (frontmatter.temperature !== undefined) opts.temperature = frontmatter.temperature\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;;;;AAKvB,SAAS,QAAQ,KAAqB;CACpC,IAAI,IAAI,UAAU,GAAG;EACnB,MAAM,QAAQ,IAAI;EAClB,MAAM,OAAO,IAAI,IAAI,SAAS;EAC9B,IAAK,UAAU,QAAO,SAAS,QAAS,U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AAK,cAAc,YAAY;EAC1E,IAAI,OAAO,2BAA2B,KAAA,GACpC,KAAK,yBAAyB,OAAO;EAGvC,MAAM,SAAS,MAAM,OAAO,OAAO,SAAY,IAAI;EAEnD,MAAM,iBAAiB,GAAG,OAAO,eAAe,SAAS,GAAG,OAAO,eAAe;EAClF,IAAI,WAAW,OAAO;GACpB,MAAM;GACN,MAAM;GACN,OAAO;GACP,OAAO,OAAO;EAChB,CAAC;EAED,OAAO,OAAO;CAChB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"agents.js","names":[],"sources":["../src/agents/define_agent.ts"],"sourcesContent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `temperature`) is parsed into the agent's\n * step name and engine call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model` and `config.schema_repair_attempts` shape the call from\n * code. An explicit `model` wins over frontmatter `model` (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent name,\n * resolved model id, and engine-reported usage. No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature` coerced to number. Anything\n * richer should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { Engine, GenerateOptions } from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type AgentBuiltPrompt =\n | string\n | { readonly user: string; readonly system?: string }\n\nexport type DefineAgentConfig<i, o> = {\n readonly md_path: string | URL\n readonly schema: ToolSchema<o>\n readonly engine: Engine\n readonly name?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly temperature?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, and `temperature`\n * (coerced to a number); unrecognized keys are ignored. A file without an\n * opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return { frontmatter: {}, body: content }\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n\n const out: { -readonly [K in keyof Frontmatter]: Frontmatter[K] } = {}\n const lines = yaml_block.split(/\\r?\\n/)\n for (const raw of lines) {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) continue\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model') {\n out[key] = value\n continue\n }\n if (key === 'temperature') {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: temperature must be a number, got: ${value_raw}`)\n }\n out.temperature = n\n continue\n }\n }\n return { frontmatter: out, body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n\n return step<i, o>(display_name, async (input, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n if (frontmatter.temperature !== undefined) opts.temperature = frontmatter.temperature\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;;;;AAKvB,SAAS,QAAQ,KAAqB;CACpC,IAAI,IAAI,UAAU,GAAG;EACnB,MAAM,QAAQ,IAAI;EAClB,MAAM,OAAO,IAAI,IAAI,SAAS;EAC9B,IAAK,UAAU,QAAO,SAAS,QAAS,UAAU,OAAO,SAA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Y;EAC1E,IAAI,OAAO,2BAA2B,KAAA,GACpC,KAAK,yBAAyB,OAAO;EAGvC,MAAM,SAAS,MAAM,OAAO,OAAO,SAAY,IAAI;EAEnD,MAAM,iBAAiB,GAAG,OAAO,eAAe,SAAS,GAAG,OAAO,eAAe;EAClF,IAAI,WAAW,OAAO;GACpB,MAAM;GACN,MAAM;GACN,OAAO;GACP,OAAO,OAAO;EAChB,CAAC;EAED,OAAO,OAAO;CAChB,CAAC;AACH"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { z } from "zod";
|
|
3
2
|
//#region src/core/flow-schema.json
|
|
4
3
|
var flow_schema_default = {
|
|
5
4
|
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
@@ -358,13 +357,6 @@ async function run_one(fn, trajectory) {
|
|
|
358
357
|
}
|
|
359
358
|
//#endregion
|
|
360
359
|
//#region src/core/errors.ts
|
|
361
|
-
/**
|
|
362
|
-
* Typed errors for the composition layer.
|
|
363
|
-
*
|
|
364
|
-
* This is the only source file in the core layer that uses the `class`
|
|
365
|
-
* keyword. `Error` is a built-in and `instanceof` branching is how composers
|
|
366
|
-
* like `retry` and `fallback` distinguish failure modes.
|
|
367
|
-
*/
|
|
368
360
|
var timeout_error = class extends Error {
|
|
369
361
|
kind = "timeout_error";
|
|
370
362
|
timeout_ms;
|
|
@@ -1454,14 +1446,59 @@ function pipe(inner, fn, options) {
|
|
|
1454
1446
|
}
|
|
1455
1447
|
register_traced_kind("pipe");
|
|
1456
1448
|
//#endregion
|
|
1449
|
+
//#region src/policy/backoff.ts
|
|
1450
|
+
/**
|
|
1451
|
+
* Compute the delay before retry attempt `attempt`, counted from zero.
|
|
1452
|
+
*
|
|
1453
|
+
* Exponential (`initial_delay_ms * 2^attempt`) plus up to one
|
|
1454
|
+
* `initial_delay_ms` of random jitter when `policy.jitter` is set, clamped to
|
|
1455
|
+
* `max_delay_ms`. The jitter spreads retries from concurrent callers apart so
|
|
1456
|
+
* they don't stampede in lockstep; a `max_delay_ms` of `Infinity` is uncapped.
|
|
1457
|
+
*/
|
|
1458
|
+
function compute_backoff(policy, attempt) {
|
|
1459
|
+
const base = policy.initial_delay_ms * 2 ** attempt;
|
|
1460
|
+
const jitter = policy.jitter ? Math.random() * policy.initial_delay_ms : 0;
|
|
1461
|
+
return Math.min(base + jitter, policy.max_delay_ms);
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Sleep `ms`, rejecting the moment `signal` fires instead of serving out the
|
|
1465
|
+
* delay, so a pending abort never waits out a backoff.
|
|
1466
|
+
*
|
|
1467
|
+
* A non-positive `ms` resolves without arming a timer or consulting `signal`,
|
|
1468
|
+
* matching what both retry layers did before. The rejection value is
|
|
1469
|
+
* `to_error` applied to `signal.reason`.
|
|
1470
|
+
*/
|
|
1471
|
+
function wait_with_abort(ms, signal, to_error) {
|
|
1472
|
+
if (ms <= 0) return Promise.resolve();
|
|
1473
|
+
return new Promise((resolve, reject) => {
|
|
1474
|
+
if (signal.aborted) {
|
|
1475
|
+
reject(to_error(signal.reason));
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
const timer = setTimeout(() => {
|
|
1479
|
+
signal.removeEventListener("abort", on_abort);
|
|
1480
|
+
resolve();
|
|
1481
|
+
}, ms);
|
|
1482
|
+
const on_abort = () => {
|
|
1483
|
+
clearTimeout(timer);
|
|
1484
|
+
reject(to_error(signal.reason));
|
|
1485
|
+
};
|
|
1486
|
+
signal.addEventListener("abort", on_abort, { once: true });
|
|
1487
|
+
});
|
|
1488
|
+
}
|
|
1489
|
+
//#endregion
|
|
1457
1490
|
//#region src/core/retry.ts
|
|
1458
1491
|
/**
|
|
1459
1492
|
* retry: re-run on failure.
|
|
1460
1493
|
*
|
|
1461
|
-
* `retry(inner, { max_attempts, backoff_ms?, on_error? })`
|
|
1462
|
-
* throws an application error, retries up to
|
|
1463
|
-
*
|
|
1464
|
-
*
|
|
1494
|
+
* `retry(inner, { max_attempts, backoff_ms?, max_delay_ms?, jitter?, on_error? })`
|
|
1495
|
+
* runs `inner`. If it throws an application error, retries up to
|
|
1496
|
+
* `max_attempts - 1` more times with exponential backoff
|
|
1497
|
+
* (`backoff_ms * 2^(attempt-1)`), jittered by up to one `backoff_ms` and
|
|
1498
|
+
* clamped to `max_delay_ms` (default 30s) through the shared `#policy`
|
|
1499
|
+
* algebra. `jitter` defaults on: un-jittered concurrent retries stampede in
|
|
1500
|
+
* lockstep. `on_error` is called on every such failure. The last error is
|
|
1501
|
+
* rethrown if all attempts fail.
|
|
1465
1502
|
*
|
|
1466
1503
|
* Control-flow signals (`suspended_error`, `aborted_error`) are not failures:
|
|
1467
1504
|
* they propagate immediately without consuming an attempt, firing `on_error`,
|
|
@@ -1473,6 +1510,7 @@ register_traced_kind("pipe");
|
|
|
1473
1510
|
* attempts; a pending abort short-circuits the backoff and propagates.
|
|
1474
1511
|
*/
|
|
1475
1512
|
const DEFAULT_BACKOFF_MS = 1e3;
|
|
1513
|
+
const DEFAULT_MAX_DELAY_MS = 3e4;
|
|
1476
1514
|
let retry_counter = 0;
|
|
1477
1515
|
/**
|
|
1478
1516
|
* Generate a unique step id of the form `retry_<n>`.
|
|
@@ -1482,30 +1520,22 @@ function next_id$5() {
|
|
|
1482
1520
|
return `retry_${retry_counter}`;
|
|
1483
1521
|
}
|
|
1484
1522
|
/**
|
|
1485
|
-
*
|
|
1523
|
+
* Map an abort reason onto the error a retry rejects with, preserving an
|
|
1524
|
+
* `Error` reason verbatim rather than wrapping it in `aborted_error`.
|
|
1525
|
+
*
|
|
1526
|
+
* Core's convention, shared with `timeout`, `parallel`, `map`, the runner's
|
|
1527
|
+
* `throw_if_aborted`, and `bench`: this layer owns the signal chain, so the
|
|
1528
|
+
* cause set upstream has to survive it. Wrapping would turn `timeout`'s
|
|
1529
|
+
* `timeout_error` into an abort, and would flatten the runner's
|
|
1530
|
+
* `aborted_error('received SIGINT')` into a bare 'aborted' that
|
|
1531
|
+
* `runner.ts`'s catch cannot repair, since that repair only fires when the
|
|
1532
|
+
* escaping error is not already an `aborted_error`.
|
|
1486
1533
|
*
|
|
1487
|
-
*
|
|
1488
|
-
* `
|
|
1534
|
+
* The engine's retry deliberately does the opposite; `#policy`'s
|
|
1535
|
+
* `AbortErrorFactory` is where the two meet.
|
|
1489
1536
|
*/
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
await new Promise((resolve, reject) => {
|
|
1493
|
-
if (ctx.abort.aborted) {
|
|
1494
|
-
const reason = ctx.abort.reason;
|
|
1495
|
-
reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
|
|
1496
|
-
return;
|
|
1497
|
-
}
|
|
1498
|
-
const timer = setTimeout(() => {
|
|
1499
|
-
ctx.abort.removeEventListener("abort", on_abort);
|
|
1500
|
-
resolve();
|
|
1501
|
-
}, ms);
|
|
1502
|
-
const on_abort = () => {
|
|
1503
|
-
clearTimeout(timer);
|
|
1504
|
-
const reason = ctx.abort.reason;
|
|
1505
|
-
reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
|
|
1506
|
-
};
|
|
1507
|
-
ctx.abort.addEventListener("abort", on_abort, { once: true });
|
|
1508
|
-
});
|
|
1537
|
+
function to_abort_error(reason) {
|
|
1538
|
+
return reason instanceof Error ? reason : new aborted_error("aborted", { reason });
|
|
1509
1539
|
}
|
|
1510
1540
|
/**
|
|
1511
1541
|
* Build a retrying step around `inner`.
|
|
@@ -1518,14 +1548,18 @@ function retry(inner, config) {
|
|
|
1518
1548
|
const id = next_id$5();
|
|
1519
1549
|
const max_attempts = Math.max(1, Math.floor(config.max_attempts));
|
|
1520
1550
|
const backoff_ms = config.backoff_ms ?? DEFAULT_BACKOFF_MS;
|
|
1551
|
+
const max_delay_ms = config.max_delay_ms ?? DEFAULT_MAX_DELAY_MS;
|
|
1552
|
+
const jitter = config.jitter ?? true;
|
|
1521
1553
|
const on_error = config.on_error;
|
|
1554
|
+
const backoff_policy = {
|
|
1555
|
+
initial_delay_ms: backoff_ms,
|
|
1556
|
+
max_delay_ms,
|
|
1557
|
+
jitter
|
|
1558
|
+
};
|
|
1522
1559
|
const run_fn = async (input, ctx) => {
|
|
1523
1560
|
let last_err = void 0;
|
|
1524
1561
|
for (let attempt = 1; attempt <= max_attempts; attempt += 1) {
|
|
1525
|
-
if (ctx.abort.aborted)
|
|
1526
|
-
const reason = ctx.abort.reason;
|
|
1527
|
-
throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
|
|
1528
|
-
}
|
|
1562
|
+
if (ctx.abort.aborted) throw to_abort_error(ctx.abort.reason);
|
|
1529
1563
|
try {
|
|
1530
1564
|
return await dispatch_step(inner, input, ctx);
|
|
1531
1565
|
} catch (err) {
|
|
@@ -1533,14 +1567,16 @@ function retry(inner, config) {
|
|
|
1533
1567
|
last_err = err;
|
|
1534
1568
|
if (on_error) on_error(err, attempt);
|
|
1535
1569
|
if (attempt >= max_attempts) break;
|
|
1536
|
-
await
|
|
1570
|
+
await wait_with_abort(compute_backoff(backoff_policy, attempt - 1), ctx.abort, to_abort_error);
|
|
1537
1571
|
}
|
|
1538
1572
|
}
|
|
1539
1573
|
throw last_err;
|
|
1540
1574
|
};
|
|
1541
1575
|
const config_meta = {
|
|
1542
1576
|
max_attempts,
|
|
1543
|
-
backoff_ms
|
|
1577
|
+
backoff_ms,
|
|
1578
|
+
max_delay_ms,
|
|
1579
|
+
jitter
|
|
1544
1580
|
};
|
|
1545
1581
|
if (on_error) config_meta["on_error"] = on_error;
|
|
1546
1582
|
if (config.name !== void 0) config_meta["display_name"] = config.name;
|
|
@@ -1690,11 +1726,14 @@ register_traced_kind("timeout");
|
|
|
1690
1726
|
* `body` call, an optional `guard` step inspects (and may transform) the state
|
|
1691
1727
|
* and decides whether to stop. When `guard.stop` is true, the loop exits
|
|
1692
1728
|
* "converged"; otherwise it continues until `max_rounds`. `finish` projects
|
|
1693
|
-
* the final state to the loop's output value
|
|
1729
|
+
* the final state to the loop's output value, and is the loop's only output
|
|
1730
|
+
* channel: `loop` returns `Step<i, o>`, not an envelope around `o`.
|
|
1694
1731
|
*
|
|
1695
|
-
* Non-convergence is data, not error
|
|
1696
|
-
*
|
|
1697
|
-
*
|
|
1732
|
+
* Non-convergence is data, not error, and `finish` is where that data arrives:
|
|
1733
|
+
* its second argument is the `LoopOutcome` (`{ converged, rounds }`), so a
|
|
1734
|
+
* projection can fold either field into its own result shape, the way
|
|
1735
|
+
* `adversarial` and `consensus` do. A projection that wants the whole outcome
|
|
1736
|
+
* verbatim writes `finish: (state, outcome) => ({ value: state, ...outcome })`.
|
|
1698
1737
|
*
|
|
1699
1738
|
* Cancellation: between rounds the parent `ctx.abort` is honored; a pending
|
|
1700
1739
|
* abort short-circuits and propagates `ctx.abort.reason`. The body and guard
|
|
@@ -1714,8 +1753,9 @@ function next_id$2(name) {
|
|
|
1714
1753
|
*
|
|
1715
1754
|
* Threads `state` through up to `max_rounds` runs of `body`, lets the
|
|
1716
1755
|
* optional `guard` stop early, then projects the final state through
|
|
1717
|
-
* `finish`.
|
|
1718
|
-
* converged run from an exhausted one
|
|
1756
|
+
* `finish`. `finish` also receives `{ converged, rounds }`, so a projection
|
|
1757
|
+
* can tell a converged run from an exhausted one without the loop wrapping
|
|
1758
|
+
* its output.
|
|
1719
1759
|
*/
|
|
1720
1760
|
function loop(config) {
|
|
1721
1761
|
const { init, body, guard, finish, name } = config;
|
|
@@ -1739,11 +1779,10 @@ function loop(config) {
|
|
|
1739
1779
|
}
|
|
1740
1780
|
}
|
|
1741
1781
|
}
|
|
1742
|
-
return {
|
|
1743
|
-
value: finish(state, round),
|
|
1782
|
+
return finish(state, {
|
|
1744
1783
|
converged,
|
|
1745
1784
|
rounds: round
|
|
1746
|
-
};
|
|
1785
|
+
});
|
|
1747
1786
|
};
|
|
1748
1787
|
const config_meta = { max_rounds: rounds_limit };
|
|
1749
1788
|
if (name !== void 0) config_meta["display_name"] = name;
|
|
@@ -1867,6 +1906,63 @@ function checkpoint(inner, config) {
|
|
|
1867
1906
|
}
|
|
1868
1907
|
register_traced_kind("checkpoint");
|
|
1869
1908
|
//#endregion
|
|
1909
|
+
//#region src/schema/validate.ts
|
|
1910
|
+
/**
|
|
1911
|
+
* Validate `value` against `schema`, returning the typed value or the issues.
|
|
1912
|
+
*
|
|
1913
|
+
* Always async, even for a validator that answers synchronously: the spec
|
|
1914
|
+
* permits `validate` to return either a result or a promise of one, and
|
|
1915
|
+
* fascicle cannot know which a given vendor does. Awaiting a non-promise is
|
|
1916
|
+
* cheap; guessing wrong is a silent bug.
|
|
1917
|
+
*/
|
|
1918
|
+
async function validate_schema(schema, value) {
|
|
1919
|
+
const result = await schema["~standard"].validate(value);
|
|
1920
|
+
if (result.issues) return {
|
|
1921
|
+
ok: false,
|
|
1922
|
+
issues: result.issues.map(normalize_issue)
|
|
1923
|
+
};
|
|
1924
|
+
return {
|
|
1925
|
+
ok: true,
|
|
1926
|
+
value: result.value
|
|
1927
|
+
};
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Flatten one vendor issue into fascicle's shape.
|
|
1931
|
+
*
|
|
1932
|
+
* The spec allows a path segment to be a bare key or a `{ key }` wrapper, and
|
|
1933
|
+
* allows the path to be absent entirely. Normalizing here means no consumer has
|
|
1934
|
+
* to know which vendor produced the issue.
|
|
1935
|
+
*/
|
|
1936
|
+
function normalize_issue(issue) {
|
|
1937
|
+
if (issue.path === void 0) return { message: issue.message };
|
|
1938
|
+
const path = issue.path.map((segment) => typeof segment === "object" ? segment.key : segment);
|
|
1939
|
+
return {
|
|
1940
|
+
message: issue.message,
|
|
1941
|
+
path
|
|
1942
|
+
};
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Render issues as the single line that goes into an error message or a repair
|
|
1946
|
+
* prompt fed back to the model.
|
|
1947
|
+
*
|
|
1948
|
+
* Paths are dotted (`address.city`, `items.0.name`) rather than bracketed for
|
|
1949
|
+
* indices: the model reads it as a hint about which field to fix, and one
|
|
1950
|
+
* consistent separator is easier to follow than two.
|
|
1951
|
+
*/
|
|
1952
|
+
function format_schema_issues(issues) {
|
|
1953
|
+
if (issues.length === 0) return "unknown schema issue";
|
|
1954
|
+
return issues.map(format_issue).join("; ");
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* Render one issue as `path: message`, or just the message when the vendor
|
|
1958
|
+
* reported no path (a failure about the value as a whole).
|
|
1959
|
+
*/
|
|
1960
|
+
function format_issue(issue) {
|
|
1961
|
+
const path = issue.path;
|
|
1962
|
+
if (path === void 0 || path.length === 0) return issue.message;
|
|
1963
|
+
return `${path.map((segment) => String(segment)).join(".")}: ${issue.message}`;
|
|
1964
|
+
}
|
|
1965
|
+
//#endregion
|
|
1870
1966
|
//#region src/core/suspend.ts
|
|
1871
1967
|
/**
|
|
1872
1968
|
* suspend: human-in-the-loop pause.
|
|
@@ -1878,7 +1974,7 @@ register_traced_kind("checkpoint");
|
|
|
1878
1974
|
* with `run_options.resume_data[id]` populated), the provided value is
|
|
1879
1975
|
* validated against `resume_schema` and passed to `combine(input, resume,
|
|
1880
1976
|
* ctx)`; the result is returned. Invalid resume data throws
|
|
1881
|
-
* `resume_validation_error`
|
|
1977
|
+
* `resume_validation_error` carrying the vendor-neutral issue list.
|
|
1882
1978
|
*/
|
|
1883
1979
|
/**
|
|
1884
1980
|
* Structurally detect a `Step` returned from `combine`.
|
|
@@ -1911,12 +2007,9 @@ function suspend(config) {
|
|
|
1911
2007
|
await on_fn(input, ctx);
|
|
1912
2008
|
throw new suspended_error(suspend_id, { input });
|
|
1913
2009
|
}
|
|
1914
|
-
const parsed = resume_schema
|
|
1915
|
-
if (!parsed.
|
|
1916
|
-
|
|
1917
|
-
throw new resume_validation_error(`resume data for ${suspend_id} failed validation`, issues);
|
|
1918
|
-
}
|
|
1919
|
-
const result = await combine_fn(input, parsed.data, ctx);
|
|
2010
|
+
const parsed = await validate_schema(resume_schema, resume_value);
|
|
2011
|
+
if (!parsed.ok) throw new resume_validation_error(`resume data for ${suspend_id} failed validation`, parsed.issues);
|
|
2012
|
+
const result = await combine_fn(input, parsed.value, ctx);
|
|
1920
2013
|
if (is_step(result)) return dispatch_step(result, input, ctx);
|
|
1921
2014
|
return result;
|
|
1922
2015
|
};
|
|
@@ -2104,44 +2197,47 @@ function is_step_kind(value) {
|
|
|
2104
2197
|
//#endregion
|
|
2105
2198
|
//#region src/core/trajectory.ts
|
|
2106
2199
|
/**
|
|
2107
|
-
*
|
|
2108
|
-
*
|
|
2109
|
-
*
|
|
2110
|
-
*
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2200
|
+
* The wire gate: a non-array object carrying a string `kind`.
|
|
2201
|
+
*
|
|
2202
|
+
* True for every well-known kind as well, since `custom` is the fallback shape
|
|
2203
|
+
* rather than a disjoint case.
|
|
2204
|
+
*/
|
|
2205
|
+
function is_custom_trajectory_event(value) {
|
|
2206
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2207
|
+
if (Array.isArray(value)) return false;
|
|
2208
|
+
return typeof value.kind === "string";
|
|
2209
|
+
}
|
|
2210
|
+
/** A composer span open: both `span_id` and `name` must be present as strings. */
|
|
2211
|
+
function is_span_start_event(value) {
|
|
2212
|
+
if (!is_custom_trajectory_event(value)) return false;
|
|
2213
|
+
if (value.kind !== "span_start") return false;
|
|
2214
|
+
return typeof value["span_id"] === "string" && typeof value["name"] === "string";
|
|
2215
|
+
}
|
|
2216
|
+
/** A composer span close: `span_id` must be present as a string, `name` need not be. */
|
|
2217
|
+
function is_span_end_event(value) {
|
|
2218
|
+
if (!is_custom_trajectory_event(value)) return false;
|
|
2219
|
+
return value.kind === "span_end" && typeof value["span_id"] === "string";
|
|
2220
|
+
}
|
|
2221
|
+
/** A `ctx.emit` event: the kind alone identifies it, the payload is the caller's. */
|
|
2222
|
+
function is_emit_event(value) {
|
|
2223
|
+
return is_custom_trajectory_event(value) && value.kind === "emit";
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* Parse one wire value into a trajectory event, `safeParse`-shaped.
|
|
2227
|
+
*
|
|
2228
|
+
* On success `data` is the value itself, not a copy, so nothing on the line is
|
|
2229
|
+
* dropped or reordered on the way through.
|
|
2230
|
+
*/
|
|
2231
|
+
function parse_trajectory_event(value) {
|
|
2232
|
+
if (!is_custom_trajectory_event(value)) return {
|
|
2233
|
+
success: false,
|
|
2234
|
+
error: /* @__PURE__ */ new Error("not a trajectory event: expected an object with a string 'kind'")
|
|
2235
|
+
};
|
|
2236
|
+
return {
|
|
2237
|
+
success: true,
|
|
2238
|
+
data: value
|
|
2239
|
+
};
|
|
2240
|
+
}
|
|
2145
2241
|
//#endregion
|
|
2146
2242
|
//#region src/core/index.ts
|
|
2147
2243
|
/**
|
|
@@ -2154,6 +2250,6 @@ const trajectory_event_schema = z.union([
|
|
|
2154
2250
|
* and surface through the umbrella package.
|
|
2155
2251
|
*/
|
|
2156
2252
|
//#endregion
|
|
2157
|
-
export {
|
|
2253
|
+
export { aborted_error as A, map as C, describe as D, sequence as E, flow_schema_default as F, resume_validation_error as M, suspended_error as N, step as O, timeout_error as P, pipe as S, parallel as T, timeout as _, parse_trajectory_event as a, compute_backoff as b, scope as c, suspend as d, format_schema_issues as f, loop as g, compose as h, is_span_start_event as i, describe_cycle_error as j, run as k, stash as l, checkpoint as m, is_emit_event as n, STEP_KINDS as o, validate_schema as p, is_span_end_event as r, is_step_kind as s, is_custom_trajectory_event as t, use as u, fallback as v, branch as w, wait_with_abort as x, retry as y };
|
|
2158
2254
|
|
|
2159
|
-
//# sourceMappingURL=core-
|
|
2255
|
+
//# sourceMappingURL=core-Ww6An4CS.js.map
|