fascicle 0.10.2 → 0.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -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-DkuJqLwd.js} +170 -88
- package/dist/core-DkuJqLwd.js.map +1 -0
- package/dist/index.d.ts +1124 -5
- package/dist/index.js +467 -939
- package/dist/index.js.map +1 -1
- package/dist/invoke-D9pxbZcu.js +451 -0
- package/dist/invoke-D9pxbZcu.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-kO1JoGNZ.js +253 -0
- package/dist/types-kO1JoGNZ.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/dist/index.js
CHANGED
|
@@ -1,16 +1,71 @@
|
|
|
1
|
-
import { A as
|
|
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";
|
|
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
4
|
import { createHash } from "node:crypto";
|
|
4
|
-
import { z } from "zod";
|
|
5
5
|
import { mkdir, open, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
6
6
|
import { dirname, join, resolve } from "node:path";
|
|
7
7
|
import { createReadStream, existsSync, mkdtempSync, statSync, watch, writeFileSync } from "node:fs";
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
10
|
-
import { NoObjectGeneratedError, Output, generateText, isStepCount, streamText, tool } from "ai";
|
|
11
10
|
import { createServer } from "node:http";
|
|
12
11
|
import { fileURLToPath } from "node:url";
|
|
13
12
|
import { parseArgs } from "node:util";
|
|
13
|
+
//#region src/schema/errors.ts
|
|
14
|
+
/**
|
|
15
|
+
* The one error this zone raises.
|
|
16
|
+
*
|
|
17
|
+
* It lives here rather than in core's taxonomy because core imports this zone,
|
|
18
|
+
* and reaching back for an error class would close a cycle.
|
|
19
|
+
*/
|
|
20
|
+
var schema_not_convertible_error = class extends Error {
|
|
21
|
+
kind = "schema_not_convertible_error";
|
|
22
|
+
vendor;
|
|
23
|
+
constructor(vendor, message) {
|
|
24
|
+
super(message ?? `schema vendor '${vendor}' does not implement Standard JSON Schema, so it cannot be sent to a model as JSON Schema`);
|
|
25
|
+
this.name = "schema_not_convertible_error";
|
|
26
|
+
this.vendor = vendor;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/schema/json_schema.ts
|
|
31
|
+
/**
|
|
32
|
+
* JSON Schema emission for schemas that reach a model.
|
|
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.
|
|
41
|
+
*/
|
|
42
|
+
const DEFAULT_TARGET = "draft-2020-12";
|
|
43
|
+
/**
|
|
44
|
+
* Emit JSON Schema for `schema`, targeting draft-2020-12 unless told otherwise.
|
|
45
|
+
*
|
|
46
|
+
* `target` is passed explicitly on every call because the spec makes it a
|
|
47
|
+
* required argument of the converter, even where a vendor tolerates its
|
|
48
|
+
* omission. A vendor that implements Standard Schema but not Standard JSON
|
|
49
|
+
* Schema raises `schema_not_convertible_error` naming itself, so the message
|
|
50
|
+
* says which library to swap rather than just that something failed.
|
|
51
|
+
*/
|
|
52
|
+
function to_json_schema(schema, options = {}) {
|
|
53
|
+
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 });
|
|
56
|
+
return options.strip_meta === true ? strip_meta_keys(json) : json;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Drop the top-level `$schema` and `$id` keys.
|
|
60
|
+
*
|
|
61
|
+
* `claude --json-schema` rejects both, and the field constraints alone drive
|
|
62
|
+
* constrained decode, so the CLI adapter asks for a stripped emission.
|
|
63
|
+
*/
|
|
64
|
+
function strip_meta_keys(json) {
|
|
65
|
+
const { $schema: _schema, $id: _id, ...rest } = json;
|
|
66
|
+
return rest;
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
14
69
|
//#region src/composites/adversarial.ts
|
|
15
70
|
/**
|
|
16
71
|
* adversarial: build-and-critique loop.
|
|
@@ -530,7 +585,7 @@ async function read_jsonl(file_path, ctx) {
|
|
|
530
585
|
});
|
|
531
586
|
continue;
|
|
532
587
|
}
|
|
533
|
-
const result =
|
|
588
|
+
const result = parse_trajectory_event(parsed);
|
|
534
589
|
if (result.success) events.push(result.data);
|
|
535
590
|
else ctx.trajectory.record({
|
|
536
591
|
kind: "learn.parse_error",
|
|
@@ -544,7 +599,7 @@ async function read_jsonl(file_path, ctx) {
|
|
|
544
599
|
* Throw the abort reason (wrapped in `aborted_error` if needed) when the run
|
|
545
600
|
* has been cancelled.
|
|
546
601
|
*/
|
|
547
|
-
function throw_if_aborted$
|
|
602
|
+
function throw_if_aborted$2(ctx) {
|
|
548
603
|
if (!ctx.abort.aborted) return;
|
|
549
604
|
const reason = ctx.abort.reason;
|
|
550
605
|
if (reason instanceof aborted_error) throw reason;
|
|
@@ -562,7 +617,7 @@ async function resolve_events(source, ctx) {
|
|
|
562
617
|
const file_paths = source.kind === "paths" ? [...source.paths] : (await walk_jsonl(source.dir)).toSorted();
|
|
563
618
|
const all = [];
|
|
564
619
|
for (const p of file_paths) {
|
|
565
|
-
throw_if_aborted$
|
|
620
|
+
throw_if_aborted$2(ctx);
|
|
566
621
|
const events = await read_jsonl(p, ctx);
|
|
567
622
|
all.push(...events);
|
|
568
623
|
}
|
|
@@ -705,6 +760,26 @@ function tournament(config) {
|
|
|
705
760
|
return compose(config.name ?? "tournament", inner);
|
|
706
761
|
}
|
|
707
762
|
//#endregion
|
|
763
|
+
//#region src/composites/errors.ts
|
|
764
|
+
/**
|
|
765
|
+
* Typed errors for the composites layer.
|
|
766
|
+
*
|
|
767
|
+
* Listed alongside src/core/errors.ts, src/engine/errors.ts, and
|
|
768
|
+
* src/mcp/errors.ts in the `no-class` rule ignores: `instanceof` branching is
|
|
769
|
+
* how a caller tells a benched flow's usage error apart from a case failure.
|
|
770
|
+
*/
|
|
771
|
+
var bench_suspend_error = class extends Error {
|
|
772
|
+
kind = "bench_suspend_error";
|
|
773
|
+
case_id;
|
|
774
|
+
suspend_id;
|
|
775
|
+
constructor(case_id, suspend_id, message) {
|
|
776
|
+
super(message ?? `bench: case ${case_id} suspended at ${suspend_id}; bench cannot resume a suspended flow`);
|
|
777
|
+
this.name = "bench_suspend_error";
|
|
778
|
+
this.case_id = case_id;
|
|
779
|
+
this.suspend_id = suspend_id;
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
//#endregion
|
|
708
783
|
//#region src/composites/bench.ts
|
|
709
784
|
/**
|
|
710
785
|
* bench: run a flow against a fixture set, score each result, return a report.
|
|
@@ -731,12 +806,21 @@ function tournament(config) {
|
|
|
731
806
|
* judge spans land in the case's trajectory file (or push). A judge that
|
|
732
807
|
* throws or returns undefined abstains: the entry is omitted from
|
|
733
808
|
* `case.scores` and the case does not contribute to that judge's mean.
|
|
809
|
+
*
|
|
810
|
+
* Control-flow signals are not case failures and never reach a `CaseResult`.
|
|
811
|
+
* `abort` forwards to every per-case `run` and is re-checked before each case
|
|
812
|
+
* is claimed, so cancelling rejects the whole bench rather than returning a
|
|
813
|
+
* report that silently covers fewer cases than it was given. A
|
|
814
|
+
* `suspended_error` from an approval gate rejects with `bench_suspend_error`:
|
|
815
|
+
* `bench` has no resume path, so a suspend is a usage error, not a zero score.
|
|
734
816
|
*/
|
|
735
817
|
async function bench(flow, cases, judges, options = {}) {
|
|
736
818
|
const run_id = options.run_id ?? `bench-${String(Date.now())}-${random_suffix()}`;
|
|
737
819
|
const flow_name = describe_flow_name(flow);
|
|
738
820
|
const concurrency = resolve_concurrency(options.concurrency, cases.length);
|
|
739
821
|
const install_signal_handlers = options.install_signal_handlers ?? false;
|
|
822
|
+
const run_options = options.abort === void 0 ? {} : { abort: options.abort };
|
|
823
|
+
throw_if_aborted$1(options.abort);
|
|
740
824
|
if (options.trajectory_dir !== void 0) await mkdir(options.trajectory_dir, { recursive: true });
|
|
741
825
|
const judge_entries = Object.entries(judges);
|
|
742
826
|
const run_one = async (bc) => {
|
|
@@ -753,10 +837,12 @@ async function bench(flow, cases, judges, options = {}) {
|
|
|
753
837
|
try {
|
|
754
838
|
output = await run(flow, bc.input, {
|
|
755
839
|
trajectory: case_logger,
|
|
756
|
-
install_signal_handlers
|
|
840
|
+
install_signal_handlers,
|
|
841
|
+
...run_options
|
|
757
842
|
});
|
|
758
843
|
ok = true;
|
|
759
844
|
} catch (err) {
|
|
845
|
+
rethrow_control_flow(err, bc.id);
|
|
760
846
|
error = err instanceof Error ? err.message : String(err);
|
|
761
847
|
ok = false;
|
|
762
848
|
}
|
|
@@ -775,9 +861,11 @@ async function bench(flow, cases, judges, options = {}) {
|
|
|
775
861
|
try {
|
|
776
862
|
raw = await run(judge, judge_input, {
|
|
777
863
|
trajectory: case_logger,
|
|
778
|
-
install_signal_handlers
|
|
864
|
+
install_signal_handlers,
|
|
865
|
+
...run_options
|
|
779
866
|
});
|
|
780
|
-
} catch {
|
|
867
|
+
} catch (err) {
|
|
868
|
+
rethrow_control_flow(err, bc.id);
|
|
781
869
|
continue;
|
|
782
870
|
}
|
|
783
871
|
const normalized = normalize_score(raw);
|
|
@@ -799,7 +887,8 @@ async function bench(flow, cases, judges, options = {}) {
|
|
|
799
887
|
if (options.on_case) options.on_case(result);
|
|
800
888
|
return result;
|
|
801
889
|
};
|
|
802
|
-
const cases_out = await run_with_concurrency(cases, concurrency, run_one);
|
|
890
|
+
const cases_out = await run_with_concurrency(cases, concurrency, run_one, options.abort);
|
|
891
|
+
throw_if_aborted$1(options.abort);
|
|
803
892
|
return {
|
|
804
893
|
flow_name,
|
|
805
894
|
run_id,
|
|
@@ -808,6 +897,32 @@ async function bench(flow, cases, judges, options = {}) {
|
|
|
808
897
|
};
|
|
809
898
|
}
|
|
810
899
|
/**
|
|
900
|
+
* Rethrows the control-flow signals that must never become a `CaseResult`.
|
|
901
|
+
*
|
|
902
|
+
* An `aborted_error` cancels the whole bench: a report claiming every
|
|
903
|
+
* remaining case failed is worse than no report. A `suspended_error` becomes
|
|
904
|
+
* `bench_suspend_error` naming the case, because `bench` cannot resume an
|
|
905
|
+
* approval gate and scoring the paused case as a failure corrupts the
|
|
906
|
+
* benchmark. Anything else returns, and the caller records it as a failure.
|
|
907
|
+
*/
|
|
908
|
+
function rethrow_control_flow(err, case_id) {
|
|
909
|
+
if (err instanceof aborted_error) throw err;
|
|
910
|
+
if (err instanceof suspended_error) throw new bench_suspend_error(case_id, err.suspend_id);
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Rejects once `signal` has fired, so an abort stops the bench claiming
|
|
914
|
+
* further cases instead of running the queue to completion.
|
|
915
|
+
*
|
|
916
|
+
* Mirrors core's abort shape: an `Error` reason propagates verbatim, anything
|
|
917
|
+
* else is wrapped, so a caller aborting with its own `aborted_error` sees that
|
|
918
|
+
* instance rather than a copy.
|
|
919
|
+
*/
|
|
920
|
+
function throw_if_aborted$1(signal) {
|
|
921
|
+
if (signal?.aborted !== true) return;
|
|
922
|
+
const reason = signal.reason;
|
|
923
|
+
throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
811
926
|
* Aggregates per-case results into the report summary.
|
|
812
927
|
*
|
|
813
928
|
* A judge's mean only averages the cases where that judge produced a score;
|
|
@@ -900,14 +1015,20 @@ function create_cost_tracker() {
|
|
|
900
1015
|
* Uses a shared-index worker pool: each of the `limit` workers claims the
|
|
901
1016
|
* next unclaimed index and writes its result into that slot, so completion
|
|
902
1017
|
* order never reorders the output.
|
|
1018
|
+
*
|
|
1019
|
+
* `abort` is re-checked before each claim, so a signal that fires mid-run
|
|
1020
|
+
* halts scheduling at the queue rather than only cancelling work already in
|
|
1021
|
+
* flight. The full fan-out path has no queue to halt: every item is already
|
|
1022
|
+
* running, so the caller re-checks the signal before reading the results.
|
|
903
1023
|
*/
|
|
904
|
-
async function run_with_concurrency(items, limit, fn) {
|
|
1024
|
+
async function run_with_concurrency(items, limit, fn, abort) {
|
|
905
1025
|
if (items.length === 0) return [];
|
|
906
1026
|
if (limit >= items.length) return Promise.all(items.map((it) => fn(it)));
|
|
907
1027
|
const results = Array.from({ length: items.length });
|
|
908
1028
|
let next = 0;
|
|
909
1029
|
const worker = async () => {
|
|
910
1030
|
while (true) {
|
|
1031
|
+
throw_if_aborted$1(abort);
|
|
911
1032
|
const idx = next;
|
|
912
1033
|
next += 1;
|
|
913
1034
|
if (idx >= items.length) return;
|
|
@@ -969,7 +1090,7 @@ function random_suffix() {
|
|
|
969
1090
|
* Narrows an unknown value to a plain string-keyed record (non-null object,
|
|
970
1091
|
* not an array).
|
|
971
1092
|
*/
|
|
972
|
-
function is_record(v) {
|
|
1093
|
+
function is_record$1(v) {
|
|
973
1094
|
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
974
1095
|
}
|
|
975
1096
|
/**
|
|
@@ -985,7 +1106,7 @@ function deep_equal(a, b) {
|
|
|
985
1106
|
for (let i = 0; i < a.length; i += 1) if (!deep_equal(a[i], b[i])) return false;
|
|
986
1107
|
return true;
|
|
987
1108
|
}
|
|
988
|
-
if (!is_record(a) || !is_record(b)) return false;
|
|
1109
|
+
if (!is_record$1(a) || !is_record$1(b)) return false;
|
|
989
1110
|
const ak = Object.keys(a).toSorted();
|
|
990
1111
|
const bk = Object.keys(b).toSorted();
|
|
991
1112
|
if (ak.length !== bk.length) return false;
|
|
@@ -1081,7 +1202,7 @@ function parse_score(reply, scale) {
|
|
|
1081
1202
|
} catch {
|
|
1082
1203
|
return;
|
|
1083
1204
|
}
|
|
1084
|
-
if (!is_record(parsed)) return void 0;
|
|
1205
|
+
if (!is_record$1(parsed)) return void 0;
|
|
1085
1206
|
const raw_score = parsed["score"];
|
|
1086
1207
|
if (typeof raw_score !== "number" || !Number.isFinite(raw_score)) return void 0;
|
|
1087
1208
|
const clamped = Math.max(scale.min, Math.min(scale.max, raw_score));
|
|
@@ -1398,191 +1519,6 @@ function compute_cost(usage, pricing, provider) {
|
|
|
1398
1519
|
return breakdown;
|
|
1399
1520
|
}
|
|
1400
1521
|
//#endregion
|
|
1401
|
-
//#region src/engine/errors.ts
|
|
1402
|
-
var rate_limit_error = class extends Error {
|
|
1403
|
-
kind = "rate_limit_error";
|
|
1404
|
-
retry_after_ms;
|
|
1405
|
-
attempts;
|
|
1406
|
-
status;
|
|
1407
|
-
constructor(message, metadata = {}) {
|
|
1408
|
-
super(message);
|
|
1409
|
-
this.name = "rate_limit_error";
|
|
1410
|
-
this.retry_after_ms = metadata.retry_after_ms;
|
|
1411
|
-
this.attempts = metadata.attempts ?? 0;
|
|
1412
|
-
this.status = metadata.status;
|
|
1413
|
-
}
|
|
1414
|
-
};
|
|
1415
|
-
var provider_error = class extends Error {
|
|
1416
|
-
kind = "provider_error";
|
|
1417
|
-
status;
|
|
1418
|
-
body;
|
|
1419
|
-
cause_kind;
|
|
1420
|
-
constructor(message, metadata = {}) {
|
|
1421
|
-
super(message);
|
|
1422
|
-
this.name = "provider_error";
|
|
1423
|
-
this.status = metadata.status;
|
|
1424
|
-
this.body = metadata.body;
|
|
1425
|
-
this.cause_kind = metadata.cause_kind;
|
|
1426
|
-
}
|
|
1427
|
-
};
|
|
1428
|
-
/**
|
|
1429
|
-
* Turn-timeout expiry. Thrown by the engine-owned retry_turn wrapper when a
|
|
1430
|
-
* single invoke_turn exceeds `turn_timeout_ms` before any chunk streamed.
|
|
1431
|
-
* Its `kind` is the RetryFailureKind wire value `'timeout'` (not the class
|
|
1432
|
-
* name) on purpose: that is the discriminant classify_retryable /
|
|
1433
|
-
* classify_provider_error already key on, so the shared classifier treats an
|
|
1434
|
-
* expiry as retryable without any timeout-specific branch. A mid-stream
|
|
1435
|
-
* expiry never reaches here; retry_turn converts it to a non-retryable
|
|
1436
|
-
* stream interruption first.
|
|
1437
|
-
*/
|
|
1438
|
-
var turn_timeout_error = class extends Error {
|
|
1439
|
-
kind = "timeout";
|
|
1440
|
-
timeout_ms;
|
|
1441
|
-
step_index;
|
|
1442
|
-
constructor(timeout_ms, step_index) {
|
|
1443
|
-
super(`turn exceeded turn_timeout_ms budget of ${timeout_ms}ms`);
|
|
1444
|
-
this.name = "turn_timeout_error";
|
|
1445
|
-
this.timeout_ms = timeout_ms;
|
|
1446
|
-
this.step_index = step_index;
|
|
1447
|
-
}
|
|
1448
|
-
};
|
|
1449
|
-
var schema_validation_error = class extends Error {
|
|
1450
|
-
kind = "schema_validation_error";
|
|
1451
|
-
zod_error;
|
|
1452
|
-
raw_text;
|
|
1453
|
-
constructor(message, zod_error, raw_text) {
|
|
1454
|
-
super(message);
|
|
1455
|
-
this.name = "schema_validation_error";
|
|
1456
|
-
this.zod_error = zod_error;
|
|
1457
|
-
this.raw_text = raw_text;
|
|
1458
|
-
}
|
|
1459
|
-
};
|
|
1460
|
-
var tool_error = class extends Error {
|
|
1461
|
-
kind = "tool_error";
|
|
1462
|
-
tool_name;
|
|
1463
|
-
tool_call_id;
|
|
1464
|
-
cause;
|
|
1465
|
-
constructor(message, metadata) {
|
|
1466
|
-
super(message);
|
|
1467
|
-
this.name = "tool_error";
|
|
1468
|
-
this.tool_name = metadata.tool_name;
|
|
1469
|
-
this.tool_call_id = metadata.tool_call_id;
|
|
1470
|
-
this.cause = metadata.cause;
|
|
1471
|
-
}
|
|
1472
|
-
};
|
|
1473
|
-
var tool_approval_denied_error = class extends Error {
|
|
1474
|
-
kind = "tool_approval_denied_error";
|
|
1475
|
-
tool_name;
|
|
1476
|
-
step_index;
|
|
1477
|
-
tool_call_id;
|
|
1478
|
-
constructor(message, metadata) {
|
|
1479
|
-
super(message);
|
|
1480
|
-
this.name = "tool_approval_denied_error";
|
|
1481
|
-
this.tool_name = metadata.tool_name;
|
|
1482
|
-
this.step_index = metadata.step_index;
|
|
1483
|
-
this.tool_call_id = metadata.tool_call_id;
|
|
1484
|
-
}
|
|
1485
|
-
};
|
|
1486
|
-
var model_required_error = class extends Error {
|
|
1487
|
-
kind = "model_required_error";
|
|
1488
|
-
constructor(message = "no model specified: pass `model` to generate() or set `defaults.model` on the engine") {
|
|
1489
|
-
super(message);
|
|
1490
|
-
this.name = "model_required_error";
|
|
1491
|
-
}
|
|
1492
|
-
};
|
|
1493
|
-
var provider_not_configured_error = class extends Error {
|
|
1494
|
-
kind = "provider_not_configured_error";
|
|
1495
|
-
provider;
|
|
1496
|
-
constructor(provider) {
|
|
1497
|
-
super(`provider '${provider}' is not configured on this engine`);
|
|
1498
|
-
this.name = "provider_not_configured_error";
|
|
1499
|
-
this.provider = provider;
|
|
1500
|
-
}
|
|
1501
|
-
};
|
|
1502
|
-
var engine_config_error = class extends Error {
|
|
1503
|
-
kind = "engine_config_error";
|
|
1504
|
-
provider;
|
|
1505
|
-
constructor(message, provider) {
|
|
1506
|
-
super(message);
|
|
1507
|
-
this.name = "engine_config_error";
|
|
1508
|
-
this.provider = provider;
|
|
1509
|
-
}
|
|
1510
|
-
};
|
|
1511
|
-
var on_chunk_error = class extends Error {
|
|
1512
|
-
kind = "on_chunk_error";
|
|
1513
|
-
cause;
|
|
1514
|
-
constructor(message, cause) {
|
|
1515
|
-
super(message);
|
|
1516
|
-
this.name = "on_chunk_error";
|
|
1517
|
-
this.cause = cause;
|
|
1518
|
-
}
|
|
1519
|
-
};
|
|
1520
|
-
var provider_capability_error = class extends Error {
|
|
1521
|
-
kind = "provider_capability_error";
|
|
1522
|
-
provider;
|
|
1523
|
-
capability;
|
|
1524
|
-
constructor(provider, capability, detail) {
|
|
1525
|
-
const suffix = detail !== void 0 ? `: ${detail}` : "";
|
|
1526
|
-
super(`provider '${provider}' does not support '${capability}'${suffix}`);
|
|
1527
|
-
this.name = "provider_capability_error";
|
|
1528
|
-
this.provider = provider;
|
|
1529
|
-
this.capability = capability;
|
|
1530
|
-
}
|
|
1531
|
-
};
|
|
1532
|
-
var engine_disposed_error = class extends Error {
|
|
1533
|
-
kind = "engine_disposed_error";
|
|
1534
|
-
constructor(message = "engine has been disposed; further calls are not permitted") {
|
|
1535
|
-
super(message);
|
|
1536
|
-
this.name = "engine_disposed_error";
|
|
1537
|
-
}
|
|
1538
|
-
};
|
|
1539
|
-
var claude_cli_error = class extends Error {
|
|
1540
|
-
kind = "claude_cli_error";
|
|
1541
|
-
reason;
|
|
1542
|
-
status;
|
|
1543
|
-
stderr_snippet;
|
|
1544
|
-
constructor(reason, message, metadata = {}) {
|
|
1545
|
-
super(message);
|
|
1546
|
-
this.name = "claude_cli_error";
|
|
1547
|
-
this.reason = reason;
|
|
1548
|
-
this.status = metadata.status;
|
|
1549
|
-
this.stderr_snippet = metadata.stderr_snippet;
|
|
1550
|
-
}
|
|
1551
|
-
};
|
|
1552
|
-
var provider_auth_error = class extends Error {
|
|
1553
|
-
kind = "provider_auth_error";
|
|
1554
|
-
provider;
|
|
1555
|
-
refresh_command;
|
|
1556
|
-
constructor(provider, message, metadata = {}) {
|
|
1557
|
-
super(message);
|
|
1558
|
-
this.name = "provider_auth_error";
|
|
1559
|
-
this.provider = provider;
|
|
1560
|
-
this.refresh_command = metadata.refresh_command;
|
|
1561
|
-
}
|
|
1562
|
-
};
|
|
1563
|
-
/**
|
|
1564
|
-
* A generate call that set a schema finished for a reason other than 'stop'
|
|
1565
|
-
* (content_filter, length, max_steps, tool_calls), so no schema-validated
|
|
1566
|
-
* value exists and validation was never attempted. Carries the raw model text
|
|
1567
|
-
* and the last provider-reported payload, so a guardrail trace or other
|
|
1568
|
-
* block detail stays reachable from the catch. Distinct from
|
|
1569
|
-
* schema_validation_error, which covers a response that completed normally
|
|
1570
|
-
* and then failed validation after its repair attempts ran out.
|
|
1571
|
-
*/
|
|
1572
|
-
var incomplete_generation_error = class extends Error {
|
|
1573
|
-
kind = "incomplete_generation_error";
|
|
1574
|
-
finish_reason;
|
|
1575
|
-
raw_text;
|
|
1576
|
-
provider_reported;
|
|
1577
|
-
constructor(finish_reason, raw_text, provider_reported) {
|
|
1578
|
-
super(`generation finished with '${finish_reason}' before a schema-validated response was produced`);
|
|
1579
|
-
this.name = "incomplete_generation_error";
|
|
1580
|
-
this.finish_reason = finish_reason;
|
|
1581
|
-
this.raw_text = raw_text;
|
|
1582
|
-
this.provider_reported = provider_reported;
|
|
1583
|
-
}
|
|
1584
|
-
};
|
|
1585
|
-
//#endregion
|
|
1586
1522
|
//#region src/engine/retry.ts
|
|
1587
1523
|
const DEFAULT_RETRY = {
|
|
1588
1524
|
max_attempts: 3,
|
|
@@ -1612,46 +1548,6 @@ function parse_retry_after(value) {
|
|
|
1612
1548
|
return Math.max(0, parsed - Date.now());
|
|
1613
1549
|
}
|
|
1614
1550
|
/**
|
|
1615
|
-
* Compute the delay before the next retry attempt.
|
|
1616
|
-
*
|
|
1617
|
-
* Exponential backoff (`initial_delay_ms * 2^attempt`) plus up to one
|
|
1618
|
-
* `initial_delay_ms` of random jitter, capped at `max_delay_ms`. The jitter
|
|
1619
|
-
* spreads retries from concurrent callers apart so they don't all retry in
|
|
1620
|
-
* lockstep.
|
|
1621
|
-
*/
|
|
1622
|
-
function compute_backoff(policy, attempt) {
|
|
1623
|
-
const base = policy.initial_delay_ms * 2 ** attempt;
|
|
1624
|
-
const jitter = Math.random() * policy.initial_delay_ms;
|
|
1625
|
-
return Math.min(base + jitter, policy.max_delay_ms);
|
|
1626
|
-
}
|
|
1627
|
-
/**
|
|
1628
|
-
* Wait `ms` milliseconds, or reject immediately with `aborted_error` if
|
|
1629
|
-
* `abort` fires first.
|
|
1630
|
-
*
|
|
1631
|
-
* A zero or negative `ms` resolves synchronously without arming a timer.
|
|
1632
|
-
*/
|
|
1633
|
-
function wait_ms(ms, abort) {
|
|
1634
|
-
return new Promise((resolve, reject) => {
|
|
1635
|
-
if (ms <= 0) {
|
|
1636
|
-
resolve();
|
|
1637
|
-
return;
|
|
1638
|
-
}
|
|
1639
|
-
if (abort?.aborted === true) {
|
|
1640
|
-
reject(new aborted_error("aborted", { reason: abort.reason }));
|
|
1641
|
-
return;
|
|
1642
|
-
}
|
|
1643
|
-
const timer = setTimeout(() => {
|
|
1644
|
-
if (abort !== void 0) abort.removeEventListener("abort", on_abort);
|
|
1645
|
-
resolve();
|
|
1646
|
-
}, ms);
|
|
1647
|
-
const on_abort = () => {
|
|
1648
|
-
clearTimeout(timer);
|
|
1649
|
-
reject(new aborted_error("aborted", { reason: abort?.reason }));
|
|
1650
|
-
};
|
|
1651
|
-
abort?.addEventListener("abort", on_abort, { once: true });
|
|
1652
|
-
});
|
|
1653
|
-
}
|
|
1654
|
-
/**
|
|
1655
1551
|
* Check whether `policy` allows retrying a failure of the given `kind`.
|
|
1656
1552
|
*/
|
|
1657
1553
|
function is_retryable(kind, policy) {
|
|
@@ -1667,6 +1563,12 @@ function is_retryable(kind, policy) {
|
|
|
1667
1563
|
* 5xx/network/timeout).
|
|
1668
1564
|
*/
|
|
1669
1565
|
async function retry_with_policy(fn, policy = DEFAULT_RETRY, abort) {
|
|
1566
|
+
const backoff_policy = {
|
|
1567
|
+
initial_delay_ms: policy.initial_delay_ms,
|
|
1568
|
+
max_delay_ms: policy.max_delay_ms,
|
|
1569
|
+
jitter: true
|
|
1570
|
+
};
|
|
1571
|
+
const signal = abort ?? new AbortController().signal;
|
|
1670
1572
|
let attempt = 0;
|
|
1671
1573
|
let last_rate_limit_after;
|
|
1672
1574
|
while (true) {
|
|
@@ -1693,12 +1595,12 @@ async function retry_with_policy(fn, policy = DEFAULT_RETRY, abort) {
|
|
|
1693
1595
|
}
|
|
1694
1596
|
throw new provider_error(retryable.message ?? `${retryable.kind} after ${attempt} attempts`, metadata);
|
|
1695
1597
|
}
|
|
1696
|
-
let delay = compute_backoff(
|
|
1598
|
+
let delay = compute_backoff(backoff_policy, attempt - 1);
|
|
1697
1599
|
if (retryable.kind === "rate_limit" && retryable.retry_after_ms !== void 0) {
|
|
1698
1600
|
delay = Math.max(delay, retryable.retry_after_ms);
|
|
1699
1601
|
last_rate_limit_after = retryable.retry_after_ms;
|
|
1700
1602
|
}
|
|
1701
|
-
await
|
|
1603
|
+
await wait_with_abort(delay, signal, (reason) => new aborted_error("aborted", { reason }));
|
|
1702
1604
|
}
|
|
1703
1605
|
}
|
|
1704
1606
|
}
|
|
@@ -1755,58 +1657,6 @@ function classify_retryable(err) {
|
|
|
1755
1657
|
}
|
|
1756
1658
|
}
|
|
1757
1659
|
//#endregion
|
|
1758
|
-
//#region src/engine/providers/types.ts
|
|
1759
|
-
/**
|
|
1760
|
-
* Read the `transport` selector off a provider init. Defaults to 'ai_sdk';
|
|
1761
|
-
* anything but the two known backends throws at construction so a typo
|
|
1762
|
-
* fails loud instead of silently running the default.
|
|
1763
|
-
*/
|
|
1764
|
-
function resolve_transport(init, provider) {
|
|
1765
|
-
const raw = init["transport"];
|
|
1766
|
-
if (raw === void 0 || raw === "ai_sdk") return "ai_sdk";
|
|
1767
|
-
if (raw === "native") return "native";
|
|
1768
|
-
throw new engine_config_error(`${provider} provider: transport must be 'ai_sdk' or 'native', got ${JSON.stringify(raw)}`, provider);
|
|
1769
|
-
}
|
|
1770
|
-
/**
|
|
1771
|
-
* Map raw provider usage to UsageTotals, the mapper most adapters share.
|
|
1772
|
-
*
|
|
1773
|
-
* Missing usage zeroes the totals. Optional fields (reasoning and cache
|
|
1774
|
-
* tokens) are set only when the raw payload carries them, reading the
|
|
1775
|
-
* flattened field first and the AI SDK's *_details container second.
|
|
1776
|
-
*/
|
|
1777
|
-
function default_normalize_usage(raw) {
|
|
1778
|
-
if (raw === void 0) return {
|
|
1779
|
-
input_tokens: 0,
|
|
1780
|
-
output_tokens: 0
|
|
1781
|
-
};
|
|
1782
|
-
const totals = {
|
|
1783
|
-
input_tokens: typeof raw.input_tokens === "number" ? raw.input_tokens : 0,
|
|
1784
|
-
output_tokens: typeof raw.output_tokens === "number" ? raw.output_tokens : 0
|
|
1785
|
-
};
|
|
1786
|
-
if (typeof raw.reasoning_tokens === "number") totals.reasoning_tokens = raw.reasoning_tokens;
|
|
1787
|
-
else if (typeof raw.output_token_details?.reasoning_tokens === "number") totals.reasoning_tokens = raw.output_token_details.reasoning_tokens;
|
|
1788
|
-
if (typeof raw.cached_input_tokens === "number") totals.cached_input_tokens = raw.cached_input_tokens;
|
|
1789
|
-
else if (typeof raw.input_token_details?.cached_tokens === "number") totals.cached_input_tokens = raw.input_token_details.cached_tokens;
|
|
1790
|
-
if (typeof raw.cache_write_tokens === "number") totals.cache_write_tokens = raw.cache_write_tokens;
|
|
1791
|
-
else if (typeof raw.input_token_details?.cache_creation_input_tokens === "number") totals.cache_write_tokens = raw.input_token_details.cache_creation_input_tokens;
|
|
1792
|
-
return totals;
|
|
1793
|
-
}
|
|
1794
|
-
/**
|
|
1795
|
-
* Dynamically import an optional peer dependency, rethrowing an import
|
|
1796
|
-
* failure as an error that names the package and the install command so a
|
|
1797
|
-
* missing peer is diagnosable from the message alone.
|
|
1798
|
-
*/
|
|
1799
|
-
async function load_optional_peer(specifier) {
|
|
1800
|
-
let mod;
|
|
1801
|
-
try {
|
|
1802
|
-
mod = await import(specifier);
|
|
1803
|
-
} catch (err) {
|
|
1804
|
-
const message = `missing peer dependency '${specifier}'. Install it with: pnpm add ${specifier}. Cause: ${err instanceof Error ? err.message : JSON.stringify(err)}`;
|
|
1805
|
-
throw new Error(message, { cause: err });
|
|
1806
|
-
}
|
|
1807
|
-
return mod;
|
|
1808
|
-
}
|
|
1809
|
-
//#endregion
|
|
1810
1660
|
//#region src/engine/providers/sse_native.ts
|
|
1811
1661
|
/**
|
|
1812
1662
|
* Incremental SSE decoder shared by the native (raw-HTTP) provider adapters.
|
|
@@ -2002,13 +1852,13 @@ function to_anthropic_messages(messages) {
|
|
|
2002
1852
|
}
|
|
2003
1853
|
/**
|
|
2004
1854
|
* Map fascicle tool definitions to the Messages-API tool shape, converting
|
|
2005
|
-
* each
|
|
1855
|
+
* each input schema to JSON Schema.
|
|
2006
1856
|
*/
|
|
2007
1857
|
function to_anthropic_tools(tools) {
|
|
2008
1858
|
return tools.map((tool) => ({
|
|
2009
1859
|
name: tool.name,
|
|
2010
1860
|
description: tool.description,
|
|
2011
|
-
input_schema:
|
|
1861
|
+
input_schema: to_json_schema(tool.input_schema)
|
|
2012
1862
|
}));
|
|
2013
1863
|
}
|
|
2014
1864
|
/**
|
|
@@ -2642,7 +2492,7 @@ function to_chat_messages(messages, provider) {
|
|
|
2642
2492
|
}
|
|
2643
2493
|
/**
|
|
2644
2494
|
* Map fascicle Tool[] to the Chat Completions function-tool shape,
|
|
2645
|
-
* converting each
|
|
2495
|
+
* converting each input schema to JSON Schema.
|
|
2646
2496
|
*/
|
|
2647
2497
|
function to_chat_tools(tools) {
|
|
2648
2498
|
return tools.map((tool) => ({
|
|
@@ -2650,7 +2500,7 @@ function to_chat_tools(tools) {
|
|
|
2650
2500
|
function: {
|
|
2651
2501
|
name: tool.name,
|
|
2652
2502
|
description: tool.description,
|
|
2653
|
-
parameters:
|
|
2503
|
+
parameters: to_json_schema(tool.input_schema)
|
|
2654
2504
|
}
|
|
2655
2505
|
}));
|
|
2656
2506
|
}
|
|
@@ -4583,114 +4433,172 @@ async function* build_stdout_lines(child, on_data) {
|
|
|
4583
4433
|
}
|
|
4584
4434
|
//#endregion
|
|
4585
4435
|
//#region src/engine/providers/claude_cli/stream_parse.ts
|
|
4436
|
+
/** A non-null, non-array object: the shape every CLI event and sub-object takes. */
|
|
4437
|
+
function is_record(value) {
|
|
4438
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4439
|
+
}
|
|
4440
|
+
/** `key` is absent (or `undefined`), or holds a string. */
|
|
4441
|
+
function opt_string(rec, key) {
|
|
4442
|
+
const value = rec[key];
|
|
4443
|
+
return value === void 0 || typeof value === "string";
|
|
4444
|
+
}
|
|
4445
|
+
/** `key` is absent (or `undefined`), or holds a number. */
|
|
4446
|
+
function opt_number(rec, key) {
|
|
4447
|
+
const value = rec[key];
|
|
4448
|
+
return value === void 0 || typeof value === "number";
|
|
4449
|
+
}
|
|
4450
|
+
/** `key` is absent (or `undefined`), or holds a boolean. */
|
|
4451
|
+
function opt_boolean(rec, key) {
|
|
4452
|
+
const value = rec[key];
|
|
4453
|
+
return value === void 0 || typeof value === "boolean";
|
|
4454
|
+
}
|
|
4586
4455
|
/**
|
|
4587
|
-
*
|
|
4588
|
-
*
|
|
4589
|
-
*
|
|
4590
|
-
|
|
4591
|
-
|
|
4592
|
-
|
|
4593
|
-
|
|
4594
|
-
|
|
4595
|
-
|
|
4596
|
-
|
|
4597
|
-
*
|
|
4598
|
-
*
|
|
4599
|
-
*
|
|
4600
|
-
|
|
4601
|
-
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
|
|
4606
|
-
|
|
4607
|
-
*
|
|
4608
|
-
*
|
|
4609
|
-
*
|
|
4610
|
-
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
|
|
4617
|
-
const
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
}
|
|
4634
|
-
const assistant_content_array_schema = z.array(z.unknown()).transform((arr) => {
|
|
4635
|
-
const out = [];
|
|
4636
|
-
for (const entry of arr) {
|
|
4637
|
-
const result = assistant_content_part_schema.safeParse(entry);
|
|
4638
|
-
if (result.success) out.push(result.data);
|
|
4456
|
+
* The optional `usage` sub-object of a `result` event. Absent is fine; a present
|
|
4457
|
+
* value must be an object whose known token counts are numbers when given. A
|
|
4458
|
+
* `null`, an array, or a mistyped count rejects the event.
|
|
4459
|
+
*/
|
|
4460
|
+
function is_valid_usage(value) {
|
|
4461
|
+
if (value === void 0) return true;
|
|
4462
|
+
if (!is_record(value)) return false;
|
|
4463
|
+
return opt_number(value, "input_tokens") && opt_number(value, "output_tokens") && opt_number(value, "cache_read_input_tokens") && opt_number(value, "cache_creation_input_tokens");
|
|
4464
|
+
}
|
|
4465
|
+
/**
|
|
4466
|
+
* The optional `rate_limit_info` sub-object of a `rate_limit_event`, under the
|
|
4467
|
+
* same rule as usage: absent is fine, a present value is validated field by
|
|
4468
|
+
* field or the event is rejected.
|
|
4469
|
+
*/
|
|
4470
|
+
function is_valid_rate_limit_info(value) {
|
|
4471
|
+
if (value === void 0) return true;
|
|
4472
|
+
if (!is_record(value)) return false;
|
|
4473
|
+
return opt_string(value, "status") && opt_number(value, "resetsAt") && opt_string(value, "rateLimitType") && opt_string(value, "overageStatus") && opt_number(value, "overageResetsAt") && opt_boolean(value, "isUsingOverage");
|
|
4474
|
+
}
|
|
4475
|
+
/**
|
|
4476
|
+
* Recognize one `assistant` content entry, or `undefined` for anything
|
|
4477
|
+
* unrecognized. `text` needs a string `text`; `tool_use` needs string `id` and
|
|
4478
|
+
* `name` and carries its opaque `input` through (absent `input` becomes
|
|
4479
|
+
* `undefined`, one deliberate tolerance the old `z.unknown()` did not grant).
|
|
4480
|
+
* Callers drop the `undefined` results, so an unknown entry type never rejects
|
|
4481
|
+
* the surrounding event.
|
|
4482
|
+
*/
|
|
4483
|
+
function as_assistant_part(value) {
|
|
4484
|
+
if (!is_record(value)) return void 0;
|
|
4485
|
+
if (value["type"] === "text") {
|
|
4486
|
+
const text = value["text"];
|
|
4487
|
+
return typeof text === "string" ? {
|
|
4488
|
+
type: "text",
|
|
4489
|
+
text
|
|
4490
|
+
} : void 0;
|
|
4491
|
+
}
|
|
4492
|
+
if (value["type"] === "tool_use") {
|
|
4493
|
+
const id = value["id"];
|
|
4494
|
+
const name = value["name"];
|
|
4495
|
+
if (typeof id !== "string") return void 0;
|
|
4496
|
+
if (typeof name !== "string") return void 0;
|
|
4497
|
+
return {
|
|
4498
|
+
type: "tool_use",
|
|
4499
|
+
id,
|
|
4500
|
+
name,
|
|
4501
|
+
input: value["input"]
|
|
4502
|
+
};
|
|
4639
4503
|
}
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
4644
|
-
|
|
4645
|
-
|
|
4646
|
-
|
|
4504
|
+
}
|
|
4505
|
+
/**
|
|
4506
|
+
* Recognize one `user` content entry as a tool result, or `undefined`. Requires
|
|
4507
|
+
* a string `tool_use_id`; `is_error` must be boolean when present, and a present
|
|
4508
|
+
* `content` of any shape is carried through. Callers drop the `undefined`
|
|
4509
|
+
* results.
|
|
4510
|
+
*/
|
|
4511
|
+
function as_user_part(value) {
|
|
4512
|
+
if (!is_record(value)) return void 0;
|
|
4513
|
+
if (value["type"] !== "tool_result") return void 0;
|
|
4514
|
+
const tool_use_id = value["tool_use_id"];
|
|
4515
|
+
if (typeof tool_use_id !== "string") return void 0;
|
|
4516
|
+
if (!opt_boolean(value, "is_error")) return void 0;
|
|
4517
|
+
const part = {
|
|
4518
|
+
type: "tool_result",
|
|
4519
|
+
tool_use_id
|
|
4520
|
+
};
|
|
4521
|
+
if ("content" in value) part.content = value["content"];
|
|
4522
|
+
const is_error = value["is_error"];
|
|
4523
|
+
if (typeof is_error === "boolean") part.is_error = is_error;
|
|
4524
|
+
return part;
|
|
4525
|
+
}
|
|
4526
|
+
/**
|
|
4527
|
+
* Collect the valid parts of an `assistant`/`user` content array. Returns
|
|
4528
|
+
* `undefined` (rejecting the event) when `value` is not an array; otherwise maps
|
|
4529
|
+
* each entry through `recognize` and keeps the ones it accepts.
|
|
4530
|
+
*/
|
|
4531
|
+
function collect_parts(value, recognize) {
|
|
4532
|
+
if (!Array.isArray(value)) return void 0;
|
|
4533
|
+
const parts = [];
|
|
4534
|
+
for (const entry of value) {
|
|
4535
|
+
const part = recognize(entry);
|
|
4536
|
+
if (part !== void 0) parts.push(part);
|
|
4647
4537
|
}
|
|
4648
|
-
return
|
|
4649
|
-
}
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
subtype
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
}
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
const
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4692
|
-
|
|
4693
|
-
|
|
4538
|
+
return parts;
|
|
4539
|
+
}
|
|
4540
|
+
/** A `system` event whose optional metadata fields type-check. */
|
|
4541
|
+
function is_system_event(raw) {
|
|
4542
|
+
return opt_string(raw, "subtype") && opt_string(raw, "session_id") && opt_string(raw, "model");
|
|
4543
|
+
}
|
|
4544
|
+
/** A `result` event whose optional fields and `usage` sub-object type-check. */
|
|
4545
|
+
function is_result_event(raw) {
|
|
4546
|
+
return opt_string(raw, "subtype") && opt_string(raw, "session_id") && opt_number(raw, "total_cost_usd") && opt_number(raw, "duration_ms") && opt_boolean(raw, "is_error") && is_valid_usage(raw["usage"]) && opt_string(raw, "result");
|
|
4547
|
+
}
|
|
4548
|
+
/** A `rate_limit_event` whose `rate_limit_info` sub-object and `session_id` type-check. */
|
|
4549
|
+
function is_rate_limit_event(raw) {
|
|
4550
|
+
return is_valid_rate_limit_info(raw["rate_limit_info"]) && opt_string(raw, "session_id");
|
|
4551
|
+
}
|
|
4552
|
+
/**
|
|
4553
|
+
* Recognize a pass-through event in place: hand the original object back (extra
|
|
4554
|
+
* keys and all, since nothing downstream reads them) when `recognize` accepts
|
|
4555
|
+
* it, or `undefined` to reject. Narrowing keeps this cast-free.
|
|
4556
|
+
*/
|
|
4557
|
+
function gate(raw, recognize) {
|
|
4558
|
+
return recognize(raw) ? raw : void 0;
|
|
4559
|
+
}
|
|
4560
|
+
/**
|
|
4561
|
+
* Normalize an `assistant` event: its `message` must be an object and its
|
|
4562
|
+
* `content` an array, whose recognized parts are kept and the rest dropped.
|
|
4563
|
+
*/
|
|
4564
|
+
function as_assistant_event(raw) {
|
|
4565
|
+
const message = raw["message"];
|
|
4566
|
+
if (!is_record(message)) return void 0;
|
|
4567
|
+
const content = collect_parts(message["content"], as_assistant_part);
|
|
4568
|
+
return content === void 0 ? void 0 : {
|
|
4569
|
+
type: "assistant",
|
|
4570
|
+
message: { content }
|
|
4571
|
+
};
|
|
4572
|
+
}
|
|
4573
|
+
/** Normalize a `user` event, under the same rule as `as_assistant_event`. */
|
|
4574
|
+
function as_user_event(raw) {
|
|
4575
|
+
const message = raw["message"];
|
|
4576
|
+
if (!is_record(message)) return void 0;
|
|
4577
|
+
const content = collect_parts(message["content"], as_user_part);
|
|
4578
|
+
return content === void 0 ? void 0 : {
|
|
4579
|
+
type: "user",
|
|
4580
|
+
message: { content }
|
|
4581
|
+
};
|
|
4582
|
+
}
|
|
4583
|
+
/**
|
|
4584
|
+
* The wire gate: validate a parsed JSON value against the recognized CLI event
|
|
4585
|
+
* shapes, returning the typed event or `undefined` on any mismatch.
|
|
4586
|
+
*
|
|
4587
|
+
* `assistant` and `user` are normalized (their content arrays are filtered down
|
|
4588
|
+
* to the recognized parts); the pass-through events are recognized in place, so
|
|
4589
|
+
* unknown keys survive but are never read.
|
|
4590
|
+
*/
|
|
4591
|
+
function as_event(raw) {
|
|
4592
|
+
if (!is_record(raw)) return void 0;
|
|
4593
|
+
switch (raw["type"]) {
|
|
4594
|
+
case "system": return gate(raw, is_system_event);
|
|
4595
|
+
case "assistant": return as_assistant_event(raw);
|
|
4596
|
+
case "user": return as_user_event(raw);
|
|
4597
|
+
case "result": return gate(raw, is_result_event);
|
|
4598
|
+
case "rate_limit_event": return gate(raw, is_rate_limit_event);
|
|
4599
|
+
default: return;
|
|
4600
|
+
}
|
|
4601
|
+
}
|
|
4694
4602
|
/**
|
|
4695
4603
|
* Build a fresh, empty `ParserState` for one CLI invocation.
|
|
4696
4604
|
*/
|
|
@@ -4801,14 +4709,6 @@ function flush_turn(state) {
|
|
|
4801
4709
|
};
|
|
4802
4710
|
}
|
|
4803
4711
|
/**
|
|
4804
|
-
* Validate a parsed JSON value against `cli_event_schema`, returning
|
|
4805
|
-
* `undefined` instead of throwing on a mismatch.
|
|
4806
|
-
*/
|
|
4807
|
-
function as_event(raw) {
|
|
4808
|
-
const result = cli_event_schema.safeParse(raw);
|
|
4809
|
-
return result.success ? result.data : void 0;
|
|
4810
|
-
}
|
|
4811
|
-
/**
|
|
4812
4712
|
* Append a `StreamChunk` to the output array and, if the caller passed an
|
|
4813
4713
|
* `on_chunk` dispatcher, await its delivery too.
|
|
4814
4714
|
*/
|
|
@@ -5278,6 +5178,14 @@ function build_generate_result(input) {
|
|
|
5278
5178
|
//#endregion
|
|
5279
5179
|
//#region src/engine/schema.ts
|
|
5280
5180
|
/**
|
|
5181
|
+
* Schema parse and repair helpers.
|
|
5182
|
+
*
|
|
5183
|
+
* The tool-loop / generate orchestrator owns the repair loop itself (counting
|
|
5184
|
+
* attempts toward `max_steps`, re-dispatching through the provider). This
|
|
5185
|
+
* module exposes only the parse primitive and the canonical repair-prompt
|
|
5186
|
+
* shape.
|
|
5187
|
+
*/
|
|
5188
|
+
/**
|
|
5281
5189
|
* Attempt to parse `text` as JSON and validate it with `schema`. Returns a
|
|
5282
5190
|
* tagged union; the caller decides whether to escalate to repair, throw, or
|
|
5283
5191
|
* surface the failure.
|
|
@@ -5288,35 +5196,39 @@ function build_generate_result(input) {
|
|
|
5288
5196
|
* block in the text, and the outermost {…} / […] slice. The first candidate
|
|
5289
5197
|
* that both parses as JSON and matches the schema wins.
|
|
5290
5198
|
*
|
|
5291
|
-
* When every candidate fails, we prefer the schema-validation
|
|
5292
|
-
* FIRST candidate that parsed as JSON:
|
|
5293
|
-
* primary output and
|
|
5294
|
-
* candidates (e.g. the bracket-slice fallback) often produce noisy
|
|
5199
|
+
* When every candidate fails, we prefer the schema-validation issues from the
|
|
5200
|
+
* FIRST candidate that parsed as JSON: those issues reflect the model's
|
|
5201
|
+
* primary output and are what a repair prompt should feed back. Later
|
|
5202
|
+
* candidates (e.g. the bracket-slice fallback) often produce noisy issues
|
|
5295
5203
|
* like "expected object, received array" that misdirect the model. Only when
|
|
5296
5204
|
* NO candidate parses as JSON do we surface the JSON parse error.
|
|
5205
|
+
*
|
|
5206
|
+
* Async because Standard Schema permits a vendor's `validate` to return a
|
|
5207
|
+
* promise; the ripple stops at generate.ts and the claude_cli adapter, both of
|
|
5208
|
+
* which already await their surrounding work.
|
|
5297
5209
|
*/
|
|
5298
|
-
function parse_with_schema(schema, text) {
|
|
5210
|
+
async function parse_with_schema(schema, text) {
|
|
5299
5211
|
const candidates = json_candidates(text);
|
|
5300
|
-
let
|
|
5301
|
-
let
|
|
5212
|
+
let json_parse_issues = [{ message: "No JSON-parseable content found in model output" }];
|
|
5213
|
+
let first_schema_issues;
|
|
5302
5214
|
for (const candidate of candidates) {
|
|
5303
5215
|
let parsed;
|
|
5304
5216
|
try {
|
|
5305
5217
|
parsed = JSON.parse(candidate);
|
|
5306
5218
|
} catch (err) {
|
|
5307
|
-
|
|
5219
|
+
json_parse_issues = [{ message: err instanceof Error ? err.message : String(err) }];
|
|
5308
5220
|
continue;
|
|
5309
5221
|
}
|
|
5310
|
-
const result = schema
|
|
5311
|
-
if (result.
|
|
5222
|
+
const result = await validate_schema(schema, parsed);
|
|
5223
|
+
if (result.ok) return {
|
|
5312
5224
|
ok: true,
|
|
5313
|
-
value: result.
|
|
5225
|
+
value: result.value
|
|
5314
5226
|
};
|
|
5315
|
-
|
|
5227
|
+
first_schema_issues ??= result.issues;
|
|
5316
5228
|
}
|
|
5317
5229
|
return {
|
|
5318
5230
|
ok: false,
|
|
5319
|
-
|
|
5231
|
+
issues: first_schema_issues ?? json_parse_issues
|
|
5320
5232
|
};
|
|
5321
5233
|
}
|
|
5322
5234
|
const FENCE_BLOCK = /```(?:[\w-]*)\s*\n?([\s\S]*?)\n?```/g;
|
|
@@ -5360,10 +5272,10 @@ function slice_outermost(text, open, close) {
|
|
|
5360
5272
|
* The wording is fixed rather than adapter-specific, so the repair prompt
|
|
5361
5273
|
* stays predictable and is easy to read back from trajectory output.
|
|
5362
5274
|
*/
|
|
5363
|
-
function build_repair_message(
|
|
5275
|
+
function build_repair_message(issues) {
|
|
5364
5276
|
return {
|
|
5365
5277
|
role: "user",
|
|
5366
|
-
content: build_repair_prompt_text(
|
|
5278
|
+
content: build_repair_prompt_text(issues)
|
|
5367
5279
|
};
|
|
5368
5280
|
}
|
|
5369
5281
|
/**
|
|
@@ -5371,36 +5283,15 @@ function build_repair_message(zod_error) {
|
|
|
5371
5283
|
* a single stdin string rather than a Message. Same wording as
|
|
5372
5284
|
* build_repair_message so the on-wire instruction is identical across providers.
|
|
5373
5285
|
*/
|
|
5374
|
-
function build_repair_prompt_text(
|
|
5375
|
-
return `Your previous response did not match the expected schema. Error: ${
|
|
5286
|
+
function build_repair_prompt_text(issues) {
|
|
5287
|
+
return `Your previous response did not match the expected schema. Error: ${format_schema_issues(issues)}. Please provide a corrected response that strictly conforms to the schema. Return ONLY the JSON value: no markdown code fences, no surrounding prose, no commentary.`;
|
|
5376
5288
|
}
|
|
5377
5289
|
/**
|
|
5378
|
-
* Throw schema_validation_error carrying the
|
|
5290
|
+
* Throw schema_validation_error carrying the schema issues and the raw model text.
|
|
5379
5291
|
* Called by the orchestrator when all repair attempts are exhausted.
|
|
5380
5292
|
*/
|
|
5381
|
-
function throw_schema_validation(
|
|
5382
|
-
throw new schema_validation_error(`schema validation failed: ${
|
|
5383
|
-
}
|
|
5384
|
-
/**
|
|
5385
|
-
* Render an unknown error value as a display string.
|
|
5386
|
-
*
|
|
5387
|
-
* Handles `Error` instances, plain strings, and objects with a string
|
|
5388
|
-
* `message` directly; falls back to `JSON.stringify`, and finally to a fixed
|
|
5389
|
-
* placeholder if even that throws.
|
|
5390
|
-
*/
|
|
5391
|
-
function format_zod_error(err) {
|
|
5392
|
-
if (err === null || err === void 0) return "unknown error";
|
|
5393
|
-
if (typeof err === "string") return err;
|
|
5394
|
-
if (err instanceof Error) return err.message;
|
|
5395
|
-
if (typeof err === "object" && "message" in err) {
|
|
5396
|
-
const msg = err.message;
|
|
5397
|
-
if (typeof msg === "string") return msg;
|
|
5398
|
-
}
|
|
5399
|
-
try {
|
|
5400
|
-
return JSON.stringify(err) ?? "unknown error";
|
|
5401
|
-
} catch {
|
|
5402
|
-
return "unknown error";
|
|
5403
|
-
}
|
|
5293
|
+
function throw_schema_validation(issues, raw_text) {
|
|
5294
|
+
throw new schema_validation_error(`schema validation failed: ${format_schema_issues(issues)}`, issues, raw_text);
|
|
5404
5295
|
}
|
|
5405
5296
|
//#endregion
|
|
5406
5297
|
//#region src/engine/trajectory.ts
|
|
@@ -5558,16 +5449,16 @@ function record_effort_ignored(trajectory, model_id) {
|
|
|
5558
5449
|
}
|
|
5559
5450
|
/**
|
|
5560
5451
|
* Emit a structured event when a schema-driven generate call returns text
|
|
5561
|
-
* that fails parse +
|
|
5562
|
-
* formatted
|
|
5563
|
-
* without needing stdout.
|
|
5452
|
+
* that fails parse + schema validation. Persists the raw model output and a
|
|
5453
|
+
* formatted schema issues summary to the trajectory so the failure is
|
|
5454
|
+
* debuggable without needing stdout.
|
|
5564
5455
|
*/
|
|
5565
5456
|
function record_schema_validation_failed(trajectory, meta) {
|
|
5566
5457
|
if (trajectory === void 0) return;
|
|
5567
5458
|
trajectory.record({
|
|
5568
5459
|
kind: "schema_validation_failed",
|
|
5569
5460
|
attempt: meta.attempt,
|
|
5570
|
-
|
|
5461
|
+
schema_issues: meta.schema_issues,
|
|
5571
5462
|
raw_text: meta.raw_text
|
|
5572
5463
|
});
|
|
5573
5464
|
}
|
|
@@ -5723,12 +5614,14 @@ function extract_system_text(prompt) {
|
|
|
5723
5614
|
for (const m of prompt) if (m.role === "system") return m.content;
|
|
5724
5615
|
}
|
|
5725
5616
|
/**
|
|
5726
|
-
* Serialize a
|
|
5727
|
-
*
|
|
5617
|
+
* Serialize a schema to the JSON Schema string the CLI's `--json-schema`
|
|
5618
|
+
* flag expects.
|
|
5619
|
+
*
|
|
5620
|
+
* `strip_meta` is what makes this CLI-specific: `claude --json-schema`
|
|
5621
|
+
* rejects a top-level `$schema`/`$id`, which every other provider tolerates.
|
|
5728
5622
|
*/
|
|
5729
5623
|
function compile_schema(schema) {
|
|
5730
|
-
|
|
5731
|
-
return JSON.stringify(json);
|
|
5624
|
+
return JSON.stringify(to_json_schema(schema, { strip_meta: true }));
|
|
5732
5625
|
}
|
|
5733
5626
|
/**
|
|
5734
5627
|
* Turn a closed CLI subprocess's exit code, signal, and stderr into an
|
|
@@ -5905,26 +5798,26 @@ function create_claude_cli_adapter(init) {
|
|
|
5905
5798
|
const max_repairs = opts.schema_repair_attempts ?? 1;
|
|
5906
5799
|
let repairs_done = 0;
|
|
5907
5800
|
for (;;) {
|
|
5908
|
-
const attempt = parse_with_schema(opts.schema, parsed.final_text);
|
|
5801
|
+
const attempt = await parse_with_schema(opts.schema, parsed.final_text);
|
|
5909
5802
|
if (attempt.ok) {
|
|
5910
5803
|
parsed_content = attempt.value;
|
|
5911
5804
|
break;
|
|
5912
5805
|
}
|
|
5913
5806
|
record_schema_validation_failed(trajectory, {
|
|
5914
5807
|
attempt: repairs_done === 0 ? "initial" : "repair",
|
|
5915
|
-
|
|
5808
|
+
schema_issues: format_schema_issues(attempt.issues),
|
|
5916
5809
|
raw_text: parsed.final_text
|
|
5917
5810
|
});
|
|
5918
|
-
if (repairs_done >= max_repairs) throw new schema_validation_error(max_repairs === 0 ? "schema validation failed and repair is disabled (schema_repair_attempts: 0)" : `schema validation failed after ${String(max_repairs)} repair attempt${max_repairs === 1 ? "" : "s"}`, attempt.
|
|
5811
|
+
if (repairs_done >= max_repairs) throw new schema_validation_error(max_repairs === 0 ? "schema validation failed and repair is disabled (schema_repair_attempts: 0)" : `schema validation failed after ${String(max_repairs)} repair attempt${max_repairs === 1 ? "" : "s"}`, attempt.issues, parsed.final_text);
|
|
5919
5812
|
const repair_session_id = parsed.session_id;
|
|
5920
|
-
if (repair_session_id === void 0) throw new schema_validation_error("schema validation failed and no session_id available for repair", attempt.
|
|
5813
|
+
if (repair_session_id === void 0) throw new schema_validation_error("schema validation failed and no session_id available for repair", attempt.issues, parsed.final_text);
|
|
5921
5814
|
const repair_call_opts = {
|
|
5922
5815
|
...call_opts,
|
|
5923
5816
|
session_id: repair_session_id
|
|
5924
5817
|
};
|
|
5925
5818
|
parsed = (await run_cli(spawn_runtime, {
|
|
5926
5819
|
...base_args,
|
|
5927
|
-
stdin_text: build_repair_prompt_text(attempt.
|
|
5820
|
+
stdin_text: build_repair_prompt_text(attempt.issues),
|
|
5928
5821
|
call_opts: repair_call_opts
|
|
5929
5822
|
})).parsed;
|
|
5930
5823
|
repairs_done += 1;
|
|
@@ -6140,6 +6033,36 @@ function sum_usage(steps) {
|
|
|
6140
6033
|
}
|
|
6141
6034
|
//#endregion
|
|
6142
6035
|
//#region src/engine/tool_call_salvage.ts
|
|
6036
|
+
/**
|
|
6037
|
+
* Salvage tool calls that a model emitted as assistant TEXT instead of a
|
|
6038
|
+
* structured tool_calls array. Local runtimes (Ollama native API, LM Studio
|
|
6039
|
+
* /v1) frequently mis-serialize tool definitions in the chat template, so the
|
|
6040
|
+
* model writes its call into the content in one of three well-known formats:
|
|
6041
|
+
*
|
|
6042
|
+
* hermes <tool_call>{"name":"x","arguments":{...}}</tool_call>
|
|
6043
|
+
* json {"name":"x","arguments":{...}} bare or ```json-fenced
|
|
6044
|
+
* qwen_xml <tool_call><function=x><parameter=k>v</parameter></function></tool_call>
|
|
6045
|
+
*
|
|
6046
|
+
* A candidate is accepted ONLY when its name resolves in the call's tool
|
|
6047
|
+
* registry AND its arguments validate against that tool's input_schema.
|
|
6048
|
+
* That double gate is the guard against a false positive on an ordinary
|
|
6049
|
+
* answer that merely contains JSON.
|
|
6050
|
+
*
|
|
6051
|
+
* Parsing rules that matter for correctness:
|
|
6052
|
+
* - Every <tool_call> block extent, accepted or rejected, is masked so the
|
|
6053
|
+
* bare-JSON pass never re-matches a payload inside it (a hermes block
|
|
6054
|
+
* contains a shape-valid bare object; double-matching would double-strip).
|
|
6055
|
+
* - All code fences are masked from the bare pass for the same reason;
|
|
6056
|
+
* only fences with no info string or `json` are parsed as candidates.
|
|
6057
|
+
* - A complete bare object that is not a call is skipped whole: descending
|
|
6058
|
+
* into it could false-positive on substructures of ordinary JSON output.
|
|
6059
|
+
* - An unterminated <tool_call> is ignored (finish_reason 'length'
|
|
6060
|
+
* truncation); its text is left intact.
|
|
6061
|
+
* - Qwen XML parameter values that contain a literal </parameter> mis-parse
|
|
6062
|
+
* under the non-greedy matcher; accepted limitation.
|
|
6063
|
+
*
|
|
6064
|
+
* Never throws; returns undefined when zero candidates survive validation.
|
|
6065
|
+
*/
|
|
6143
6066
|
const TOOL_CALL_OPEN = "<tool_call>";
|
|
6144
6067
|
const TOOL_CALL_CLOSE = "</tool_call>";
|
|
6145
6068
|
const FUNCTION_RE = /<function=([^>\s]+)>([\s\S]*?)<\/function>/g;
|
|
@@ -6394,14 +6317,14 @@ function scan_bare_json(text, masks) {
|
|
|
6394
6317
|
* qwen_xml candidates get one retry with per-parameter JSON coercion, since
|
|
6395
6318
|
* XML parameter values always arrive as strings.
|
|
6396
6319
|
*/
|
|
6397
|
-
function validate_candidate(candidate, tool_map) {
|
|
6320
|
+
async function validate_candidate(candidate, tool_map) {
|
|
6398
6321
|
const tool = tool_map.get(candidate.name);
|
|
6399
6322
|
if (tool === void 0) return void 0;
|
|
6400
6323
|
const schema = tool.input_schema;
|
|
6401
|
-
const raw = schema
|
|
6402
|
-
if (raw.
|
|
6324
|
+
const raw = await validate_schema(schema, candidate.args);
|
|
6325
|
+
if (raw.ok) return {
|
|
6403
6326
|
name: candidate.name,
|
|
6404
|
-
input: raw.
|
|
6327
|
+
input: raw.value,
|
|
6405
6328
|
format: candidate.format,
|
|
6406
6329
|
span: candidate.span
|
|
6407
6330
|
};
|
|
@@ -6418,11 +6341,11 @@ function validate_candidate(candidate, tool_map) {
|
|
|
6418
6341
|
coerced[k] = v;
|
|
6419
6342
|
}
|
|
6420
6343
|
}
|
|
6421
|
-
const retried = schema
|
|
6422
|
-
if (!retried.
|
|
6344
|
+
const retried = await validate_schema(schema, coerced);
|
|
6345
|
+
if (!retried.ok) return void 0;
|
|
6423
6346
|
return {
|
|
6424
6347
|
name: candidate.name,
|
|
6425
|
-
input: retried.
|
|
6348
|
+
input: retried.value,
|
|
6426
6349
|
format: candidate.format,
|
|
6427
6350
|
span: candidate.span
|
|
6428
6351
|
};
|
|
@@ -6445,7 +6368,7 @@ function strip_spans(text, spans) {
|
|
|
6445
6368
|
* surviving calls plus the text with their spans stripped. Returns undefined
|
|
6446
6369
|
* when nothing survives.
|
|
6447
6370
|
*/
|
|
6448
|
-
function salvage_tool_calls(text, tool_map) {
|
|
6371
|
+
async function salvage_tool_calls(text, tool_map) {
|
|
6449
6372
|
if (text.length === 0) return void 0;
|
|
6450
6373
|
const blocks = scan_tool_call_blocks(text);
|
|
6451
6374
|
const fences = scan_fences(text, blocks.masks);
|
|
@@ -6455,11 +6378,7 @@ function salvage_tool_calls(text, tool_map) {
|
|
|
6455
6378
|
...fences.candidates,
|
|
6456
6379
|
...scan_bare_json(text, all_masks)
|
|
6457
6380
|
].toSorted((a, b) => a.span.start - b.span.start);
|
|
6458
|
-
const calls =
|
|
6459
|
-
for (const c of candidates) {
|
|
6460
|
-
const validated = validate_candidate(c, tool_map);
|
|
6461
|
-
if (validated !== void 0) calls.push(validated);
|
|
6462
|
-
}
|
|
6381
|
+
const calls = (await Promise.all(candidates.map((c) => validate_candidate(c, tool_map)))).filter((c) => c !== void 0);
|
|
6463
6382
|
if (calls.length === 0) return void 0;
|
|
6464
6383
|
return {
|
|
6465
6384
|
calls,
|
|
@@ -6469,6 +6388,53 @@ function salvage_tool_calls(text, tool_map) {
|
|
|
6469
6388
|
//#endregion
|
|
6470
6389
|
//#region src/engine/tool_loop.ts
|
|
6471
6390
|
/**
|
|
6391
|
+
* Tool-call loop orchestration.
|
|
6392
|
+
*
|
|
6393
|
+
* Invariants:
|
|
6394
|
+
* - Tools execute SEQUENTIALLY within a turn (no parallel dispatch).
|
|
6395
|
+
* - Abort is checked at the top of each loop iteration AND before each tool
|
|
6396
|
+
* call within a turn.
|
|
6397
|
+
* - Tool input is validated against tool.input_schema BEFORE execute is
|
|
6398
|
+
* invoked. Invalid input is fed back as a tool result with error: true and
|
|
6399
|
+
* consumes a step; execute is not called.
|
|
6400
|
+
* - tool_error_policy:
|
|
6401
|
+
* 'feed_back' (default) serializes the thrown error into a tool result
|
|
6402
|
+
* with { error: <message> }. Loop continues.
|
|
6403
|
+
* 'throw' wraps the error in tool_error and ends the call.
|
|
6404
|
+
* - needs_approval (boolean or predicate) gates execute. Abort fired during
|
|
6405
|
+
* the await rejects with aborted_error.
|
|
6406
|
+
* - Absent on_tool_approval with needs_approval truthy FAILS CLOSED
|
|
6407
|
+
* (tool_approval_denied_error thrown before execute).
|
|
6408
|
+
* - max_steps cap RESOLVES with finish_reason: 'max_steps' (does not throw).
|
|
6409
|
+
* Attempted-but-unexecuted tool calls from the final turn land in
|
|
6410
|
+
* tool_calls with error: { message: 'max_steps_exceeded_before_execution' }.
|
|
6411
|
+
* - salvage_budget (from tool_call_repair_attempts): a turn with NO
|
|
6412
|
+
* structured calls, finish_reason 'stop'|'length', and tools present is
|
|
6413
|
+
* scanned for calls the model emitted as text (a local-runtime failure).
|
|
6414
|
+
* Validated matches run the normal execute path and produce the same
|
|
6415
|
+
* records/events/chunks as native calls, marked salvaged. The budget is
|
|
6416
|
+
* a shared mutable holder so it spans schema-repair re-invocations.
|
|
6417
|
+
* - max_tool_calls_per_step: calls beyond the cap are dropped for the step
|
|
6418
|
+
* (the model can re-issue next turn), recorded with
|
|
6419
|
+
* error: { message: 'dropped_max_tool_calls_per_step' }, and excluded
|
|
6420
|
+
* from the assistant history message so providers that require a result
|
|
6421
|
+
* per emitted call do not reject the next request.
|
|
6422
|
+
* - ends_turn (Tool.ends_turn): a tool flagged terminal ends the loop when a
|
|
6423
|
+
* call to it executes SUCCESSFULLY. The call runs the normal execute path
|
|
6424
|
+
* (record, fed tool_result message, trajectory events + chunk), then the
|
|
6425
|
+
* loop breaks with finish_reason 'stop' instead of running another model
|
|
6426
|
+
* turn. Salvaged terminal calls behave identically. A denied, invalid,
|
|
6427
|
+
* dropped, or throwing terminal call does NOT end the loop. A successful
|
|
6428
|
+
* terminal call is exempt from the max_steps would_exceed_after skip (it
|
|
6429
|
+
* needs no follow-up turn), so a terminal finish wins over a coincident
|
|
6430
|
+
* max_steps cap (finish_reason 'stop', max_steps_reached false).
|
|
6431
|
+
*
|
|
6432
|
+
* The loop does not itself call the AI SDK. It invokes a supplied `invoke_once`
|
|
6433
|
+
* seam that returns a neutral TurnResult. generate.ts builds the real seam
|
|
6434
|
+
* (the ai_sdk transport in providers/ai_sdk/, or a native adapter's
|
|
6435
|
+
* invoke_turn); tests inject a mock seam directly.
|
|
6436
|
+
*/
|
|
6437
|
+
/**
|
|
6472
6438
|
* Throw `aborted_error` (tagged with the step index) if the signal has fired.
|
|
6473
6439
|
*/
|
|
6474
6440
|
function throw_if_aborted(abort, step_index) {
|
|
@@ -6648,18 +6614,18 @@ function compute_and_record_cost(config, step_index, usage) {
|
|
|
6648
6614
|
return breakdown;
|
|
6649
6615
|
}
|
|
6650
6616
|
/**
|
|
6651
|
-
* Validate a raw tool-call input against the tool's
|
|
6652
|
-
*
|
|
6617
|
+
* Validate a raw tool-call input against the tool's schema before execution,
|
|
6618
|
+
* returning the parsed value or a feedback-ready error message.
|
|
6653
6619
|
*/
|
|
6654
|
-
function validate_tool_input(tool, input) {
|
|
6655
|
-
const parsed = tool.input_schema
|
|
6656
|
-
if (parsed.
|
|
6620
|
+
async function validate_tool_input(tool, input) {
|
|
6621
|
+
const parsed = await validate_schema(tool.input_schema, input);
|
|
6622
|
+
if (parsed.ok) return {
|
|
6657
6623
|
ok: true,
|
|
6658
|
-
value: parsed.
|
|
6624
|
+
value: parsed.value
|
|
6659
6625
|
};
|
|
6660
6626
|
return {
|
|
6661
6627
|
ok: false,
|
|
6662
|
-
message: `invalid tool input: ${
|
|
6628
|
+
message: `invalid tool input: ${format_schema_issues(parsed.issues)}`
|
|
6663
6629
|
};
|
|
6664
6630
|
}
|
|
6665
6631
|
/**
|
|
@@ -6741,7 +6707,7 @@ async function run_tool_loop(config) {
|
|
|
6741
6707
|
let salvage;
|
|
6742
6708
|
const salvaged_formats = /* @__PURE__ */ new Map();
|
|
6743
6709
|
if (turn.tool_calls.length === 0 && (turn.finish_reason === "stop" || turn.finish_reason === "length") && config.tools.length > 0 && config.salvage_budget !== void 0 && config.salvage_budget.remaining > 0) {
|
|
6744
|
-
salvage = salvage_tool_calls(turn.text, tool_map);
|
|
6710
|
+
salvage = await salvage_tool_calls(turn.text, tool_map);
|
|
6745
6711
|
if (salvage !== void 0) {
|
|
6746
6712
|
config.salvage_budget.remaining -= 1;
|
|
6747
6713
|
history_text = salvage.stripped_text;
|
|
@@ -6874,7 +6840,7 @@ async function run_tool_loop(config) {
|
|
|
6874
6840
|
await dispatch_tool_result_chunk(config.dispatch_chunk, step_index, raw_call.id, void 0, { message: err_message });
|
|
6875
6841
|
continue;
|
|
6876
6842
|
}
|
|
6877
|
-
const validation = validate_tool_input(tool, raw_call.input);
|
|
6843
|
+
const validation = await validate_tool_input(tool, raw_call.input);
|
|
6878
6844
|
if (!validation.ok) {
|
|
6879
6845
|
const record = {
|
|
6880
6846
|
id: raw_call.id,
|
|
@@ -7094,451 +7060,6 @@ async function run_tool_loop(config) {
|
|
|
7094
7060
|
};
|
|
7095
7061
|
}
|
|
7096
7062
|
//#endregion
|
|
7097
|
-
//#region src/engine/providers/ai_sdk/telemetry.ts
|
|
7098
|
-
/**
|
|
7099
|
-
* Build the AI SDK's `experimental_telemetry` option from engine settings,
|
|
7100
|
-
* loading the `@ai-sdk/otel` peer only when telemetry is enabled.
|
|
7101
|
-
*/
|
|
7102
|
-
async function build_ai_sdk_telemetry(settings) {
|
|
7103
|
-
if (!settings?.enabled) return void 0;
|
|
7104
|
-
const out = {
|
|
7105
|
-
isEnabled: true,
|
|
7106
|
-
integrations: [new (await (load_optional_peer("@ai-sdk/otel"))).OpenTelemetry(settings.tracer !== void 0 ? { tracer: settings.tracer } : {})]
|
|
7107
|
-
};
|
|
7108
|
-
if (settings.function_id !== void 0) out.functionId = settings.function_id;
|
|
7109
|
-
if (settings.record_inputs !== void 0) out.recordInputs = settings.record_inputs;
|
|
7110
|
-
if (settings.record_outputs !== void 0) out.recordOutputs = settings.record_outputs;
|
|
7111
|
-
if (settings.metadata !== void 0) out.metadata = settings.metadata;
|
|
7112
|
-
return out;
|
|
7113
|
-
}
|
|
7114
|
-
//#endregion
|
|
7115
|
-
//#region src/engine/providers/ai_sdk/invoke.ts
|
|
7116
|
-
/**
|
|
7117
|
-
* The ai_sdk transport: the engine's only Vercel AI SDK call site.
|
|
7118
|
-
*
|
|
7119
|
-
* Only this module imports from `ai` or invokes generateText / streamText.
|
|
7120
|
-
* generate.ts drives this transport through create_ai_sdk_turn and stays
|
|
7121
|
-
* SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native
|
|
7122
|
-
* adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.
|
|
7123
|
-
*
|
|
7124
|
-
* Retry stays out of this module on purpose: generate.ts wraps the turn
|
|
7125
|
-
* returned here in the engine-owned retry_turn, exactly as it wraps a native
|
|
7126
|
-
* adapter's invoke_turn. This module owns request/response mapping only.
|
|
7127
|
-
*/
|
|
7128
|
-
/**
|
|
7129
|
-
* Map the AI SDK's finish reason string to the engine's FinishReason.
|
|
7130
|
-
*/
|
|
7131
|
-
function map_finish_reason(raw) {
|
|
7132
|
-
switch (raw) {
|
|
7133
|
-
case "stop": return "stop";
|
|
7134
|
-
case "length": return "length";
|
|
7135
|
-
case "content-filter":
|
|
7136
|
-
case "content_filter": return "content_filter";
|
|
7137
|
-
case "tool-calls":
|
|
7138
|
-
case "tool_calls": return "tool_calls";
|
|
7139
|
-
default: return "stop";
|
|
7140
|
-
}
|
|
7141
|
-
}
|
|
7142
|
-
/**
|
|
7143
|
-
* Extract the usage fields `default_normalize_usage` understands from an AI
|
|
7144
|
-
* SDK usage object, tolerating both the SDK's camelCase shape and the
|
|
7145
|
-
* flattened snake_case fields some provider mocks return directly.
|
|
7146
|
-
*/
|
|
7147
|
-
function to_raw_provider_usage(usage) {
|
|
7148
|
-
if (usage === null || typeof usage !== "object") return {};
|
|
7149
|
-
const raw = {};
|
|
7150
|
-
const input_tokens = Reflect.get(usage, "inputTokens");
|
|
7151
|
-
if (typeof input_tokens === "number") raw.input_tokens = input_tokens;
|
|
7152
|
-
const output_tokens = Reflect.get(usage, "outputTokens");
|
|
7153
|
-
if (typeof output_tokens === "number") raw.output_tokens = output_tokens;
|
|
7154
|
-
const input_details = Reflect.get(usage, "inputTokenDetails");
|
|
7155
|
-
if (input_details !== null && typeof input_details === "object") {
|
|
7156
|
-
const cache_read = Reflect.get(input_details, "cacheReadTokens");
|
|
7157
|
-
const cache_write = Reflect.get(input_details, "cacheWriteTokens");
|
|
7158
|
-
raw.input_token_details = {};
|
|
7159
|
-
if (typeof cache_read === "number") raw.input_token_details.cached_tokens = cache_read;
|
|
7160
|
-
if (typeof cache_write === "number") raw.input_token_details.cache_creation_input_tokens = cache_write;
|
|
7161
|
-
}
|
|
7162
|
-
const output_details = Reflect.get(usage, "outputTokenDetails");
|
|
7163
|
-
if (output_details !== null && typeof output_details === "object") {
|
|
7164
|
-
const reasoning = Reflect.get(output_details, "reasoningTokens");
|
|
7165
|
-
raw.output_token_details = {};
|
|
7166
|
-
if (typeof reasoning === "number") raw.output_token_details.reasoning_tokens = reasoning;
|
|
7167
|
-
}
|
|
7168
|
-
const cached_flat = Reflect.get(usage, "cached_input_tokens");
|
|
7169
|
-
if (typeof cached_flat === "number") raw.cached_input_tokens = cached_flat;
|
|
7170
|
-
const cache_write_flat = Reflect.get(usage, "cache_write_tokens");
|
|
7171
|
-
if (typeof cache_write_flat === "number") raw.cache_write_tokens = cache_write_flat;
|
|
7172
|
-
const reasoning_flat = Reflect.get(usage, "reasoning_tokens");
|
|
7173
|
-
if (typeof reasoning_flat === "number") raw.reasoning_tokens = reasoning_flat;
|
|
7174
|
-
const input_flat = Reflect.get(usage, "input_tokens");
|
|
7175
|
-
if (raw.input_tokens === void 0 && typeof input_flat === "number") raw.input_tokens = input_flat;
|
|
7176
|
-
const output_flat = Reflect.get(usage, "output_tokens");
|
|
7177
|
-
if (raw.output_tokens === void 0 && typeof output_flat === "number") raw.output_tokens = output_flat;
|
|
7178
|
-
return raw;
|
|
7179
|
-
}
|
|
7180
|
-
/**
|
|
7181
|
-
* Normalize an AI SDK `providerMetadata` value into the neutral
|
|
7182
|
-
* TurnResult.provider_reported shape.
|
|
7183
|
-
*
|
|
7184
|
-
* The SDK's metadata is already keyed by provider name, which is the shape
|
|
7185
|
-
* provider_reported documents, so the keys ride through untranslated and every
|
|
7186
|
-
* ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,
|
|
7187
|
-
* anthropic's cache detail, openai's own fields. The payloads stay opaque
|
|
7188
|
-
* (callers narrow them at the use site), so this copies the top level and
|
|
7189
|
-
* inspects nothing below it. An absent or empty map returns undefined, keeping
|
|
7190
|
-
* "the provider reported nothing" spelled one way.
|
|
7191
|
-
*/
|
|
7192
|
-
function to_provider_reported(metadata) {
|
|
7193
|
-
if (metadata === null || typeof metadata !== "object") return void 0;
|
|
7194
|
-
const keys = Object.keys(metadata);
|
|
7195
|
-
if (keys.length === 0) return void 0;
|
|
7196
|
-
const reported = {};
|
|
7197
|
-
for (const key of keys) reported[key] = Reflect.get(metadata, key);
|
|
7198
|
-
return reported;
|
|
7199
|
-
}
|
|
7200
|
-
/**
|
|
7201
|
-
* Map fascicle's Message[] to the AI SDK's ModelMessage[] shape.
|
|
7202
|
-
*/
|
|
7203
|
-
function to_sdk_messages(messages) {
|
|
7204
|
-
const out = [];
|
|
7205
|
-
for (const m of messages) {
|
|
7206
|
-
if (m.role === "system") {
|
|
7207
|
-
out.push({
|
|
7208
|
-
role: "system",
|
|
7209
|
-
content: m.content
|
|
7210
|
-
});
|
|
7211
|
-
continue;
|
|
7212
|
-
}
|
|
7213
|
-
if (m.role === "user") {
|
|
7214
|
-
if (typeof m.content === "string") out.push({
|
|
7215
|
-
role: "user",
|
|
7216
|
-
content: m.content
|
|
7217
|
-
});
|
|
7218
|
-
else {
|
|
7219
|
-
const parts = m.content.map((p) => {
|
|
7220
|
-
if (p.type === "text") return {
|
|
7221
|
-
type: "text",
|
|
7222
|
-
text: p.text
|
|
7223
|
-
};
|
|
7224
|
-
const image_part = {
|
|
7225
|
-
type: "image",
|
|
7226
|
-
image: p.image
|
|
7227
|
-
};
|
|
7228
|
-
if (p.media_type !== void 0) image_part.mediaType = p.media_type;
|
|
7229
|
-
return image_part;
|
|
7230
|
-
});
|
|
7231
|
-
out.push({
|
|
7232
|
-
role: "user",
|
|
7233
|
-
content: parts
|
|
7234
|
-
});
|
|
7235
|
-
}
|
|
7236
|
-
continue;
|
|
7237
|
-
}
|
|
7238
|
-
if (m.role === "tool") {
|
|
7239
|
-
out.push({
|
|
7240
|
-
role: "tool",
|
|
7241
|
-
content: [{
|
|
7242
|
-
type: "tool-result",
|
|
7243
|
-
toolCallId: m.tool_call_id,
|
|
7244
|
-
toolName: m.name,
|
|
7245
|
-
output: {
|
|
7246
|
-
type: "text",
|
|
7247
|
-
value: m.content
|
|
7248
|
-
}
|
|
7249
|
-
}]
|
|
7250
|
-
});
|
|
7251
|
-
continue;
|
|
7252
|
-
}
|
|
7253
|
-
if (typeof m.content === "string") {
|
|
7254
|
-
out.push({
|
|
7255
|
-
role: "assistant",
|
|
7256
|
-
content: m.content
|
|
7257
|
-
});
|
|
7258
|
-
continue;
|
|
7259
|
-
}
|
|
7260
|
-
const parts = m.content.map((p) => {
|
|
7261
|
-
if (p.type === "text") return {
|
|
7262
|
-
type: "text",
|
|
7263
|
-
text: p.text
|
|
7264
|
-
};
|
|
7265
|
-
return {
|
|
7266
|
-
type: "tool-call",
|
|
7267
|
-
toolCallId: p.id,
|
|
7268
|
-
toolName: p.name,
|
|
7269
|
-
input: p.input
|
|
7270
|
-
};
|
|
7271
|
-
});
|
|
7272
|
-
out.push({
|
|
7273
|
-
role: "assistant",
|
|
7274
|
-
content: parts
|
|
7275
|
-
});
|
|
7276
|
-
}
|
|
7277
|
-
return out;
|
|
7278
|
-
}
|
|
7279
|
-
/**
|
|
7280
|
-
* Hoist a leading run of system messages out of the SDK message list into the
|
|
7281
|
-
* AI SDK's top-level `system` option.
|
|
7282
|
-
*
|
|
7283
|
-
* Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it
|
|
7284
|
-
* as potentially attacker-controlled: it warns on every call (and newer `ai`
|
|
7285
|
-
* versions throw unless `allowSystemInMessages` is set). fascicle's system
|
|
7286
|
-
* content is the developer's own prompt, and the SDK's own recommendation is to
|
|
7287
|
-
* deliver it through the top-level `instructions` option (v7's rename of the
|
|
7288
|
-
* former `system` option), which removes the warning at its source rather than
|
|
7289
|
-
* suppressing it.
|
|
7290
|
-
*
|
|
7291
|
-
* Only the *leading* run is hoisted (fascicle's only shape: one or more system
|
|
7292
|
-
* messages, then the conversation). A system message that appears after a
|
|
7293
|
-
* non-system message keeps its position rather than being silently reordered to
|
|
7294
|
-
* the top, and the original list is returned untouched when hoisting would leave
|
|
7295
|
-
* `messages` empty, since the SDK rejects an empty messages array.
|
|
7296
|
-
*/
|
|
7297
|
-
function split_leading_system(messages) {
|
|
7298
|
-
let run_end = 0;
|
|
7299
|
-
const system_parts = [];
|
|
7300
|
-
while (run_end < messages.length) {
|
|
7301
|
-
const m = messages[run_end];
|
|
7302
|
-
if (m?.role !== "system") break;
|
|
7303
|
-
system_parts.push(m.content);
|
|
7304
|
-
run_end += 1;
|
|
7305
|
-
}
|
|
7306
|
-
const rest = messages.slice(run_end);
|
|
7307
|
-
if (system_parts.length === 0 || rest.length === 0) return { messages: [...messages] };
|
|
7308
|
-
return {
|
|
7309
|
-
system: system_parts.join("\n\n"),
|
|
7310
|
-
messages: rest
|
|
7311
|
-
};
|
|
7312
|
-
}
|
|
7313
|
-
/**
|
|
7314
|
-
* Map fascicle's Tool[] to the AI SDK's ToolSet.
|
|
7315
|
-
*
|
|
7316
|
-
* Returns undefined for an empty tool list so the caller can omit `tools`
|
|
7317
|
-
* from the call params entirely instead of passing an empty object.
|
|
7318
|
-
*/
|
|
7319
|
-
function to_sdk_tools(tools) {
|
|
7320
|
-
if (tools.length === 0) return void 0;
|
|
7321
|
-
const entries = {};
|
|
7322
|
-
for (const t of tools) entries[t.name] = tool({
|
|
7323
|
-
description: t.description,
|
|
7324
|
-
inputSchema: t.input_schema
|
|
7325
|
-
});
|
|
7326
|
-
return entries;
|
|
7327
|
-
}
|
|
7328
|
-
/**
|
|
7329
|
-
* Map one AI SDK stream part to the engine's StreamChunk shape, or undefined
|
|
7330
|
-
* for a part kind the engine does not model.
|
|
7331
|
-
*/
|
|
7332
|
-
function map_stream_part_to_chunk(part, step_index) {
|
|
7333
|
-
switch (part.type) {
|
|
7334
|
-
case "text-delta": return {
|
|
7335
|
-
kind: "text",
|
|
7336
|
-
text: part.text,
|
|
7337
|
-
step_index
|
|
7338
|
-
};
|
|
7339
|
-
case "reasoning-delta": return {
|
|
7340
|
-
kind: "reasoning",
|
|
7341
|
-
text: part.text,
|
|
7342
|
-
step_index
|
|
7343
|
-
};
|
|
7344
|
-
case "tool-input-start": return {
|
|
7345
|
-
kind: "tool_call_start",
|
|
7346
|
-
id: part.id,
|
|
7347
|
-
name: part.toolName,
|
|
7348
|
-
step_index
|
|
7349
|
-
};
|
|
7350
|
-
case "tool-input-delta": return {
|
|
7351
|
-
kind: "tool_call_input_delta",
|
|
7352
|
-
id: part.id,
|
|
7353
|
-
delta: part.delta,
|
|
7354
|
-
step_index
|
|
7355
|
-
};
|
|
7356
|
-
case "tool-call": return {
|
|
7357
|
-
kind: "tool_call_end",
|
|
7358
|
-
id: part.toolCallId,
|
|
7359
|
-
input: part.input,
|
|
7360
|
-
step_index
|
|
7361
|
-
};
|
|
7362
|
-
case "finish-step": return {
|
|
7363
|
-
kind: "step_finish",
|
|
7364
|
-
step_index,
|
|
7365
|
-
finish_reason: map_finish_reason(part.finishReason),
|
|
7366
|
-
usage: default_usage_from_sdk(part.usage)
|
|
7367
|
-
};
|
|
7368
|
-
default: return;
|
|
7369
|
-
}
|
|
7370
|
-
}
|
|
7371
|
-
/**
|
|
7372
|
-
* Normalize a raw AI SDK usage object into UsageTotals for a streamed
|
|
7373
|
-
* step_finish chunk.
|
|
7374
|
-
*/
|
|
7375
|
-
function default_usage_from_sdk(usage) {
|
|
7376
|
-
return default_normalize_usage(to_raw_provider_usage(usage));
|
|
7377
|
-
}
|
|
7378
|
-
/**
|
|
7379
|
-
* Run one streamText call, dispatching StreamChunks as parts arrive and
|
|
7380
|
-
* accumulating them into a TurnResult once the stream completes.
|
|
7381
|
-
*/
|
|
7382
|
-
async function collect_stream(params, step_index, dispatcher, on_first_chunk, internal_controller, adapter) {
|
|
7383
|
-
const stream_result = streamText(params);
|
|
7384
|
-
let text = "";
|
|
7385
|
-
const tool_calls = [];
|
|
7386
|
-
let finish_reason = "stop";
|
|
7387
|
-
let raw_usage = {};
|
|
7388
|
-
let provider_reported;
|
|
7389
|
-
let first = true;
|
|
7390
|
-
for await (const part of stream_result.stream) {
|
|
7391
|
-
if (first) {
|
|
7392
|
-
first = false;
|
|
7393
|
-
on_first_chunk();
|
|
7394
|
-
}
|
|
7395
|
-
if (part.type === "text-delta") text += part.text;
|
|
7396
|
-
if (part.type === "tool-call") tool_calls.push({
|
|
7397
|
-
id: part.toolCallId,
|
|
7398
|
-
name: part.toolName,
|
|
7399
|
-
input: part.input
|
|
7400
|
-
});
|
|
7401
|
-
if (part.type === "finish-step") {
|
|
7402
|
-
finish_reason = map_finish_reason(part.finishReason);
|
|
7403
|
-
raw_usage = to_raw_provider_usage(part.usage);
|
|
7404
|
-
provider_reported = to_provider_reported(part.providerMetadata);
|
|
7405
|
-
}
|
|
7406
|
-
if (part.type === "error") throw part.error;
|
|
7407
|
-
if (part.type === "abort") throw new aborted_error("aborted", { step_index });
|
|
7408
|
-
const chunk = map_stream_part_to_chunk(part, step_index);
|
|
7409
|
-
if (chunk === void 0) continue;
|
|
7410
|
-
try {
|
|
7411
|
-
await dispatcher.dispatch(chunk);
|
|
7412
|
-
} catch (err) {
|
|
7413
|
-
internal_controller.abort();
|
|
7414
|
-
throw err;
|
|
7415
|
-
}
|
|
7416
|
-
}
|
|
7417
|
-
return {
|
|
7418
|
-
text,
|
|
7419
|
-
tool_calls,
|
|
7420
|
-
finish_reason,
|
|
7421
|
-
usage: adapter.normalize_usage(raw_usage),
|
|
7422
|
-
...provider_reported !== void 0 ? { provider_reported } : {}
|
|
7423
|
-
};
|
|
7424
|
-
}
|
|
7425
|
-
/**
|
|
7426
|
-
* Run one generateText call and map its result into a TurnResult, recovering
|
|
7427
|
-
* a schema-validation failure from the SDK via recover_no_object_generated
|
|
7428
|
-
* instead of letting it throw.
|
|
7429
|
-
*/
|
|
7430
|
-
async function collect_non_stream(params, adapter) {
|
|
7431
|
-
let result;
|
|
7432
|
-
try {
|
|
7433
|
-
result = await generateText(params);
|
|
7434
|
-
} catch (err) {
|
|
7435
|
-
const recovered = recover_no_object_generated(err, adapter);
|
|
7436
|
-
if (recovered !== void 0) return recovered;
|
|
7437
|
-
throw err;
|
|
7438
|
-
}
|
|
7439
|
-
const tool_calls = [];
|
|
7440
|
-
for (const tc of result.toolCalls) tool_calls.push({
|
|
7441
|
-
id: tc.toolCallId,
|
|
7442
|
-
name: tc.toolName,
|
|
7443
|
-
input: tc.input
|
|
7444
|
-
});
|
|
7445
|
-
const raw_usage = to_raw_provider_usage(result.usage);
|
|
7446
|
-
const provider_reported = to_provider_reported(result.providerMetadata);
|
|
7447
|
-
return {
|
|
7448
|
-
text: result.text,
|
|
7449
|
-
tool_calls,
|
|
7450
|
-
finish_reason: map_finish_reason(result.finishReason),
|
|
7451
|
-
usage: adapter.normalize_usage(raw_usage),
|
|
7452
|
-
...provider_reported !== void 0 ? { provider_reported } : {}
|
|
7453
|
-
};
|
|
7454
|
-
}
|
|
7455
|
-
/**
|
|
7456
|
-
* When `output` (structured output) is in play, `generateText` eagerly parses the
|
|
7457
|
-
* model's text against the schema and throws `NoObjectGeneratedError` if it
|
|
7458
|
-
* does not conform. That parse is the SDK's, not fascicle's: turning it into a
|
|
7459
|
-
* thrown error would skip the engine's own schema-parse + repair loop (and the
|
|
7460
|
-
* error is not a retryable transient, so it would surface raw). Instead we
|
|
7461
|
-
* recover the model's raw text from the error and hand it back as a normal
|
|
7462
|
-
* turn result, so `parse_with_schema` re-validates it and the repair loop
|
|
7463
|
-
* engages exactly as it does for the prompt-based path. Returns undefined for
|
|
7464
|
-
* any other error so the caller rethrows.
|
|
7465
|
-
*
|
|
7466
|
-
* The recovered turn carries no provider_reported: the SDK's error exposes
|
|
7467
|
-
* text, usage, finishReason and response metadata, but not providerMetadata,
|
|
7468
|
-
* so there is nothing to read. The repair turn that follows reports normally.
|
|
7469
|
-
*/
|
|
7470
|
-
function recover_no_object_generated(err, adapter) {
|
|
7471
|
-
if (!NoObjectGeneratedError.isInstance(err)) return void 0;
|
|
7472
|
-
const text_field = Reflect.get(err, "text");
|
|
7473
|
-
const finish_field = Reflect.get(err, "finishReason");
|
|
7474
|
-
const raw_usage = to_raw_provider_usage(Reflect.get(err, "usage"));
|
|
7475
|
-
return {
|
|
7476
|
-
text: typeof text_field === "string" ? text_field : "",
|
|
7477
|
-
tool_calls: [],
|
|
7478
|
-
finish_reason: map_finish_reason(typeof finish_field === "string" ? finish_field : void 0),
|
|
7479
|
-
usage: adapter.normalize_usage(raw_usage)
|
|
7480
|
-
};
|
|
7481
|
-
}
|
|
7482
|
-
/**
|
|
7483
|
-
* Build the single-attempt SDK turn for one generate call: the
|
|
7484
|
-
* generateText/streamText call body behind the same neutral seam a native
|
|
7485
|
-
* adapter's invoke_turn implements. The built model is memoized across steps
|
|
7486
|
-
* of one generate call. No retry here: generate.ts wraps the returned turn in
|
|
7487
|
-
* the engine-owned retry_turn.
|
|
7488
|
-
*/
|
|
7489
|
-
function create_ai_sdk_turn(cfg) {
|
|
7490
|
-
let model_instance;
|
|
7491
|
-
const get_model = async () => {
|
|
7492
|
-
if (model_instance === void 0) model_instance = await cfg.adapter.build_model(cfg.model_id);
|
|
7493
|
-
return model_instance;
|
|
7494
|
-
};
|
|
7495
|
-
let telemetry_options;
|
|
7496
|
-
let telemetry_resolved = false;
|
|
7497
|
-
const get_telemetry = async () => {
|
|
7498
|
-
if (!telemetry_resolved) {
|
|
7499
|
-
telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry);
|
|
7500
|
-
telemetry_resolved = true;
|
|
7501
|
-
}
|
|
7502
|
-
return telemetry_options;
|
|
7503
|
-
};
|
|
7504
|
-
const sdk_tools = to_sdk_tools(cfg.tools);
|
|
7505
|
-
let output_spec;
|
|
7506
|
-
if (cfg.schema !== void 0 && cfg.tools.length === 0 && cfg.adapter.supports("structured_output")) output_spec = Output.object({ schema: cfg.schema });
|
|
7507
|
-
const provider_options = cfg.provider_options;
|
|
7508
|
-
return async (args) => {
|
|
7509
|
-
const model = await get_model();
|
|
7510
|
-
const telemetry = await get_telemetry();
|
|
7511
|
-
const internal_controller = new AbortController();
|
|
7512
|
-
const cancel_on_user_abort = () => {
|
|
7513
|
-
internal_controller.abort(args.abort.reason);
|
|
7514
|
-
};
|
|
7515
|
-
if (args.abort.aborted) internal_controller.abort(args.abort.reason);
|
|
7516
|
-
else args.abort.addEventListener("abort", cancel_on_user_abort, { once: true });
|
|
7517
|
-
const { system: hoisted_system, messages: sdk_messages } = split_leading_system(to_sdk_messages(args.messages));
|
|
7518
|
-
const base_params = {
|
|
7519
|
-
model,
|
|
7520
|
-
messages: sdk_messages,
|
|
7521
|
-
abortSignal: internal_controller.signal,
|
|
7522
|
-
stopWhen: isStepCount(1),
|
|
7523
|
-
maxRetries: 0
|
|
7524
|
-
};
|
|
7525
|
-
if (hoisted_system !== void 0) base_params.instructions = hoisted_system;
|
|
7526
|
-
if (sdk_tools !== void 0) base_params.tools = sdk_tools;
|
|
7527
|
-
if (output_spec !== void 0) base_params.output = output_spec;
|
|
7528
|
-
if (provider_options !== void 0) base_params.providerOptions = provider_options;
|
|
7529
|
-
if (cfg.temperature !== void 0) base_params.temperature = cfg.temperature;
|
|
7530
|
-
if (cfg.max_tokens !== void 0) base_params.maxOutputTokens = cfg.max_tokens;
|
|
7531
|
-
if (cfg.top_p !== void 0) base_params.topP = cfg.top_p;
|
|
7532
|
-
if (telemetry !== void 0) base_params.experimental_telemetry = telemetry;
|
|
7533
|
-
try {
|
|
7534
|
-
if (args.stream) return await collect_stream(base_params, args.step_index, cfg.dispatcher, args.on_first_chunk, internal_controller, cfg.adapter);
|
|
7535
|
-
return await collect_non_stream(base_params, cfg.adapter);
|
|
7536
|
-
} finally {
|
|
7537
|
-
args.abort.removeEventListener("abort", cancel_on_user_abort);
|
|
7538
|
-
}
|
|
7539
|
-
};
|
|
7540
|
-
}
|
|
7541
|
-
//#endregion
|
|
7542
7063
|
//#region src/engine/generate.ts
|
|
7543
7064
|
/**
|
|
7544
7065
|
* Build the initial message list for a generate call from `opts.system` and
|
|
@@ -7842,6 +7363,13 @@ async function generate(opts_in, engine) {
|
|
|
7842
7363
|
if (effort !== "none" && effort_translation.effort_ignored) record_effort_ignored(trajectory, target.model_id);
|
|
7843
7364
|
const combined_provider_options = merge_provider_options(effort_translation.provider_options, opts.provider_options);
|
|
7844
7365
|
const provider_options = combined_provider_options !== void 0 && Object.keys(combined_provider_options).length > 0 ? combined_provider_options : void 0;
|
|
7366
|
+
let ai_sdk_invoke_mod;
|
|
7367
|
+
try {
|
|
7368
|
+
ai_sdk_invoke_mod = await import("./invoke-D9pxbZcu.js");
|
|
7369
|
+
} catch (err) {
|
|
7370
|
+
throw missing_peer_error("ai", err);
|
|
7371
|
+
}
|
|
7372
|
+
const { create_ai_sdk_turn } = ai_sdk_invoke_mod;
|
|
7845
7373
|
invoke_once = build_ai_sdk_invoke({
|
|
7846
7374
|
invoke_turn: create_ai_sdk_turn({
|
|
7847
7375
|
adapter,
|
|
@@ -7947,19 +7475,19 @@ async function generate(opts_in, engine) {
|
|
|
7947
7475
|
finish_reason = loop_result.finish_reason;
|
|
7948
7476
|
if (opts.schema === void 0) break;
|
|
7949
7477
|
if (finish_reason !== "stop") throw new incomplete_generation_error(finish_reason, text, last_provider_reported(steps_accum));
|
|
7950
|
-
const parse = parse_with_schema(opts.schema, text);
|
|
7478
|
+
const parse = await parse_with_schema(opts.schema, text);
|
|
7951
7479
|
if (parse.ok) {
|
|
7952
7480
|
content_parsed = { value: parse.value };
|
|
7953
7481
|
break;
|
|
7954
7482
|
}
|
|
7955
7483
|
record_schema_validation_failed(trajectory, {
|
|
7956
7484
|
attempt: repair_remaining === schema_repair_attempts ? "initial" : "repair",
|
|
7957
|
-
|
|
7485
|
+
schema_issues: format_schema_issues(parse.issues),
|
|
7958
7486
|
raw_text: text
|
|
7959
7487
|
});
|
|
7960
|
-
if (repair_remaining <= 0 || total_steps >= max_steps) throw_schema_validation(parse.
|
|
7488
|
+
if (repair_remaining <= 0 || total_steps >= max_steps) throw_schema_validation(parse.issues, text);
|
|
7961
7489
|
repair_remaining -= 1;
|
|
7962
|
-
messages_mutable.push(build_repair_message(parse.
|
|
7490
|
+
messages_mutable.push(build_repair_message(parse.issues));
|
|
7963
7491
|
}
|
|
7964
7492
|
const aggregated_usage = sum_usage(steps_accum);
|
|
7965
7493
|
const aggregated_cost = aggregate_cost(steps_accum, target.provider);
|
|
@@ -8591,7 +8119,7 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
|
|
|
8591
8119
|
if (on_parse_error) on_parse_error(err, line);
|
|
8592
8120
|
return;
|
|
8593
8121
|
}
|
|
8594
|
-
const result =
|
|
8122
|
+
const result = parse_trajectory_event(parsed);
|
|
8595
8123
|
if (!result.success) {
|
|
8596
8124
|
rejected++;
|
|
8597
8125
|
if (on_parse_error) on_parse_error(result.error, line);
|
|
@@ -8634,7 +8162,7 @@ function handle_ingest(req, res, broadcaster, on_parse_error) {
|
|
|
8634
8162
|
* current offset means the file shrunk. Reset offset to 0 and re-stream.
|
|
8635
8163
|
* - Partial last line: if the trailing chunk has no `\n`, buffer it and
|
|
8636
8164
|
* wait. Never parse a half-written line.
|
|
8637
|
-
* - Schema failures: a line that fails `
|
|
8165
|
+
* - Schema failures: a line that fails `parse_trajectory_event` is
|
|
8638
8166
|
* dropped and surfaced to `on_parse_error`. The stream keeps going.
|
|
8639
8167
|
*
|
|
8640
8168
|
* The watcher is fs.watch-based; reads are serialized and change events
|
|
@@ -8671,7 +8199,7 @@ function start_tail(options) {
|
|
|
8671
8199
|
if (on_parse_error) on_parse_error(err, line);
|
|
8672
8200
|
return;
|
|
8673
8201
|
}
|
|
8674
|
-
const result =
|
|
8202
|
+
const result = parse_trajectory_event(parsed);
|
|
8675
8203
|
if (!result.success) {
|
|
8676
8204
|
if (on_parse_error) on_parse_error(result.error, line);
|
|
8677
8205
|
return;
|
|
@@ -8998,6 +8526,6 @@ if (process.argv[1] !== void 0 && process.argv[1] === fileURLToPath(import.meta.
|
|
|
8998
8526
|
process.exit(1);
|
|
8999
8527
|
});
|
|
9000
8528
|
//#endregion
|
|
9001
|
-
export { STEP_KINDS, aborted_error, adversarial, bench, branch, checkpoint, claude_cli_error, compose, consensus, create_engine,
|
|
8529
|
+
export { STEP_KINDS, aborted_error, adversarial, bench, bench_suspend_error, branch, checkpoint, claude_cli_error, compose, consensus, create_engine, default_normalize_usage, describe, describe_cycle_error, engine_config_error, engine_disposed_error, ensemble, ensemble_step, fallback, flow_schema_default as flow_schema, forward_standard_env, improve, incomplete_generation_error, is_custom_trajectory_event, is_emit_event, is_span_end_event, is_span_start_event, is_step_kind, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_required_error, normalize_score, on_chunk_error, parallel, parse_trajectory_event, 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, start_viewer, stash, step, suspend, suspended_error, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, use, write_baseline };
|
|
9002
8530
|
|
|
9003
8531
|
//# sourceMappingURL=index.js.map
|