fascicle 0.17.0 → 0.17.2

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 FlowValue, c as Step, d as StepMetadata, f as StepOptions, h as TrajectoryLogger, i as FlowNode, l as StepFn, m as TrajectoryEvent, n as CheckpointStore, o as RunContext, p as StepOutput, r as CleanupFn, s as ScopedCheckpointStore, t as AnyStep, u as StepInput } from "./types-CPqLZOEr.js";
2
2
  import { n as SchemaIssue, r as ToolSchema, t as AnySchema } from "./types-BK0UW28o.js";
3
3
  import { _ as is_run_end_event, a as MapItemFailedEvent, b as is_step_replayed_event, c as RunEndStatus, d as StepReplayedEvent, f as TrajectoryParseResult, g as is_map_item_failed_event, h as is_emit_event, i as EmitEvent, l as SpanEndEvent, m as is_custom_trajectory_event, n as CheckpointStatus, o as ParsedTrajectoryEvent, p as is_checkpoint_event, r as CustomTrajectoryEvent, s as RunEndEvent, t as CheckpointEvent, u as SpanStartEvent, v as is_span_end_event, x as parse_trajectory_event, y as is_span_start_event } from "./trajectory-BKGNxi7u.js";
4
- import { A as StepTiming, B as UserContentPart, C as ProviderConfigMap, D as RetryFailureKind, E as ResolvedModel, F as ToolCallRecord, G as ProviderAdapter, H as EffortTranslation, I as ToolExecContext, J as ProviderTransport, K as ProviderCapability, L as TurnRequest, M as Tool, N as ToolApprovalHandler, O as RetryPolicy, P as ToolApprovalRequest, R as TurnResult, S as PricingTable, T as ProviderOptions, U as ExternalAgentAdapter, V as AiSdkProviderAdapter, W as NativeProviderAdapter, X as default_normalize_usage, Y as RawProviderUsage, Z as ClaudeCliProviderReported, _ as Message, a as CacheSetting, b as PrepareStepResult, c as CostBreakdown, d as EngineConfig, f as EngineDefaults, g as GenerateTiming, h as GenerateResult, i as BedrockCredentials, j as StreamChunk, k as StepRecord, l as EffortLevel, m as GenerateOptions, n as AssistantContentPart, o as CaptureLevel, p as FinishReason, q as ProviderFactory, r as BedrockCredentialProvider, s as CapturePayload, t as AiSdkTelemetrySettings, u as Engine, v as PrepareStepContext, w as ProviderInit, x as Pricing, y as PrepareStepHook, z as UsageTotals } from "./types-BNgAUQP1.js";
4
+ import { A as StepTiming, B as UsageTotals, C as ProviderConfigMap, D as RetryFailureKind, E as ResolvedModel, F as ToolCallRecord, G as NativeProviderAdapter, H as AiSdkProviderAdapter, I as ToolExecContext, J as ProviderFactory, K as ProviderAdapter, L as TruncatedTurnPolicy, M as Tool, N as ToolApprovalHandler, O as RetryPolicy, P as ToolApprovalRequest, Q as ClaudeCliProviderReported, R as TurnRequest, S as PricingTable, T as ProviderOptions, U as EffortTranslation, V as UserContentPart, W as ExternalAgentAdapter, X as RawProviderUsage, Y as ProviderTransport, Z as default_normalize_usage, _ as Message, a as CacheSetting, b as PrepareStepResult, c as CostBreakdown, d as EngineConfig, f as EngineDefaults, g as GenerateTiming, h as GenerateResult, i as BedrockCredentials, j as StreamChunk, k as StepRecord, l as EffortLevel, m as GenerateOptions, n as AssistantContentPart, o as CaptureLevel, p as FinishReason, q as ProviderCapability, r as BedrockCredentialProvider, s as CapturePayload, t as AiSdkTelemetrySettings, u as Engine, v as PrepareStepContext, w as ProviderInit, x as Pricing, y as PrepareStepHook, z as TurnResult } from "./types-C7pO0jLq.js";
5
5
  //#region src/core/runner.d.ts
