fascicle 0.12.8 → 0.12.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as Step, c as StepMetadata, d as TrajectoryLogger, i as RunContext, l as StepOutput, n as CheckpointStore, o as StepFn, r as CleanupFn, s as StepInput, t as AnyStep, u as TrajectoryEvent } from "./types-DBpU27sQ.js";
2
2
  import { n as SchemaIssue, r as ToolSchema, t as AnySchema } from "./types-BK0UW28o.js";
3
3
  import { _ as parse_trajectory_event, a as ParsedTrajectoryEvent, c as SpanEndEvent, d as is_checkpoint_event, f as is_custom_trajectory_event, g as is_span_start_event, h as is_span_end_event, i as EmitEvent, l as SpanStartEvent, m as is_run_end_event, n as CheckpointStatus, o as RunEndEvent, p as is_emit_event, r as CustomTrajectoryEvent, s as RunEndStatus, t as CheckpointEvent, u as TrajectoryParseResult } from "./trajectory-ByoOQZ6T.js";
4
- import { A as TurnRequest, B as ProviderFactory, C as StepTiming, D as ToolApprovalRequest, E as ToolApprovalHandler, F as EffortTranslation, H as RawProviderUsage, I as ExternalAgentAdapter, L as NativeProviderAdapter, M as UsageTotals, N as UserContentPart, O as ToolCallRecord, P as AiSdkProviderAdapter, R as ProviderAdapter, S as StepRecord, T as Tool, U as default_normalize_usage, V as ProviderTransport, _ as ProviderConfigMap, a as Engine, b as RetryFailureKind, c as FinishReason, d as Message, f as PrepareStepContext, g as PricingTable, h as Pricing, i as EffortLevel, j as TurnResult, k as ToolExecContext, l as GenerateOptions, m as PrepareStepResult, n as AssistantContentPart, o as EngineConfig, p as PrepareStepHook, r as CostBreakdown, s as EngineDefaults, t as AiSdkTelemetrySettings, u as GenerateResult, v as ProviderInit, w as StreamChunk, x as RetryPolicy, y as ResolvedModel, z as ProviderCapability } from "./types-CLigYA62.js";
4
+ import { A as ToolExecContext, B as ProviderCapability, C as StepRecord, D as ToolApprovalHandler, E as Tool, F as AiSdkProviderAdapter, G as ClaudeCliProviderReported, H as ProviderTransport, I as EffortTranslation, L as ExternalAgentAdapter, M as TurnResult, N as UsageTotals, O as ToolApprovalRequest, P as UserContentPart, R as NativeProviderAdapter, S as RetryPolicy, T as StreamChunk, U as RawProviderUsage, V as ProviderFactory, W as default_normalize_usage, _ as PricingTable, a as Engine, b as ResolvedModel, c as FinishReason, d as GenerateTiming, f as Message, g as Pricing, h as PrepareStepResult, i as EffortLevel, j as TurnRequest, k as ToolCallRecord, l as GenerateOptions, m as PrepareStepHook, n as AssistantContentPart, o as EngineConfig, p as PrepareStepContext, r as CostBreakdown, s as EngineDefaults, t as AiSdkTelemetrySettings, u as GenerateResult, v as ProviderConfigMap, w as StepTiming, x as RetryFailureKind, y as ProviderInit, z as ProviderAdapter } from "./types-B46o3nHw.js";
5
5
 
6
6
  //#region src/core/flow-schema.json.d.ts
7
7
  declare let $schema: string;
@@ -849,36 +849,100 @@ type PipeOptions = {
849
849
  declare function pipe<i, a, b>(inner: Step<i, a>, fn: (value: a) => b | Promise<b>, options?: PipeOptions): Step<i, b>;
850
850
  //#endregion
851
851
  //#region src/core/retry.d.ts
852
+ /**
853
+ * How a retry reached its value: `attempts` counts every dispatch including the
854
+ * one that succeeded, and `errors` holds each failed attempt's error in order,
855
+ * so `errors.length === attempts - 1`.
856
+ */
857
+ type RetryOutcome<o> = {
858
+ readonly value: o;
859
+ readonly attempts: number;
860
+ readonly errors: ReadonlyArray<unknown>;
861
+ };
852
862
  type RetryConfig = {
853
863
  readonly name?: string;
854
864
  readonly max_attempts: number;
855
865
  readonly backoff_ms?: number;
856
866
  readonly max_delay_ms?: number;
857
867
  readonly jitter?: boolean;
868
+ /**
869
+ * Decide whether an application error is retryable. Returning false
870
+ * propagates the error untouched, the way a control-flow signal does.
871
+ * Omitted, every application error is retryable.
872
+ */
873
+ readonly when?: (err: unknown, attempt: number) => boolean;
858
874
  readonly on_error?: (err: unknown, attempt: number) => void;
859
875
  };
876
+ /**
877
+ * The `project` option `retry` accepts beside `RetryConfig`. It sits outside
878
+ * `RetryConfig` so a config annotated as `RetryConfig` leaves the output type
879
+ * to be inferred from the inner step.
880
+ */
881
+ type RetryProjection<o, projected> = {
882
+ /**
883
+ * Map the `RetryOutcome` envelope into the step's output inside the retry
884
+ * step itself, so `describe` and the trajectory gain no wrapper node.
885
+ * Omitted, the value is the output.
886
+ */
887
+ readonly project?: (outcome: RetryOutcome<o>) => projected;
888
+ };
860
889
  /**
861
890
  * Build a retrying step around `inner`.
862
891
  *
863
892
  * Runs `inner` up to `max_attempts` times with exponential backoff between
864
- * failures. Application errors consume an attempt and fire `on_error`;
865
- * control-flow signals propagate untouched.
893
+ * failures. Retryable application errors consume an attempt and fire
894
+ * `on_error`; control-flow signals and errors `when` rejects propagate
895
+ * untouched. `project` maps the outcome envelope into the output.
866
896
  */
867
- declare function retry<i, o>(inner: Step<i, o>, config: RetryConfig): Step<i, o>;
897
+ declare function retry<i, o, projected = o>(inner: Step<i, o>, config: RetryConfig & RetryProjection<o, projected>): Step<i, projected>;
868
898
  //#endregion
869
899
  //#region src/core/fallback.d.ts
900
+ /**
901
+ * Which leg produced a fallback's value. `primary_error` is the error that
902
+ * sent the run to the backup, present only when `source` is `'backup'`.
903
+ */
904
+ type FallbackOutcome<o> = {
905
+ readonly value: o;
906
+ readonly source: 'primary';
907
+ readonly primary_error?: undefined;
908
+ } | {
909
+ readonly value: o;
910
+ readonly source: 'backup';
911
+ readonly primary_error: unknown;
912
+ };
870
913
  type FallbackOptions<i = unknown> = {
871
914
  readonly name?: string;
915
+ /**
916
+ * Decide whether a primary error sends the run to the backup. Returning
917
+ * false propagates the error untouched, the way a control-flow signal
918
+ * does. Omitted, every application error does.
919
+ */
920
+ readonly when?: (err: unknown) => boolean;
872
921
  readonly handoff?: (input: i, err: unknown) => i;
873
922
  };
923
+ /**
924
+ * The `project` option `fallback` accepts beside `FallbackOptions`. It sits
925
+ * outside `FallbackOptions` so options annotated as `FallbackOptions` leave
926
+ * the output type to be inferred from the two legs.
927
+ */
928
+ type FallbackProjection<o, projected> = {
929
+ /**
930
+ * Map the `FallbackOutcome` envelope into the step's output inside the
931
+ * fallback step itself, so `describe` and the trajectory gain no wrapper
932
+ * node. Omitted, the value is the output.
933
+ */
934
+ readonly project?: (outcome: FallbackOutcome<o>) => projected;
935
+ };
874
936
  /**
875
937
  * Build a primary-or-backup step.
876
938
  *
877
- * Runs `primary`; on an application error runs `backup` with the same input,
878
- * or with `handoff(input, err)` when the option is set. Control-flow signals
879
- * propagate without triggering the backup or the handoff.
939
+ * Runs `primary`; on an application error `when` accepts, runs `backup` with
940
+ * the same input, or with `handoff(input, err)` when the option is set.
941
+ * Control-flow signals and errors `when` rejects propagate without
942
+ * triggering the backup or the handoff. `project` maps the outcome envelope
943
+ * into the output.
880
944
  */
881
- declare function fallback<i, o>(primary: Step<i, o>, backup: Step<i, o>, options?: FallbackOptions<i>): Step<i, o>;
945
+ declare function fallback<i, o, projected = o>(primary: Step<i, o>, backup: Step<i, o>, options?: FallbackOptions<i> & FallbackProjection<o, projected>): Step<i, projected>;
882
946
  //#endregion
883
947
  //#region src/core/timeout.d.ts
884
948
  type TimeoutOptions = {
@@ -1167,6 +1231,20 @@ type Throughput = {
1167
1231
  */
1168
1232
  declare function throughput(source: GenerateResult<unknown> | StepRecord | ReadonlyArray<StepRecord>): Throughput | undefined;
1169
1233
  //#endregion
1234
+ //#region src/engine/providers/claude_cli/reported.d.ts
1235
+ /**
1236
+ * Read the claude CLI's reported run detail off anything carrying
1237
+ * `provider_reported`: a `GenerateResult`, a `StepRecord`, or an
1238
+ * `incomplete_generation_error`.
1239
+ *
1240
+ * Returns undefined when the source has no `claude_cli` entry, or when the
1241
+ * entry lacks a string `session_id` and a numeric `duration_ms`.
1242
+ * `duration_api_ms` carries through only when it is a number.
1243
+ */
1244
+ declare function claude_cli_reported(source: {
1245
+ readonly provider_reported?: Readonly<Record<string, unknown>>;
1246
+ }): ClaudeCliProviderReported | undefined;
1247
+ //#endregion
1170
1248
  //#region src/engine/errors.d.ts
1171
1249
  declare class rate_limit_error extends Error {
1172
1250
  readonly kind: "rate_limit_error";
@@ -1844,6 +1922,15 @@ type ModelCallConfig<T = string, projected = GenerateResult<T>> = {
1844
1922
  readonly tool_call_repair_attempts?: number;
1845
1923
  readonly max_tool_calls_per_step?: number;
1846
1924
  readonly on_tool_approval?: ToolApprovalHandler;
1925
+ /**
1926
+ * Observe every chunk of the call as it streams, for a live renderer that
1927
+ * should not go through `run.stream`. Setting it makes the call stream.
1928
+ * It is called beside the `run.stream` forwarder, never in place of it, so
1929
+ * abort and the trajectory stay owned by the composition layer. A returned
1930
+ * promise is awaited before the next chunk, and a throw aborts the call
1931
+ * with `on_chunk_error`, as `GenerateOptions.on_chunk` does.
1932
+ */
1933
+ readonly on_chunk?: (chunk: StreamChunk) => void | Promise<void>;
1847
1934
  /**
1848
1935
  * Map the `GenerateResult` envelope into the step's output at the source.
1849
1936
  * The projection runs inside the model_call step itself, so `describe` and
@@ -1858,7 +1945,8 @@ type ModelCallConfig<T = string, projected = GenerateResult<T>> = {
1858
1945
  *
1859
1946
  * Threads `ctx.abort` and `ctx.trajectory` (nested under the model_call
1860
1947
  * step's own span) into every call, and, when `run.stream` is driving,
1861
- * records each chunk as a `model_chunk` trajectory event. `cfg.project`
1948
+ * records each chunk as a `model_chunk` trajectory event before handing it
1949
+ * to `cfg.on_chunk`. `cfg.project`
1862
1950
  * maps the `GenerateResult` envelope into the step's output inside the same
1863
1951
  * step; omitted, the envelope is the output.
1864
1952
  */
@@ -1895,5 +1983,5 @@ declare function model_step<T = string>(cfg: Omit<ModelCallConfig<T>, 'project'>
1895
1983
  */
1896
1984
  declare function forward_standard_env(): Record<string, string>;
1897
1985
  //#endregion
1898
- export { type AdversarialBuildInput, type AdversarialConfig, type AdversarialCritiqueResult, type AdversarialResult, type AiSdkProviderAdapter, type AiSdkTelemetrySettings, type AnySchema, type AnyStep, type AssistantContentPart, type BenchCase, type BenchOptions, type BenchReport, type BenchSummary, type BracketRecord, type BranchConfig, type Candidate, type CaseResult, type Chain, type ChainOpen, type ChainStepOptions, type CheckpointConfig, type CheckpointEvent, type CheckpointStatus, type CheckpointStore, type ClaudeCliErrorReason, type CleanupFn, type ComposeConfig, type ConsensusConfig, type ConsensusResult, type CostBreakdown, type CustomTrajectoryEvent, type DescribeOptions, type EffortLevel, type EffortTranslation, type EmitEvent, type Engine, type EngineConfig, type EngineDefaults, type EnsembleConfig, type EnsembleResult, type EnsembleStepConfig, type EnsembleStepResult, type ExternalAgentAdapter, type FallbackOptions, type FinishReason, type FlowNode, type FlowValue, type GateConfig, type GenerateOptions, type GenerateResult, type HistoryEntry, type ImproveBudget, type ImproveConfig, type ImproveResult, type ImproveRoundInput, type Improvement, type Judge, type JudgeArgs, type JudgeLlmConfig, type JudgeWithFn, type LearnConfig, type LearnInput, type LearnResult, type Lesson, type LoopConfig, type LoopGuardPredicate, type LoopGuardResult, type LoopOutcome, type MapConfig, type Message, type ModelCallConfig, type ModelCallInput, type NativeProviderAdapter, type ParallelOptions, type ParsedTrajectoryEvent, type PerCaseDelta, type PipeOptions, type PrepareStepContext, type PrepareStepHook, type PrepareStepResult, type Pricing, type PricingTable, type ProviderAdapter, type ProviderCapability, type ProviderConfigMap, type ProviderFactory, type ProviderInit, type ProviderTransport, type RawProviderUsage, type RegressionCompareOptions, type RegressionDelta, type RegressionReport, type ResolvedModel, type RetryConfig, type RetryFailureKind, type RetryPolicy, type RunContext, type RunEndEvent, type RunEndStatus, type RunOptions, type RunOutcome, STEP_KINDS, type SchemaIssue, type ScopeOptions, type Score, type ScoredCandidate, type SequenceOptions, type SpanEndEvent, type SpanStartEvent, type StashOptions, type Step, type StepFn, type StepInput, type StepKind, type StepMetadata, type StepOutput, type StepRecord, type StepTiming, type StreamChunk, type StreamingRunHandle, type SuspendConfig, type Throughput, type TimeoutOptions, type Tool, type ToolApprovalHandler, type ToolApprovalRequest, type ToolCallRecord, type ToolExecContext, type ToolSchema, type TournamentConfig, type TournamentResult, type TrajectoryEvent, type TrajectoryLogger, type TrajectoryParseResult, type TrajectorySource, type TurnRequest, type TurnResult, type UsageTotals, type UseOptions, type UserContentPart, aborted_error, adversarial, assert_valid_step_id, bench, bench_suspend_error, branch, chain, checkpoint, claude_cli_error, compose, consensus, create_engine, default_normalize_usage, describe, describe_cycle_error, engine_config_error, engine_disposed_error, ensemble, ensemble_step, error_path, fallback, __json_default_export as flow_schema, forward_standard_env, gate, improve, incomplete_generation_error, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step, is_step_kind, is_valid_step_id, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_required_error, model_step, normalize_score, on_chunk_error, parallel, parse_trajectory_event, pipe, provider_auth_error, provider_capability_error, provider_error, provider_not_configured_error, provider_required_error, rate_limit_error, read_baseline, regression_compare, resolve_display_name, resume_validation_error, retry, run, schema_validation_error, scope, sequence, stash, step, suggest_step_id, suspend, suspended_error, throughput, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, use, write_baseline };
1986
+ export { type AdversarialBuildInput, type AdversarialConfig, type AdversarialCritiqueResult, type AdversarialResult, type AiSdkProviderAdapter, type AiSdkTelemetrySettings, type AnySchema, type AnyStep, type AssistantContentPart, type BenchCase, type BenchOptions, type BenchReport, type BenchSummary, type BracketRecord, type BranchConfig, type Candidate, type CaseResult, type Chain, type ChainOpen, type ChainStepOptions, type CheckpointConfig, type CheckpointEvent, type CheckpointStatus, type CheckpointStore, type ClaudeCliErrorReason, type ClaudeCliProviderReported, type CleanupFn, type ComposeConfig, type ConsensusConfig, type ConsensusResult, type CostBreakdown, type CustomTrajectoryEvent, type DescribeOptions, type EffortLevel, type EffortTranslation, type EmitEvent, type Engine, type EngineConfig, type EngineDefaults, type EnsembleConfig, type EnsembleResult, type EnsembleStepConfig, type EnsembleStepResult, type ExternalAgentAdapter, type FallbackOptions, type FallbackOutcome, type FallbackProjection, type FinishReason, type FlowNode, type FlowValue, type GateConfig, type GenerateOptions, type GenerateResult, type GenerateTiming, type HistoryEntry, type ImproveBudget, type ImproveConfig, type ImproveResult, type ImproveRoundInput, type Improvement, type Judge, type JudgeArgs, type JudgeLlmConfig, type JudgeWithFn, type LearnConfig, type LearnInput, type LearnResult, type Lesson, type LoopConfig, type LoopGuardPredicate, type LoopGuardResult, type LoopOutcome, type MapConfig, type Message, type ModelCallConfig, type ModelCallInput, type NativeProviderAdapter, type ParallelOptions, type ParsedTrajectoryEvent, type PerCaseDelta, type PipeOptions, type PrepareStepContext, type PrepareStepHook, type PrepareStepResult, type Pricing, type PricingTable, type ProviderAdapter, type ProviderCapability, type ProviderConfigMap, type ProviderFactory, type ProviderInit, type ProviderTransport, type RawProviderUsage, type RegressionCompareOptions, type RegressionDelta, type RegressionReport, type ResolvedModel, type RetryConfig, type RetryFailureKind, type RetryOutcome, type RetryPolicy, type RetryProjection, type RunContext, type RunEndEvent, type RunEndStatus, type RunOptions, type RunOutcome, STEP_KINDS, type SchemaIssue, type ScopeOptions, type Score, type ScoredCandidate, type SequenceOptions, type SpanEndEvent, type SpanStartEvent, type StashOptions, type Step, type StepFn, type StepInput, type StepKind, type StepMetadata, type StepOutput, type StepRecord, type StepTiming, type StreamChunk, type StreamingRunHandle, type SuspendConfig, type Throughput, type TimeoutOptions, type Tool, type ToolApprovalHandler, type ToolApprovalRequest, type ToolCallRecord, type ToolExecContext, type ToolSchema, type TournamentConfig, type TournamentResult, type TrajectoryEvent, type TrajectoryLogger, type TrajectoryParseResult, type TrajectorySource, type TurnRequest, type TurnResult, type UsageTotals, type UseOptions, type UserContentPart, aborted_error, adversarial, assert_valid_step_id, bench, bench_suspend_error, branch, chain, checkpoint, claude_cli_error, claude_cli_reported, compose, consensus, create_engine, default_normalize_usage, describe, describe_cycle_error, engine_config_error, engine_disposed_error, ensemble, ensemble_step, error_path, fallback, __json_default_export as flow_schema, forward_standard_env, gate, improve, incomplete_generation_error, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step, is_step_kind, is_valid_step_id, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_required_error, model_step, normalize_score, on_chunk_error, parallel, parse_trajectory_event, pipe, provider_auth_error, provider_capability_error, provider_error, provider_not_configured_error, provider_required_error, rate_limit_error, read_baseline, regression_compare, resolve_display_name, resume_validation_error, retry, run, schema_validation_error, scope, sequence, stash, step, suggest_step_id, suspend, suspended_error, throughput, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, use, write_baseline };
1899
1987
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { A as describe_cycle_error, C as is_valid_step_id, D as resolve_display_name, E as describe, M as resume_validation_error, N as suspended_error, O as is_step, P as timeout_error, S as assert_valid_step_id, T as run, _ as map, a as suspend, b as sequence, c as checkpoint, d as timeout, f as fallback, g as pipe, i as use, j as error_path, k as aborted_error, l as compose, n as scope, p as retry, r as stash, t as chain, u as loop, v as branch, w as suggest_step_id, x as step, y as parallel } from "./core-CFdEjtiT.js";
2
- import { t as create_engine } from "./engine-DQiQHiy8.js";
1
+ import { A as describe_cycle_error, C as is_valid_step_id, D as resolve_display_name, E as describe, M as resume_validation_error, N as suspended_error, O as is_step, P as timeout_error, S as assert_valid_step_id, T as run, _ as map, a as suspend, b as sequence, c as checkpoint, d as timeout, f as fallback, g as pipe, i as use, j as error_path, k as aborted_error, l as compose, n as scope, p as retry, r as stash, t as chain, u as loop, v as branch, w as suggest_step_id, x as step, y as parallel } from "./core-BClsJ3h0.js";
2
+ import { t as create_engine } from "./engine-M0fpGDol.js";
3
3
  import { a as is_span_end_event, i as is_run_end_event, n as is_custom_trajectory_event, o as is_span_start_event, r as is_emit_event, s as parse_trajectory_event, t as is_checkpoint_event } from "./trajectory-D1eq9eue.js";
4
4
  import { a as http_logger, n as tee_logger, o as filesystem_logger } from "./adapters-CutexJd3.js";
5
- import { _ as provider_required_error, b as tool_approval_denied_error, c as engine_config_error, d as model_required_error, f as on_chunk_error, g as provider_not_configured_error, h as provider_error, l as engine_disposed_error, m as provider_capability_error, n as default_normalize_usage, p as provider_auth_error, s as claude_cli_error, u as incomplete_generation_error, v as rate_limit_error, x as tool_error, y as schema_validation_error } from "./leading_system-DQmlA6Fs.js";
5
+ import { _ as provider_required_error, b as tool_approval_denied_error, c as engine_config_error, d as model_required_error, f as on_chunk_error, g as provider_not_configured_error, h as provider_error, l as engine_disposed_error, m as provider_capability_error, n as default_normalize_usage, p as provider_auth_error, s as claude_cli_error, u as incomplete_generation_error, v as rate_limit_error, x as tool_error, y as schema_validation_error } from "./leading_system-B6hsYN90.js";
6
6
  import { createHash } from "node:crypto";
7
7
  import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
8
8
  import { dirname, join } from "node:path";
@@ -1930,6 +1930,33 @@ function throughput(source) {
1930
1930
  };
1931
1931
  }
1932
1932
  //#endregion
1933
+ //#region src/engine/providers/claude_cli/reported.ts
1934
+ /**
1935
+ * Read the claude CLI's reported run detail off anything carrying
1936
+ * `provider_reported`: a `GenerateResult`, a `StepRecord`, or an
1937
+ * `incomplete_generation_error`.
1938
+ *
1939
+ * Returns undefined when the source has no `claude_cli` entry, or when the
1940
+ * entry lacks a string `session_id` and a numeric `duration_ms`.
1941
+ * `duration_api_ms` carries through only when it is a number.
1942
+ */
1943
+ function claude_cli_reported(source) {
1944
+ const entry = source.provider_reported?.["claude_cli"];
1945
+ if (typeof entry !== "object" || entry === null) return void 0;
1946
+ const session_id = Reflect.get(entry, "session_id");
1947
+ const duration_ms = Reflect.get(entry, "duration_ms");
1948
+ if (typeof session_id !== "string" || typeof duration_ms !== "number") return void 0;
1949
+ const duration_api_ms = Reflect.get(entry, "duration_api_ms");
1950
+ return typeof duration_api_ms === "number" ? {
1951
+ session_id,
1952
+ duration_ms,
1953
+ duration_api_ms
1954
+ } : {
1955
+ session_id,
1956
+ duration_ms
1957
+ };
1958
+ }
1959
+ //#endregion
1933
1960
  //#region src/model_call.ts
1934
1961
  /**
1935
1962
  * model_call: the single sanctioned bridge between the composition and
@@ -1942,8 +1969,10 @@ function throughput(source) {
1942
1969
  * The returned Step auto-threads ctx.abort, ctx.trajectory, and, only when
1943
1970
  * run.stream is driving, an on_chunk forwarder that records each chunk as a
1944
1971
  * `model_chunk` trajectory event. Callers cannot override these: the
1945
- * composition layer owns cancellation and trajectory plumbing. Cost events
1946
- * flow out via ctx.trajectory per the engine's own emission rules.
1972
+ * composition layer owns cancellation and trajectory plumbing. A caller's own
1973
+ * `on_chunk` is an observer called beside the forwarder, never in place of
1974
+ * it. Cost events flow out via ctx.trajectory per the engine's own emission
1975
+ * rules.
1947
1976
  */
1948
1977
  /**
1949
1978
  * Wrap the run's trajectory so the engine's own spans (engine.generate and its
@@ -2052,7 +2081,8 @@ function build_generate_options(cfg, prompt, ctx) {
2052
2081
  *
2053
2082
  * Threads `ctx.abort` and `ctx.trajectory` (nested under the model_call
2054
2083
  * step's own span) into every call, and, when `run.stream` is driving,
2055
- * records each chunk as a `model_chunk` trajectory event. `cfg.project`
2084
+ * records each chunk as a `model_chunk` trajectory event before handing it
2085
+ * to `cfg.on_chunk`. `cfg.project`
2056
2086
  * maps the `GenerateResult` envelope into the step's output inside the same
2057
2087
  * step; omitted, the envelope is the output.
2058
2088
  */
@@ -2094,13 +2124,16 @@ function model_call(cfg) {
2094
2124
  text: input
2095
2125
  }]
2096
2126
  }] : [...input], ctx);
2127
+ const observer = cfg.on_chunk;
2097
2128
  if (ctx.streaming) opts.on_chunk = (chunk) => {
2098
2129
  ctx.trajectory.record({
2099
2130
  kind: "model_chunk",
2100
2131
  step_id,
2101
2132
  chunk
2102
2133
  });
2134
+ return observer?.(chunk);
2103
2135
  };
2136
+ else if (observer !== void 0) opts.on_chunk = observer;
2104
2137
  return project(await cfg.engine.generate(opts));
2105
2138
  });