6
6
  type RunOptions = {
7
7
  readonly install_signal_handlers?: boolean;
@@ -575,6 +575,14 @@ type CheckpointConfig<i> = {
575
575
  * refers to a result that the store didn't keep.
576
576
  */
577
577
  readonly on_write_error?: 'record' | 'fail';
578
+ /**
579
+ * What a failed `store.get` does. `'miss'` (the default) records a
580
+ * `read_error` event and runs `inner`, as today. `'fail'` records the same
581
+ * event and then throws the store's error, which is what a checkpoint
582
+ * whose result a `suspend` hands to an approver wants, so a resume never
583
+ * runs `inner` again and passes the new result through.
584
+ */
585
+ readonly on_read_error?: 'miss' | 'fail';
578
586
  };
579
587
  /**
580
588
  * Wrap `inner` with persist-and-resume behavior keyed by `config.key`.
@@ -587,6 +595,20 @@ type CheckpointConfig<i> = {
587
595
  */
588
596
  export declare function checkpoint<i, o>(inner: Step<i, o>, config: CheckpointConfig<i>): Step<i, o>;
589
597
  //#endregion
598
+ //#region src/core/suspend_ids.d.ts
599
+ /**
600
+ * A test of whether a later input is the same as `first`, which a resume
601
+ * datum taken for `first` answers as well.
602
+ *
603
+ * `first` is snapshotted now, as stable JSON with its keys sorted, and a
604
+ * later input matches when its stable JSON is the same, so a `retry` that
605
+ * reaches a step again on a copy of its input passes, while an object that
606
+ * a `loop` changed in place since doesn't, since the datum answered what the
607
+ * object held then. When JSON can't hold `first`, a later input matches
608
+ * only when it's the same value by `Object.is`.
609
+ */
610
+ export declare function same_input_as(first: unknown): (next: unknown) => boolean;
611
+ //#endregion
590
612
  //#region src/core/suspend.d.ts
591
613
  type SuspendConfig<i, o, resume> = {
592
614
  readonly id: string;
@@ -726,6 +748,26 @@ export declare class flow_changed_error extends Error {
726
748
  readonly continued_on: string;
727
749
  constructor(run_id: string, started_on: string, continued_on: string);
728
750
  }
751
+ export declare class gate_result_error extends Error {
752
+ readonly kind: 'gate_result_error';
753
+ readonly path?: ReadonlyArray<string>;
754
+ readonly suspend_id: string;
755
+ readonly reason: 'read_error' | 'missing' | 'no_store';
756
+ constructor(suspend_id: string, reason: gate_result_error['reason'], cause?: unknown);
757
+ }
758
+ type DuplicateSuspendIdDetail = {
759
+ readonly paths?: ReadonlyArray<ReadonlyArray<string>>;
760
+ readonly labels?: ReadonlyArray<string>;
761
+ readonly at_branch?: boolean;
762
+ };
763
+ export declare class duplicate_suspend_id_error extends Error {
764
+ readonly kind: 'duplicate_suspend_id_error';
765
+ readonly path?: ReadonlyArray<string>;
766
+ readonly suspend_id: string;
767
+ readonly reason: 'declared_twice' | 'reached_twice';
768
+ readonly paths: ReadonlyArray<ReadonlyArray<string>>;
769
+ constructor(suspend_id: string, reason: duplicate_suspend_id_error['reason'], detail?: DuplicateSuspendIdDetail);
770
+ }
729
771
  export declare class run_not_found_error extends Error {
730
772
  readonly kind: 'run_not_found_error';
731
773
  readonly path?: ReadonlyArray<string>;
@@ -1494,6 +1536,10 @@ export declare const flow_schema: {
1494
1536
  type: string;
1495
1537
  enum: string[];
1496
1538
  };
1539
+ on_read_error: {
1540
+ type: string;
1541
+ enum: string[];
1542
+ };
1497
1543
  };
1498
1544
  };
1499
1545
  suspend_config: {
@@ -2121,9 +2167,11 @@ type GateConfig<o> = {
2121
2167
  * Build a Step that runs `inner`, checkpoints its result at `gate:<id>`, and
2122
2168
  * suspends with that result as the payload awaiting approval.
2123
2169
  *
2124
- * On resume (any defined resume value) the gate resolves to the inner result
2125
- * unchanged; the decision itself is discarded. On a re-run against the same
2126
- * store, the checkpoint absorbs the replay so `inner` never re-executes.
2170
+ * On resume (any defined resume value) the gate resolves to the stored inner
2171
+ * result unchanged; the decision itself is discarded. A resume that can't
2172
+ * serve the stored result throws `gate_result_error` rather than run `inner`
2173
+ * again. On a re-run against the same store, the checkpoint absorbs the
2174
+ * replay so `inner` never re-executes.
2127
2175
  * Throws at construction time when `inner` is anonymous, because the cached
2128
2176
  * result must map back to a stable step, and when `config.id` isn't an
2129
2177
  * identifier, which it checks under its own name before its `suspend` sees
@@ -2132,7 +2180,8 @@ type GateConfig<o> = {
2132
2180
  * Implemented as a `compose`d `scope`: the checkpointed result is stashed,
2133
2181
  * projected into the approver's view, and handed to `suspend`; the suspend's
2134
2182
  * `combine` returns a `use` step that restores the stashed result, which is
2135
- * how the decision stays signal-only.
2183
+ * how the decision stays signal-only. The checkpoint keeps its node and runs
2184
+ * through `resume_aware`, which is how a resume never runs `inner`.
2136
2185
  */
2137
2186
  export declare function gate<i, o>(inner: Step<i, o>, config: GateConfig<o>): Step<i, o>;
2138
2187
  //#endregion
@@ -2525,6 +2574,12 @@ type ModelCallConfig<T = string, projected = GenerateResult<T>> = {
2525
2574
  readonly schema_repair_attempts?: number;
2526
2575
  readonly tool_call_repair_attempts?: number;
2527
2576
  readonly max_tool_calls_per_step?: number;
2577
+ /**
2578
+ * What the loop does with a turn that reached its output limit before it
2579
+ * made a tool call, forwarded to the engine. See
2580
+ * `GenerateOptions.truncated_turn_policy`.
2581
+ */
2582
+ readonly truncated_turn_policy?: TruncatedTurnPolicy;
2528
2583
  readonly on_tool_approval?: ToolApprovalHandler;
2529
2584
  /**
2530
2585
  * Observe every chunk of the call as it streams, for a live renderer that
@@ -2587,5 +2642,5 @@ export declare function model_step<T = string>(cfg: Omit<ModelCallConfig<T>, 'pr
2587
2642
  */
2588
2643
  export declare function forward_standard_env(): Record<string, string>;
2589
2644
  //#endregion
2590
- export { type AdversarialBuildInput, type AdversarialConfig, type AdversarialCritiqueResult, type AdversarialResult, type AiSdkProviderAdapter, type AiSdkTelemetrySettings, type AnySchema, type AnyStep, type AssistantContentPart, type BedrockCredentialProvider, type BedrockCredentials, type BenchCase, type BenchOptions, type BenchReport, type BenchSummary, type BracketRecord, type BranchConfig, type CacheSetting, type Candidate, type CaptureLevel, type CapturePayload, type CapturedSettings, type CapturedTool, type CapturedTurn, 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 DiagramOptions, type DurableConfig, type DurableOutcome, type DurableRunOptions, type DurableRunState, type DurableRuns, type DurableStore, 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 MapItemFailedEvent, type MapSettleConfig, 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 ProviderOptions, type ProviderTransport, type RawProviderUsage, type RegressionCompareOptions, type RegressionDelta, type RegressionReport, type ReplayHint, type ResolvedModel, type RetryConfig, type RetryFailureKind, type RetryOutcome, type RetryPolicy, type RetryProjection, type RunContext, type RunEndEvent, type RunEndStatus, type RunOptions, type RunOutcome, type SchemaIssue, type ScopeOptions, type ScopedCheckpointStore, type Score, type ScoredCandidate, type SequenceOptions, type Settled, type SettledError, type SpanEndEvent, type SpanStartEvent, type StashOptions, type Step, type StepFn, type StepInput, type StepKind, type StepMetadata, type StepOptions, type StepOutput, type StepRecord, type StepReplayedEvent, 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, default_normalize_usage, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_map_item_failed_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step_replayed_event, parse_trajectory_event };
2645
+ export { type AdversarialBuildInput, type AdversarialConfig, type AdversarialCritiqueResult, type AdversarialResult, type AiSdkProviderAdapter, type AiSdkTelemetrySettings, type AnySchema, type AnyStep, type AssistantContentPart, type BedrockCredentialProvider, type BedrockCredentials, type BenchCase, type BenchOptions, type BenchReport, type BenchSummary, type BracketRecord, type BranchConfig, type CacheSetting, type Candidate, type CaptureLevel, type CapturePayload, type CapturedSettings, type CapturedTool, type CapturedTurn, 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 DiagramOptions, type DurableConfig, type DurableOutcome, type DurableRunOptions, type DurableRunState, type DurableRuns, type DurableStore, 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 MapItemFailedEvent, type MapSettleConfig, 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 ProviderOptions, type ProviderTransport, type RawProviderUsage, type RegressionCompareOptions, type RegressionDelta, type RegressionReport, type ReplayHint, type ResolvedModel, type RetryConfig, type RetryFailureKind, type RetryOutcome, type RetryPolicy, type RetryProjection, type RunContext, type RunEndEvent, type RunEndStatus, type RunOptions, type RunOutcome, type SchemaIssue, type ScopeOptions, type ScopedCheckpointStore, type Score, type ScoredCandidate, type SequenceOptions, type Settled, type SettledError, type SpanEndEvent, type SpanStartEvent, type StashOptions, type Step, type StepFn, type StepInput, type StepKind, type StepMetadata, type StepOptions, type StepOutput, type StepRecord, type StepReplayedEvent, 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 TruncatedTurnPolicy, type TurnRequest, type TurnResult, type UsageTotals, type UseOptions, type UserContentPart, default_normalize_usage, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_map_item_failed_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step_replayed_event, parse_trajectory_event };
2591
2646
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { A as describe_cycle_error, C as durable, D as describe, E as run, F as suspended_error, I as timeout_error, L as STEP_KINDS, M as flow_changed_error, N as resume_validation_error, O as is_step, P as run_not_found_error, R as is_step_kind, S as suggest_step_id, _ as parallel, a as suspend, b as assert_valid_step_id, c as loop, d as retry, g as branch, h as map, i as use, j as error_path, k as aborted_error, l as timeout, m as pipe, n as scope, o as checkpoint, r as stash, s as compose, t as chain, u as fallback, v as sequence, x as is_valid_step_id, y as step, z as resolve_display_name } from "./core-BOFcG3tp.js";
2
- import { t as create_engine } from "./engine-BMdRqWL2.js";
1
+ import { A as aborted_error, B as STEP_KINDS, C as durable, D as same_input_as, E as run, F as gate_result_error, H as resolve_display_name, I as resume_validation_error, L as run_not_found_error, M as duplicate_suspend_id_error, N as error_path, O as describe, P as flow_changed_error, R as suspended_error, S as suggest_step_id, V as is_step_kind, _ as parallel, a as suspend, b as assert_valid_step_id, c as loop, d as retry, g as branch, h as map, i as use, j as describe_cycle_error, k as is_step, l as timeout, m as pipe, n as scope, o as checkpoint, r as stash, s as compose, t as chain, u as fallback, v as sequence, x as is_valid_step_id, y as step, z as timeout_error } from "./core-Dwir3pkb.js";
2
+ import { t as create_engine } from "./engine-DPPqAVdZ.js";
3
3
  import { n as is_record$1 } from "./records-1HU7mWXf.js";
4
4
  import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
5
5
  import { a as is_run_end_event, c as is_step_replayed_event, i as is_map_item_failed_event, l as parse_trajectory_event, n as is_custom_trajectory_event, o as is_span_end_event, r as is_emit_event, s as is_span_start_event, t as is_checkpoint_event } from "./trajectory-DeURWIhj.js";
6
6
  import { a as http_logger, n as tee_logger, o as filesystem_logger } from "./adapters-CDUzZlby.js";
7
- import { A as tool_approval_denied_error, C as provider_auth_error, D as provider_required_error, E as provider_not_configured_error, M as turn_timeout_error, O as rate_limit_error, S as on_chunk_error, T as provider_error, _ as claude_cli_error, b as incomplete_generation_error, d as default_normalize_usage, j as tool_error, k as schema_validation_error, v as engine_config_error, w as provider_capability_error, x as model_required_error, y as engine_disposed_error } from "./leading_system-DmNxhvzL.js";
7
+ import { A as tool_approval_denied_error, C as provider_auth_error, D as provider_required_error, E as provider_not_configured_error, M as turn_timeout_error, O as rate_limit_error, S as on_chunk_error, T as provider_error, _ as claude_cli_error, b as incomplete_generation_error, d as default_normalize_usage, j as tool_error, k as schema_validation_error, v as engine_config_error, w as provider_capability_error, x as model_required_error, y as engine_disposed_error } from "./leading_system-DJvuhESU.js";
8
8
  import { createHash } from "node:crypto";
9
9
  import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
10
10
  import { dirname, join } from "node:path";
@@ -484,6 +484,10 @@ const flow_schema = {
484
484
  "on_write_error": {
485
485
  "type": "string",
486
486
  "enum": ["record", "fail"]
487
+ },
488
+ "on_read_error": {
489
+ "type": "string",
490
+ "enum": ["miss", "fail"]
487
491
  }
488
492
  }
489
493
  },
@@ -948,9 +952,15 @@ function ensemble_step(config) {
948
952
  * step must be named.
949
953
  * - A failed write fails the run: the checkpoint takes
950
954
  * `on_write_error: 'fail'`, so the run stops before it suspends rather than
951
- * ask for approval of a result that the store never kept, which a resume
952
- * would replace by running `inner` again. A hand-built checkpoint before a
953
- * `suspend` that shows its result should pass `'fail'` for the same reason.
955
+ * ask for approval of a result that the store never kept.
956
+ * - A resume serves the stored result or fails the run: it never runs
957
+ * `inner`, since a new result would pass through an approval that covered
958
+ * the old one. A store that fails the read, or no longer holds the result,
959
+ * fails the resume with `gate_result_error`. A failed read on a first run
960
+ * is still a miss, since nobody has approved anything yet. A hand-built
961
+ * checkpoint before a `suspend` that shows its result can't tell a first
962
+ * run from a resume, so it should pass `'fail'` for both `on_write_error`
963
+ * and `on_read_error`.
954
964
  * - Suspend payload: follows the library's suspend contract, which raises
955
965
  * `{ input }` on the `suspended_error`. Here that `input` is
956
966
  * `format(result)` when `format` is given and the raw result otherwise, so
@@ -964,10 +974,16 @@ function ensemble_step(config) {
964
974
  * flow that needs decision-dependent output (approve vs reject branches)
965
975
  * should use `suspend` directly, whose `combine` exists for exactly that.
966
976
  * - `store` is optional. Absent, the checkpoint falls back to the run's
967
- * `checkpoint_store`; with neither, the gate still suspends and resumes
968
- * in-process but a restart re-executes `inner`. Present, the gate-local
969
- * store wins over the run-level one, because an explicit argument beats
970
- * ambient configuration.
977
+ * `checkpoint_store`. With neither, the gate still suspends, but its resume
978
+ * fails with `gate_result_error`, since nothing holds the result it
979
+ * showed. Present, the gate-local store wins over the run-level one,
980
+ * because an explicit argument beats ambient configuration.
981
+ * - One run reaches a gate once per input: a second reach on another input,
982
+ * for the next item of a `map` or a later round of a `loop`, throws
983
+ * `duplicate_suspend_id_error` with `reason: 'reached_twice'` before it
984
+ * reads or writes the store, since the key is fixed per gate and the one
985
+ * stored result and the one decision answer the first input. A `retry`
986
+ * that reaches the gate again on the same input passes.
971
987
  * - The suspend's `on` hook is a noop: notification is the driver's job, and
972
988
  * `run.until_suspended` already hands it the payload to render.
973
989
  */
@@ -977,6 +993,99 @@ const approval_schema = { "~standard": {
977
993
  validate: (value) => ({ value })
978
994
  } };
979
995
  /**
996
+ * Whether the gate `id` is resuming: its id holds a defined value of its own
997
+ * in the run's resume data, which is exactly when its `suspend` passes. Only
998
+ * an own value counts, so a gate named like an `Object.prototype` member
999
+ * never mistakes the inherited member for a decision.
1000
+ */
1001
+ function is_resuming(ctx, id) {
1002
+ const resume_data = ctx.resume_data;
1003
+ return resume_data !== void 0 && Object.hasOwn(resume_data, id) && resume_data[id] !== void 0;
1004
+ }
1005
+ /**
1006
+ * A store that holds `value` and nothing else, so the checkpoint's own run
1007
+ * serves it as a hit. A hit never writes, so the writes go nowhere.
1008
+ */
1009
+ function holding(value) {
1010
+ return {
1011
+ get: async () => value,
1012
+ set: async () => {},
1013
+ delete: async () => {}
1014
+ };
1015
+ }
1016
+ /**
1017
+ * The gate's checkpoint, with a run that checks the gate's input and serves
1018
+ * a resumed gate from the store or fails the run.
1019
+ *
1020
+ * Before it reads or writes the store, on a first run as well as a resume,
1021
+ * the run checks its input: the first reach in a run keeps a test of its
1022
+ * input for that run, which the run's cleanup drops, and a later reach on
1023
+ * another input throws `duplicate_suspend_id_error` with
1024
+ * `reason: 'reached_twice'`. The key is fixed per gate, so a second input
1025
+ * would read or overwrite the first one's result, and the gate's `suspend`,
1026
+ * which always sees a view of that one result, can't tell.
1027
+ *
1028
+ * A gate that isn't resuming runs the checkpoint as built. A resumed one
1029
+ * reads the store itself, so it never runs `inner`: with no store, it throws
1030
+ * `gate_result_error` with `reason: 'no_store'` and records nothing; a read
1031
+ * that throws records the checkpoint's `read_error` event and throws
1032
+ * `reason: 'read_error'`; and a miss records `miss` and throws
1033
+ * `reason: 'missing'`. A hit goes to the checkpoint's own run over a store
1034
+ * that holds only that value, so the checkpoint records the hit and marks
1035
+ * the gates inside `inner` reached, as a hit always has. The node keeps its
1036
+ * kind, id, children, and config, so `describe` and a durable run's
1037
+ * fingerprint see the checkpoint they always have.
1038
+ */
1039
+ function resume_aware(checkpointed, id, key) {
1040
+ const first_inputs = /* @__PURE__ */ new Map();
1041
+ const run_fn = async (input, ctx) => {
1042
+ const same = first_inputs.get(ctx.run_id);
1043
+ if (same === void 0) {
1044
+ first_inputs.set(ctx.run_id, same_input_as(input));
1045
+ ctx.on_cleanup(() => {
1046
+ first_inputs.delete(ctx.run_id);
1047
+ });
1048
+ } else if (!same(input)) throw new duplicate_suspend_id_error(id, "reached_twice");
1049
+ if (!is_resuming(ctx, id)) return checkpointed.run(input, ctx);
1050
+ const store = ctx.checkpoint_store;
1051
+ if (store === void 0) throw new gate_result_error(id, "no_store");
1052
+ const meta = {
1053
+ id: checkpointed.id,
1054
+ key,
1055
+ span_id: ctx.parent_span_id
1056
+ };
1057
+ let value;
1058
+ try {
1059
+ value = await store.get(key);
1060
+ } catch (err) {
1061
+ const error = err instanceof Error ? err.message : String(err);
1062
+ ctx.trajectory.record({
1063
+ kind: "checkpoint",
1064
+ status: "read_error",
1065
+ error,
1066
+ ...meta
1067
+ });
1068
+ throw new gate_result_error(id, "read_error", err);
1069
+ }
1070
+ if (value === null || value === void 0) {
1071
+ ctx.trajectory.record({
1072
+ kind: "checkpoint",
1073
+ status: "miss",
1074
+ ...meta
1075
+ });
1076
+ throw new gate_result_error(id, "missing");
1077
+ }
1078
+ return checkpointed.run(input, {
1079
+ ...ctx,
1080
+ checkpoint_store: holding(value)
1081
+ });
1082
+ };
1083
+ return {
1084
+ ...checkpointed,
1085
+ run: run_fn
1086
+ };
1087
+ }
1088
+ /**
980
1089
  * Bind a gate-local store over the run context for the checkpoint beneath.
981
1090
  *
982
1091
  * `checkpoint` reads `ctx.checkpoint_store`, so scoping a store to one gate
@@ -1000,9 +1109,11 @@ function bind_store(persisted, store) {
1000
1109
  * Build a Step that runs `inner`, checkpoints its result at `gate:<id>`, and
1001
1110
  * suspends with that result as the payload awaiting approval.
1002
1111
  *
1003
- * On resume (any defined resume value) the gate resolves to the inner result
1004
- * unchanged; the decision itself is discarded. On a re-run against the same
1005
- * store, the checkpoint absorbs the replay so `inner` never re-executes.
1112
+ * On resume (any defined resume value) the gate resolves to the stored inner
1113
+ * result unchanged; the decision itself is discarded. A resume that can't
1114
+ * serve the stored result throws `gate_result_error` rather than run `inner`
1115
+ * again. On a re-run against the same store, the checkpoint absorbs the
1116
+ * replay so `inner` never re-executes.
1006
1117
  * Throws at construction time when `inner` is anonymous, because the cached
1007
1118
  * result must map back to a stable step, and when `config.id` isn't an
1008
1119
  * identifier, which it checks under its own name before its `suspend` sees
@@ -1011,16 +1122,18 @@ function bind_store(persisted, store) {
1011
1122
  * Implemented as a `compose`d `scope`: the checkpointed result is stashed,
1012
1123
  * projected into the approver's view, and handed to `suspend`; the suspend's
1013
1124
  * `combine` returns a `use` step that restores the stashed result, which is
1014
- * how the decision stays signal-only.
1125
+ * how the decision stays signal-only. The checkpoint keeps its node and runs
1126
+ * through `resume_aware`, which is how a resume never runs `inner`.
1015
1127
  */
1016
1128
  function gate(inner, config) {
1017
1129
  if (inner.anonymous === true) throw new Error("gate requires a named inner step, got anonymous — give the inner step an id with step('id', fn)");
1018
1130
  const { id, store, format } = config;
1019
1131
  assert_valid_step_id(id, "gate id", "put the label in name");
1020
- const checkpointed = checkpoint(inner, {
1021
- key: `gate:${id}`,
1132
+ const key = `gate:${id}`;
1133
+ const checkpointed = resume_aware(checkpoint(inner, {
1134
+ key,
1022
1135
  on_write_error: "fail"
1023
- });
1136
+ }), id, key);
1024
1137
  const persisted = store === void 0 ? checkpointed : bind_store(checkpointed, store);
1025
1138
  const restore = use(["result"], (vars) => {
1026
1139
  return vars["result"];
@@ -2643,6 +2756,7 @@ function build_generate_options(cfg, prompt, ctx) {
2643
2756
  assign_if_present(opts, "schema_repair_attempts", cfg.schema_repair_attempts);
2644
2757
  assign_if_present(opts, "tool_call_repair_attempts", cfg.tool_call_repair_attempts);
2645
2758
  assign_if_present(opts, "max_tool_calls_per_step", cfg.max_tool_calls_per_step);
2759
+ assign_if_present(opts, "truncated_turn_policy", cfg.truncated_turn_policy);
2646
2760
  assign_if_present(opts, "on_tool_approval", cfg.on_tool_approval);
2647
2761
  return opts;
2648
2762
  }
@@ -2776,6 +2890,6 @@ function forward_standard_env() {
2776
2890
  return out;
2777
2891
  }
2778
2892
  //#endregion
2779
- export { STEP_KINDS, aborted_error, adversarial, assert_valid_step_id, bench, bench_suspend_error, branch, captured_turns, chain, checkpoint, claude_cli_error, claude_cli_reported, compose, consensus, create_engine, default_normalize_usage, define_tool, describe, describe_cycle_error, durable, engine_config_error, engine_disposed_error, ensemble, ensemble_step, error_path, fallback, flow_changed_error, flow_schema, forward_standard_env, gate, improve, incomplete_generation_error, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_map_item_failed_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step, is_step_kind, is_step_replayed_event, 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, replay_turn, resolve_display_name, resume_validation_error, retry, run, run_not_found_error, schema_validation_error, scope, sequence, stash, step, suggest_step_id, suspend, suspended_error, throughput, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, turn_timeout_error, use, write_baseline };
2893
+ export { STEP_KINDS, aborted_error, adversarial, assert_valid_step_id, bench, bench_suspend_error, branch, captured_turns, chain, checkpoint, claude_cli_error, claude_cli_reported, compose, consensus, create_engine, default_normalize_usage, define_tool, describe, describe_cycle_error, duplicate_suspend_id_error, durable, engine_config_error, engine_disposed_error, ensemble, ensemble_step, error_path, fallback, flow_changed_error, flow_schema, forward_standard_env, gate, gate_result_error, improve, incomplete_generation_error, is_checkpoint_event, is_custom_trajectory_event, is_emit_event, is_map_item_failed_event, is_run_end_event, is_span_end_event, is_span_start_event, is_step, is_step_kind, is_step_replayed_event, 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, replay_turn, resolve_display_name, resume_validation_error, retry, run, run_not_found_error, same_input_as, schema_validation_error, scope, sequence, stash, step, suggest_step_id, suspend, suspended_error, throughput, timeout, timeout_error, tool_approval_denied_error, tool_error, tournament, turn_timeout_error, use, write_baseline };
2780
2894
 
2781
2895
  //# sourceMappingURL=index.js.map