2106
2139
  return {
@@ -2171,6 +2204,6 @@ function forward_standard_env() {
2171
2204
  return out;
2172
2205
  }
2173
2206
  //#endregion
2174
- export { STEP_KINDS, aborted_error, adversarial, assert_valid_step_id, bench, bench_suspend_error, branch, chain, checkpoint, claude_cli_error, compose, consensus, create_engine, default_normalize_usage, describe, describe_cycle_error, engine_config_error, engine_disposed_error, ensemble, ensemble_step, error_path, fallback, flow_schema_default as flow_schema, forward_standard_env, gate, improve, incomplete_generation_error, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step, is_step_kind, is_valid_step_id, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_required_error, model_step, normalize_score, on_chunk_error, parallel, parse_trajectory_event, pipe, provider_auth_error, provider_capability_error, provider_error, provider_not_configured_error, provider_required_error, rate_limit_error, read_baseline, regression_compare, resolve_display_name, resume_validation_error, retry, run, schema_validation_error, scope, sequence, stash, step, suggest_step_id, suspend, suspended_error, throughput, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, use, write_baseline };
2207
+ export { STEP_KINDS, aborted_error, adversarial, assert_valid_step_id, bench, bench_suspend_error, branch, chain, checkpoint, claude_cli_error, claude_cli_reported, compose, consensus, create_engine, default_normalize_usage, describe, describe_cycle_error, engine_config_error, engine_disposed_error, ensemble, ensemble_step, error_path, fallback, flow_schema_default as flow_schema, forward_standard_env, gate, improve, incomplete_generation_error, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step, is_step_kind, is_valid_step_id, judge_equals, judge_llm, judge_with, learn, loop, map, model_call, model_required_error, model_step, normalize_score, on_chunk_error, parallel, parse_trajectory_event, pipe, provider_auth_error, provider_capability_error, provider_error, provider_not_configured_error, provider_required_error, rate_limit_error, read_baseline, regression_compare, resolve_display_name, resume_validation_error, retry, run, schema_validation_error, scope, sequence, stash, step, suggest_step_id, suspend, suspended_error, throughput, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, use, write_baseline };
2175
2208
 
2176
2209
  //# sourceMappingURL=index.js.map