fascicle 0.17.4 → 0.17.5
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 +21 -0
- package/dist/AGENTS.md +9 -8
- package/dist/{engine-CbVdzplI.js → engine-BTijBDlY.js} +194 -51
- package/dist/engine-BTijBDlY.js.map +1 -0
- package/dist/index.d.ts +149 -147
- package/dist/index.js +2 -2
- package/dist/{invoke-x5SNh9DV.js → invoke-DnmWf8gE.js} +2 -2
- package/dist/{invoke-x5SNh9DV.js.map → invoke-DnmWf8gE.js.map} +1 -1
- package/dist/{leading_system-C23TJ9OQ.js → leading_system-CHSYz0h9.js} +168 -19
- package/dist/leading_system-CHSYz0h9.js.map +1 -0
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/dist/engine-CbVdzplI.js.map +0 -1
- package/dist/leading_system-C23TJ9OQ.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1701,152 +1701,6 @@ export declare const flow_schema: {
|
|
|
1701
1701
|
};
|
|
1702
1702
|
};
|
|
1703
1703
|
//#endregion
|
|
1704
|
-
//#region src/engine/create_engine.d.ts
|
|
1705
|
-
/**
|
|
1706
|
-
* Validate `config` and construct an `Engine`.
|
|
1707
|
-
*
|
|
1708
|
-
* Provider entries are validated synchronously via `build_provider_adapters`.
|
|
1709
|
-
* A `generate` call that names a provider absent from `config.providers`
|
|
1710
|
-
* still throws `provider_not_configured_error`, but only at call time.
|
|
1711
|
-
*/
|
|
1712
|
-
export declare function create_engine(config: EngineConfig): Engine;
|
|
1713
|
-
//#endregion
|
|
1714
|
-
//#region src/engine/define_tool.d.ts
|
|
1715
|
-
/**
|
|
1716
|
-
* Define a tool whose `execute` and `needs_approval` receive the input type
|
|
1717
|
-
* `input_schema` validates to, and return it as a plain `Tool` that any
|
|
1718
|
-
* `tools` list accepts. The widening is the one cast, and it is sound because
|
|
1719
|
-
* the tool loop validates every call's input against `input_schema` and
|
|
1720
|
-
* passes `execute` and `needs_approval` the validated value, never the raw
|
|
1721
|
-
* one; a call that fails validation goes back to the model as a tool error
|
|
1722
|
-
* and never reaches the tool. The spec comes back as the same object.
|
|
1723
|
-
*/
|
|
1724
|
-
export declare function define_tool<i, o>(spec: Tool<i, o>): Tool;
|
|
1725
|
-
//#endregion
|
|
1726
|
-
//#region src/engine/throughput.d.ts
|
|
1727
|
-
type Throughput = {
|
|
1728
|
-
/** Output tokens per second over the measured window. Not rounded. */
|
|
1729
|
-
tokens_per_second: number;
|
|
1730
|
-
/**
|
|
1731
|
-
* 'decode' when every contributing window is time the model spent emitting
|
|
1732
|
-
* output, either a decode time the provider reported or a streamed turn's
|
|
1733
|
-
* window after its first chunk; 'blended' when any window is a whole
|
|
1734
|
-
* round-trip (network + queueing + prefill included).
|
|
1735
|
-
*/
|
|
1736
|
-
basis: 'decode' | 'blended';
|
|
1737
|
-
/** Output tokens summed across the contributing steps. */
|
|
1738
|
-
output_tokens: number;
|
|
1739
|
-
/** The measured window in ms, summed across the contributing steps. */
|
|
1740
|
-
measured_ms: number;
|
|
1741
|
-
};
|
|
1742
|
-
/**
|
|
1743
|
-
* Compute output throughput from step timing: a whole GenerateResult, a step
|
|
1744
|
-
* array, or a single step.
|
|
1745
|
-
*
|
|
1746
|
-
* Tool-execution time between turns never contributes, since StepTiming
|
|
1747
|
-
* brackets the provider round-trip alone. Each step's window is the decode
|
|
1748
|
-
* time its provider reported when it has one (Ollama's `eval_duration`),
|
|
1749
|
-
* else `duration_ms - first_chunk_ms` when the turn streamed, unless its
|
|
1750
|
-
* first chunk was a tool call that arrived whole, else the full
|
|
1751
|
-
* `duration_ms`, with `basis` reporting 'decode' only when no blended window
|
|
1752
|
-
* contributed. Returns undefined when nothing is measurable: no step has
|
|
1753
|
-
* timing or a reported decode time (an external adapter, a test seam), or the
|
|
1754
|
-
* summed window is 0 ms (a sub-millisecond stub turn), where a rate would
|
|
1755
|
-
* divide by zero.
|
|
1756
|
-
*/
|
|
1757
|
-
export declare function throughput(source: GenerateResult<unknown> | StepRecord | ReadonlyArray<StepRecord>): Throughput | undefined;
|
|
1758
|
-
//#endregion
|
|
1759
|
-
//#region src/engine/replay.d.ts
|
|
1760
|
-
/**
|
|
1761
|
-
* A captured call's settings: the provider and model, the resolved effort and
|
|
1762
|
-
* cache, the sampling knobs it set, its provider options as the engine
|
|
1763
|
-
* defaults and the call merged them, before an adapter's translation, and its
|
|
1764
|
-
* schema as JSON Schema.
|
|
1765
|
-
*/
|
|
1766
|
-
type CapturedSettings = {
|
|
1767
|
-
readonly provider: string;
|
|
1768
|
-
readonly model_id: string;
|
|
1769
|
-
readonly effort: EffortLevel;
|
|
1770
|
-
readonly cache?: Exclude<CacheSetting, 'off'>;
|
|
1771
|
-
readonly temperature?: number;
|
|
1772
|
-
readonly max_tokens?: number;
|
|
1773
|
-
readonly top_p?: number;
|
|
1774
|
-
readonly provider_options?: Readonly<Record<string, unknown>>;
|
|
1775
|
-
readonly schema?: Readonly<Record<string, unknown>>;
|
|
1776
|
-
};
|
|
1777
|
-
/**
|
|
1778
|
-
* A captured tool: its name, its description, and its input schema as JSON
|
|
1779
|
-
* Schema (draft 2020-12), absent when the schema couldn't be written as one.
|
|
1780
|
-
*/
|
|
1781
|
-
type CapturedTool = {
|
|
1782
|
-
readonly name: string;
|
|
1783
|
-
readonly description: string;
|
|
1784
|
-
readonly input_schema?: Readonly<Record<string, unknown>>;
|
|
1785
|
-
};
|
|
1786
|
-
/**
|
|
1787
|
-
* One turn as it was sent: the call it belongs to, its step, the call's
|
|
1788
|
-
* settings and tools, the whole message array, system prompts included, and
|
|
1789
|
-
* the parts the provider returned when the trajectory holds them.
|
|
1790
|
-
*/
|
|
1791
|
-
type CapturedTurn = {
|
|
1792
|
-
readonly call_span_id: string;
|
|
1793
|
-
readonly step_index: number;
|
|
1794
|
-
readonly settings: CapturedSettings;
|
|
1795
|
-
readonly tools: ReadonlyArray<CapturedTool>;
|
|
1796
|
-
readonly messages: ReadonlyArray<Message>;
|
|
1797
|
-
readonly response?: ReadonlyArray<AssistantContentPart>;
|
|
1798
|
-
};
|
|
1799
|
-
/**
|
|
1800
|
-
* Rebuild every captured turn in a trajectory's events, in any order the
|
|
1801
|
-
* events arrive. Each call's turns are folded by `call_span_id` and ordered
|
|
1802
|
-
* by `step_index`, a delta is applied only on top of the turn at the step
|
|
1803
|
-
* just before it, and a turn's `response` is the `response_received.content`
|
|
1804
|
-
* that shares its step span. A turn whose request is missing or unreadable
|
|
1805
|
-
* (absent, `null`, or a string a redactor returned) is left out, and the call
|
|
1806
|
-
* picks up again at its next whole array. A call whose first turn is missing,
|
|
1807
|
-
* as in a truncated log, is left out whole. Calls come out in the order each
|
|
1808
|
-
* first appears in the events.
|
|
1809
|
-
*/
|
|
1810
|
-
export declare function captured_turns(events: Iterable<TrajectoryEvent>): CapturedTurn[];
|
|
1811
|
-
/**
|
|
1812
|
-
* Send one captured turn again, as one turn that can't act: the turn's
|
|
1813
|
-
* messages, settings, and tools through `engine.generate` with
|
|
1814
|
-
* `max_steps: 1`, `cache: 'off'`, `capture: 'off'`, and `system: ''`, so the
|
|
1815
|
-
* engine's default system prompt doesn't add a second one. The captured
|
|
1816
|
-
* schema stays behind, so the reply comes back raw. Each tool is rebuilt
|
|
1817
|
-
* with an `execute` that throws, and a model that calls one comes back with
|
|
1818
|
-
* the call listed and unexecuted (`finish_reason: 'max_steps'`). The
|
|
1819
|
-
* captured `provider_options` go as they were, a raw `cache_control`
|
|
1820
|
-
* included, and the replaying engine's defaults fill whatever the turn left
|
|
1821
|
-
* unset. `edit` changes the turn before it goes, and `provider` and `model`
|
|
1822
|
-
* send it elsewhere. A replay is inert only on the `ai_sdk` and native
|
|
1823
|
-
* transports, since an external provider runs its own loop and tools.
|
|
1824
|
-
*/
|
|
1825
|
-
export declare function replay_turn(engine: Engine, turn: CapturedTurn, options?: {
|
|
1826
|
-
/** Change the turn before it goes (drop a raw `cache_control`, reword a message). */
|
|
1827
|
-
readonly edit?: (turn: CapturedTurn) => CapturedTurn;
|
|
1828
|
-
/** Send it to this provider instead of the one it was captured on. */
|
|
1829
|
-
readonly provider?: string;
|
|
1830
|
-
/** Send it to this model instead of the one it was captured on. */
|
|
1831
|
-
readonly model?: string;
|
|
1832
|
-
/** Where the replay records its own events. */
|
|
1833
|
-
readonly trajectory?: TrajectoryLogger;
|
|
1834
|
-
}): Promise<GenerateResult>;
|
|
1835
|
-
//#endregion
|
|
1836
|
-
//#region src/engine/providers/claude_cli/reported.d.ts
|
|
1837
|
-
/**
|
|
1838
|
-
* Read the claude CLI's reported run detail off anything carrying
|
|
1839
|
-
* `provider_reported`: a `GenerateResult`, a `StepRecord`, or an
|
|
1840
|
-
* `incomplete_generation_error`.
|
|
1841
|
-
*
|
|
1842
|
-
* Returns undefined when the source has no `claude_cli` entry, or when the
|
|
1843
|
-
* entry lacks a string `session_id` and a numeric `duration_ms`.
|
|
1844
|
-
* `duration_api_ms` carries through only when it is a number.
|
|
1845
|
-
*/
|
|
1846
|
-
export declare function claude_cli_reported(source: {
|
|
1847
|
-
readonly provider_reported?: Readonly<Record<string, unknown>>;
|
|
1848
|
-
}): ClaudeCliProviderReported | undefined;
|
|
1849
|
-
//#endregion
|
|
1850
1704
|
//#region src/engine/errors.d.ts
|
|
1851
1705
|
export declare class rate_limit_error extends Error {
|
|
1852
1706
|
readonly kind: 'rate_limit_error';
|
|
@@ -1872,7 +1726,7 @@ export declare class provider_error extends Error {
|
|
|
1872
1726
|
readonly cause: unknown;
|
|
1873
1727
|
constructor(message: string, metadata?: {
|
|
1874
1728
|
status?: number;
|
|
1875
|
-
body?: string;
|
|
1729
|
+
body?: string | undefined;
|
|
1876
1730
|
cause_kind?: 'provider_5xx' | 'network' | 'unknown';
|
|
1877
1731
|
attempts?: number;
|
|
1878
1732
|
cause?: unknown;
|
|
@@ -1997,8 +1851,10 @@ export declare class provider_auth_error extends Error {
|
|
|
1997
1851
|
readonly path?: ReadonlyArray<string>;
|
|
1998
1852
|
readonly provider: string;
|
|
1999
1853
|
readonly refresh_command: string | undefined;
|
|
1854
|
+
readonly cause: unknown;
|
|
2000
1855
|
constructor(provider: string, message: string, metadata?: {
|
|
2001
1856
|
refresh_command?: string;
|
|
1857
|
+
cause?: unknown;
|
|
2002
1858
|
});
|
|
2003
1859
|
}
|
|
2004
1860
|
/**
|
|
@@ -2019,6 +1875,152 @@ export declare class incomplete_generation_error extends Error {
|
|
|
2019
1875
|
constructor(finish_reason: FinishReason, raw_text: string, provider_reported?: Record<string, unknown>);
|
|
2020
1876
|
}
|
|
2021
1877
|
//#endregion
|
|
1878
|
+
//#region src/engine/create_engine.d.ts
|
|
1879
|
+
/**
|
|
1880
|
+
* Validate `config` and construct an `Engine`.
|
|
1881
|
+
*
|
|
1882
|
+
* Provider entries are validated synchronously via `build_provider_adapters`.
|
|
1883
|
+
* A `generate` call that names a provider absent from `config.providers`
|
|
1884
|
+
* still throws `provider_not_configured_error`, but only at call time.
|
|
1885
|
+
*/
|
|
1886
|
+
export declare function create_engine(config: EngineConfig): Engine;
|
|
1887
|
+
//#endregion
|
|
1888
|
+
//#region src/engine/define_tool.d.ts
|
|
1889
|
+
/**
|
|
1890
|
+
* Define a tool whose `execute` and `needs_approval` receive the input type
|
|
1891
|
+
* `input_schema` validates to, and return it as a plain `Tool` that any
|
|
1892
|
+
* `tools` list accepts. The widening is the one cast, and it is sound because
|
|
1893
|
+
* the tool loop validates every call's input against `input_schema` and
|
|
1894
|
+
* passes `execute` and `needs_approval` the validated value, never the raw
|
|
1895
|
+
* one; a call that fails validation goes back to the model as a tool error
|
|
1896
|
+
* and never reaches the tool. The spec comes back as the same object.
|
|
1897
|
+
*/
|
|
1898
|
+
export declare function define_tool<i, o>(spec: Tool<i, o>): Tool;
|
|
1899
|
+
//#endregion
|
|
1900
|
+
//#region src/engine/throughput.d.ts
|
|
1901
|
+
type Throughput = {
|
|
1902
|
+
/** Output tokens per second over the measured window. Not rounded. */
|
|
1903
|
+
tokens_per_second: number;
|
|
1904
|
+
/**
|
|
1905
|
+
* 'decode' when every contributing window is time the model spent emitting
|
|
1906
|
+
* output, either a decode time the provider reported or a streamed turn's
|
|
1907
|
+
* window after its first chunk; 'blended' when any window is a whole
|
|
1908
|
+
* round-trip (network + queueing + prefill included).
|
|
1909
|
+
*/
|
|
1910
|
+
basis: 'decode' | 'blended';
|
|
1911
|
+
/** Output tokens summed across the contributing steps. */
|
|
1912
|
+
output_tokens: number;
|
|
1913
|
+
/** The measured window in ms, summed across the contributing steps. */
|
|
1914
|
+
measured_ms: number;
|
|
1915
|
+
};
|
|
1916
|
+
/**
|
|
1917
|
+
* Compute output throughput from step timing: a whole GenerateResult, a step
|
|
1918
|
+
* array, or a single step.
|
|
1919
|
+
*
|
|
1920
|
+
* Tool-execution time between turns never contributes, since StepTiming
|
|
1921
|
+
* brackets the provider round-trip alone. Each step's window is the decode
|
|
1922
|
+
* time its provider reported when it has one (Ollama's `eval_duration`),
|
|
1923
|
+
* else `duration_ms - first_chunk_ms` when the turn streamed, unless its
|
|
1924
|
+
* first chunk was a tool call that arrived whole, else the full
|
|
1925
|
+
* `duration_ms`, with `basis` reporting 'decode' only when no blended window
|
|
1926
|
+
* contributed. Returns undefined when nothing is measurable: no step has
|
|
1927
|
+
* timing or a reported decode time (an external adapter, a test seam), or the
|
|
1928
|
+
* summed window is 0 ms (a sub-millisecond stub turn), where a rate would
|
|
1929
|
+
* divide by zero.
|
|
1930
|
+
*/
|
|
1931
|
+
export declare function throughput(source: GenerateResult<unknown> | StepRecord | ReadonlyArray<StepRecord>): Throughput | undefined;
|
|
1932
|
+
//#endregion
|
|
1933
|
+
//#region src/engine/replay.d.ts
|
|
1934
|
+
/**
|
|
1935
|
+
* A captured call's settings: the provider and model, the resolved effort and
|
|
1936
|
+
* cache, the sampling knobs it set, its provider options as the engine
|
|
1937
|
+
* defaults and the call merged them, before an adapter's translation, and its
|
|
1938
|
+
* schema as JSON Schema.
|
|
1939
|
+
*/
|
|
1940
|
+
type CapturedSettings = {
|
|
1941
|
+
readonly provider: string;
|
|
1942
|
+
readonly model_id: string;
|
|
1943
|
+
readonly effort: EffortLevel;
|
|
1944
|
+
readonly cache?: Exclude<CacheSetting, 'off'>;
|
|
1945
|
+
readonly temperature?: number;
|
|
1946
|
+
readonly max_tokens?: number;
|
|
1947
|
+
readonly top_p?: number;
|
|
1948
|
+
readonly provider_options?: Readonly<Record<string, unknown>>;
|
|
1949
|
+
readonly schema?: Readonly<Record<string, unknown>>;
|
|
1950
|
+
};
|
|
1951
|
+
/**
|
|
1952
|
+
* A captured tool: its name, its description, and its input schema as JSON
|
|
1953
|
+
* Schema (draft 2020-12), absent when the schema couldn't be written as one.
|
|
1954
|
+
*/
|
|
1955
|
+
type CapturedTool = {
|
|
1956
|
+
readonly name: string;
|
|
1957
|
+
readonly description: string;
|
|
1958
|
+
readonly input_schema?: Readonly<Record<string, unknown>>;
|
|
1959
|
+
};
|
|
1960
|
+
/**
|
|
1961
|
+
* One turn as it was sent: the call it belongs to, its step, the call's
|
|
1962
|
+
* settings and tools, the whole message array, system prompts included, and
|
|
1963
|
+
* the parts the provider returned when the trajectory holds them.
|
|
1964
|
+
*/
|
|
1965
|
+
type CapturedTurn = {
|
|
1966
|
+
readonly call_span_id: string;
|
|
1967
|
+
readonly step_index: number;
|
|
1968
|
+
readonly settings: CapturedSettings;
|
|
1969
|
+
readonly tools: ReadonlyArray<CapturedTool>;
|
|
1970
|
+
readonly messages: ReadonlyArray<Message>;
|
|
1971
|
+
readonly response?: ReadonlyArray<AssistantContentPart>;
|
|
1972
|
+
};
|
|
1973
|
+
/**
|
|
1974
|
+
* Rebuild every captured turn in a trajectory's events, in any order the
|
|
1975
|
+
* events arrive. Each call's turns are folded by `call_span_id` and ordered
|
|
1976
|
+
* by `step_index`, a delta is applied only on top of the turn at the step
|
|
1977
|
+
* just before it, and a turn's `response` is the `response_received.content`
|
|
1978
|
+
* that shares its step span. A turn whose request is missing or unreadable
|
|
1979
|
+
* (absent, `null`, or a string a redactor returned) is left out, and the call
|
|
1980
|
+
* picks up again at its next whole array. A call whose first turn is missing,
|
|
1981
|
+
* as in a truncated log, is left out whole. Calls come out in the order each
|
|
1982
|
+
* first appears in the events.
|
|
1983
|
+
*/
|
|
1984
|
+
export declare function captured_turns(events: Iterable<TrajectoryEvent>): CapturedTurn[];
|
|
1985
|
+
/**
|
|
1986
|
+
* Send one captured turn again, as one turn that can't act: the turn's
|
|
1987
|
+
* messages, settings, and tools through `engine.generate` with
|
|
1988
|
+
* `max_steps: 1`, `cache: 'off'`, `capture: 'off'`, and `system: ''`, so the
|
|
1989
|
+
* engine's default system prompt doesn't add a second one. The captured
|
|
1990
|
+
* schema stays behind, so the reply comes back raw. Each tool is rebuilt
|
|
1991
|
+
* with an `execute` that throws, and a model that calls one comes back with
|
|
1992
|
+
* the call listed and unexecuted (`finish_reason: 'max_steps'`). The
|
|
1993
|
+
* captured `provider_options` go as they were, a raw `cache_control`
|
|
1994
|
+
* included, and the replaying engine's defaults fill whatever the turn left
|
|
1995
|
+
* unset. `edit` changes the turn before it goes, and `provider` and `model`
|
|
1996
|
+
* send it elsewhere. A replay is inert only on the `ai_sdk` and native
|
|
1997
|
+
* transports, since an external provider runs its own loop and tools.
|
|
1998
|
+
*/
|
|
1999
|
+
export declare function replay_turn(engine: Engine, turn: CapturedTurn, options?: {
|
|
2000
|
+
/** Change the turn before it goes (drop a raw `cache_control`, reword a message). */
|
|
2001
|
+
readonly edit?: (turn: CapturedTurn) => CapturedTurn;
|
|
2002
|
+
/** Send it to this provider instead of the one it was captured on. */
|
|
2003
|
+
readonly provider?: string;
|
|
2004
|
+
/** Send it to this model instead of the one it was captured on. */
|
|
2005
|
+
readonly model?: string;
|
|
2006
|
+
/** Where the replay records its own events. */
|
|
2007
|
+
readonly trajectory?: TrajectoryLogger;
|
|
2008
|
+
}): Promise<GenerateResult>;
|
|
2009
|
+
//#endregion
|
|
2010
|
+
//#region src/engine/providers/claude_cli/reported.d.ts
|
|
2011
|
+
/**
|
|
2012
|
+
* Read the claude CLI's reported run detail off anything carrying
|
|
2013
|
+
* `provider_reported`: a `GenerateResult`, a `StepRecord`, or an
|
|
2014
|
+
* `incomplete_generation_error`.
|
|
2015
|
+
*
|
|
2016
|
+
* Returns undefined when the source has no `claude_cli` entry, or when the
|
|
2017
|
+
* entry lacks a string `session_id` and a numeric `duration_ms`.
|
|
2018
|
+
* `duration_api_ms` carries through only when it is a number.
|
|
2019
|
+
*/
|
|
2020
|
+
export declare function claude_cli_reported(source: {
|
|
2021
|
+
readonly provider_reported?: Readonly<Record<string, unknown>>;
|
|
2022
|
+
}): ClaudeCliProviderReported | undefined;
|
|
2023
|
+
//#endregion
|
|
2022
2024
|
//#region src/composites/adversarial.d.ts
|
|
2023
2025
|
type AdversarialBuildInput<input, candidate> = {
|
|
2024
2026
|
readonly input: input;
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { A as is_step, B as timeout_error, F as flow_changed_error, H as is_step_kind, I as gate_result_error, L as resume_validation_error, M as describe_cycle_error, N as duplicate_suspend_id_error, O as same_input_as, P as error_path, R as run_not_found_error, U as resolve_display_name, V as STEP_KINDS, _ as step, a as suspend, b as suggest_step_id, c as loop, d as retry, f as pipe, g as sequence, h as parallel, i as use, j as aborted_error, k as describe, l as timeout, m as branch, n as scope, o as checkpoint, p as map, r as stash, s as compose, t as chain, u as fallback, v as assert_valid_step_id, w as run, x as durable, y as is_valid_step_id, z as suspended_error } from "./core-Bfzt55Fl.js";
|
|
2
|
-
import { t as create_engine } from "./engine-
|
|
2
|
+
import { t as create_engine } from "./engine-BTijBDlY.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
|
|
7
|
+
import { A as provider_auth_error, D as incomplete_generation_error, E as engine_disposed_error, F as rate_limit_error, I as schema_validation_error, L as tool_approval_denied_error, M as provider_error, N as provider_not_configured_error, O as model_required_error, P as provider_required_error, R as tool_error, T as engine_config_error, g as default_normalize_usage, j as provider_capability_error, k as on_chunk_error, w as claude_cli_error, z as turn_timeout_error } from "./leading_system-CHSYz0h9.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";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { j as aborted_error } from "./core-Bfzt55Fl.js";
|
|
2
|
-
import {
|
|
2
|
+
import { _ as load_optional_peer, g as default_normalize_usage, l as network_failure, o as is_own_reasoning, t as split_leading_system_run } from "./leading_system-CHSYz0h9.js";
|
|
3
3
|
import { Output, isStepCount, streamText, tool } from "ai";
|
|
4
4
|
//#region src/engine/providers/ai_sdk/telemetry.ts
|
|
5
5
|
/**
|
|
@@ -516,4 +516,4 @@ function create_ai_sdk_turn(cfg) {
|
|
|
516
516
|
//#endregion
|
|
517
517
|
export { create_ai_sdk_turn, map_finish_reason, map_stream_part_to_chunk, split_leading_system, to_provider_reported, to_raw_provider_usage, to_sdk_messages, to_sdk_tools, to_turn_content };
|
|
518
518
|
|
|
519
|
-
//# sourceMappingURL=invoke-
|
|
519
|
+
//# sourceMappingURL=invoke-DnmWf8gE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invoke-x5SNh9DV.js","names":["ai_tool"],"sources":["../src/engine/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts"],"sourcesContent":["/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes streamText, which every\n * turn takes, whether or not a consumer is attached.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type AssistantContent,\n type ContentPart,\n type ImagePart,\n type LanguageModel,\n type ModelMessage,\n type TextPart,\n type TextStreamPart,\n type ToolCallPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n AssistantContentPart,\n FinishReason,\n Message,\n ProviderOptions,\n StreamChunk,\n Tool,\n TurnResult,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport { split_leading_system_run } from '../../leading_system.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type RawProviderUsage,\n} from '../types.js'\nimport { is_own_reasoning, network_failure } from '../native_shared.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n// The SDK exports no name for an assistant reasoning part, so it is read off\n// the assistant content union.\ntype SdkReasoningPart = Extract<Exclude<AssistantContent, string>[number], { type: 'reasoning' }>\n\n/**\n * Attach a Fascicle part's provider_options to an SDK prompt part as its\n * providerOptions, the key the SDK reads a part's provider data back from.\n */\nfunction with_provider_options<part extends { providerOptions?: TextPart['providerOptions'] }>(\n sdk_part: part,\n provider_options: ProviderOptions | undefined,\n): part {\n if (provider_options === undefined) return sdk_part\n // ProviderOptions is the two-level provider map the SDK's shared provider\n // options spell with JSON values; the payloads are the SDK's own metadata.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return { ...sdk_part, providerOptions: provider_options as NonNullable<part['providerOptions']> }\n}\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Read a numeric field off an object by key, or undefined when it is absent or\n * not a number. The single typeof guard behind every usage-field read below.\n */\nfunction read_number(source: object, key: string): number | undefined {\n const value = Reflect.get(source, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read the AI SDK's nested `inputTokenDetails` (cache read/write counts) onto\n * `raw`. Present-but-empty details still seed `input_token_details` so the\n * \"the SDK reported details\" signal survives even when both counts are absent.\n */\nfunction read_input_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'inputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.input_token_details = {}\n const cache_read = read_number(details, 'cacheReadTokens')\n if (cache_read !== undefined) raw.input_token_details.cached_tokens = cache_read\n const cache_write = read_number(details, 'cacheWriteTokens')\n if (cache_write !== undefined) raw.input_token_details.cache_creation_input_tokens = cache_write\n}\n\n/**\n * Read the AI SDK's nested `outputTokenDetails` (reasoning-token count) onto\n * `raw`, seeding `output_token_details` whenever the details object is present.\n */\nfunction read_output_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'outputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.output_token_details = {}\n const reasoning = read_number(details, 'reasoningTokens')\n if (reasoning !== undefined) raw.output_token_details.reasoning_tokens = reasoning\n}\n\n/**\n * Read the flattened snake_case usage fields some provider mocks return\n * directly. The `input_tokens`/`output_tokens` flats are fallbacks: they fill\n * in only when the camelCase read did not already set the same total.\n */\nfunction read_flat_usage(usage: object, raw: RawProviderUsage): void {\n const cached = read_number(usage, 'cached_input_tokens')\n if (cached !== undefined) raw.cached_input_tokens = cached\n const cache_write = read_number(usage, 'cache_write_tokens')\n if (cache_write !== undefined) raw.cache_write_tokens = cache_write\n const reasoning = read_number(usage, 'reasoning_tokens')\n if (reasoning !== undefined) raw.reasoning_tokens = reasoning\n const input_flat = read_number(usage, 'input_tokens')\n if (raw.input_tokens === undefined && input_flat !== undefined) raw.input_tokens = input_flat\n const output_flat = read_number(usage, 'output_tokens')\n if (raw.output_tokens === undefined && output_flat !== undefined) raw.output_tokens = output_flat\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = read_number(usage, 'inputTokens')\n if (input_tokens !== undefined) raw.input_tokens = input_tokens\n const output_tokens = read_number(usage, 'outputTokens')\n if (output_tokens !== undefined) raw.output_tokens = output_tokens\n read_input_details(usage, raw)\n read_output_details(usage, raw)\n read_flat_usage(usage, raw)\n return raw\n}\n\n/**\n * Normalize an AI SDK `providerMetadata` value into the neutral\n * TurnResult.provider_reported shape.\n *\n * The SDK's metadata is already keyed by provider name, which is the shape\n * provider_reported documents, so the keys ride through untranslated and every\n * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,\n * anthropic's cache detail, openai's own fields. The payloads stay opaque\n * (callers narrow them at the use site), so this copies the top level and\n * inspects nothing below it. An absent or empty map returns undefined, keeping\n * \"the provider reported nothing\" spelled one way.\n */\nexport function to_provider_reported(metadata: unknown): Record<string, unknown> | undefined {\n if (metadata === null || typeof metadata !== 'object') return undefined\n const keys = Object.keys(metadata)\n if (keys.length === 0) return undefined\n const reported: Record<string, unknown> = {}\n for (const key of keys) reported[key] = Reflect.get(metadata, key)\n return reported\n}\n\n/**\n * Map a tool result to the SDK's tool message. A failed call's result goes as\n * `error-text`, a denial included, since @ai-sdk/anthropic turns `error-text`\n * into `is_error` and drops the flag for `execution-denied`; a success's goes\n * as `text`.\n */\nfunction to_sdk_tool_message(m: Extract<Message, { role: 'tool' }>): ModelMessage {\n return {\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: m.is_error === true ? 'error-text' : 'text', value: m.content },\n },\n ],\n }\n}\n\n/**\n * Map Fascicle's Message[] to the AI SDK's ModelMessage[] shape. Each\n * assistant part's provider_options go back as its providerOptions, which is\n * where the SDK reads a signature or a thought signature back from, and a\n * reasoning part goes back only when it carries data under `metadata_key`,\n * the key the adapter's package writes, so a turn only ever sends back its\n * own provider's reasoning.\n */\nexport function to_sdk_messages(\n messages: ReadonlyArray<Message>,\n metadata_key: string,\n): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<TextPart | ImagePart> = m.content.map((p) => {\n if (p.type === 'text') {\n return with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)\n }\n const image_part: ImagePart = { type: 'image', image: p.image }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return with_provider_options(image_part, p.provider_options)\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push(to_sdk_tool_message(m))\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.flatMap((p): Array<TextPart | SdkReasoningPart | ToolCallPart> => {\n if (p.type === 'text') {\n return [with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)]\n }\n if (p.type === 'reasoning') {\n // Another package's reasoning, or reasoning with no data, would draw a\n // warning or a refusal from this one.\n if (!is_own_reasoning(p, metadata_key)) return []\n return [\n with_provider_options<SdkReasoningPart>(\n { type: 'reasoning', text: p.text },\n p.provider_options,\n ),\n ]\n }\n // A block only its provider understands has no SDK part to ride.\n if (p.type === 'opaque') return []\n return [\n with_provider_options<ToolCallPart>(\n { type: 'tool-call', toolCallId: p.id, toolName: p.name, input: p.input },\n p.provider_options,\n ),\n ]\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). Fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (Fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n return split_leading_system_run(messages, (m) => m.content)\n}\n\n/**\n * Read a part's providerMetadata as provider_options, or undefined when it\n * carries none, so a part with nothing to send back stays bare.\n */\nfunction to_part_options(metadata: ProviderOptions | undefined): ProviderOptions | undefined {\n return metadata !== undefined && Object.keys(metadata).length > 0 ? metadata : undefined\n}\n\n/**\n * Map one SDK content part to an assistant part with its providerMetadata as\n * provider_options, or undefined for a kind with nothing to send back\n * (sources, files, tool results).\n */\nfunction to_turn_part(part: ContentPart<ToolSet>): AssistantContentPart | undefined {\n if (part.type === 'text') {\n return with_part_options({ type: 'text', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'reasoning') {\n return with_part_options({ type: 'reasoning', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'tool-call') {\n return with_part_options(\n { type: 'tool_call', id: part.toolCallId, name: part.toolName, input: part.input },\n part.providerMetadata,\n )\n }\n return undefined\n}\n\n/**\n * Give an assistant part the provider_options its metadata carries, leaving\n * the key off when there is none.\n */\nfunction with_part_options<part extends AssistantContentPart>(\n turn_part: part,\n metadata: ProviderOptions | undefined,\n): part {\n const provider_options = to_part_options(metadata)\n return provider_options === undefined ? turn_part : { ...turn_part, provider_options }\n}\n\n/**\n * Map an SDK step's content to TurnResult.content: its text, reasoning, and\n * tool calls in the order the provider sent them, each with its\n * providerMetadata as provider_options. Undefined when no part is reasoning\n * or carries data, so every other turn stays exactly what it was.\n */\nexport function to_turn_content(\n content: ReadonlyArray<ContentPart<ToolSet>>,\n): AssistantContentPart[] | undefined {\n const parts = content.flatMap((part) => to_turn_part(part) ?? [])\n const carries = parts.some(\n (part) => part.type === 'reasoning' || part.provider_options !== undefined,\n )\n return carries ? parts : undefined\n}\n\n/**\n * Map Fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model. A finish-step's usage goes\n * through `normalize_usage` with the step's providerMetadata, the adapter's\n * own mapper on a turn, so the step_finish chunk and the step record agree.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n normalize_usage: AiSdkProviderAdapter['normalize_usage'] = default_normalize_usage,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: normalize_usage(to_raw_provider_usage(part.usage), part.providerMetadata),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * The running TurnResult fields collect_stream builds as it consumes the SDK\n * stream: text and tool calls accrue across parts, while finish reason, usage,\n * and provider_reported are overwritten by the terminal finish-step.\n */\ntype StreamAccumulator = {\n text: string\n tool_calls: RawToolCall[]\n finish_reason: FinishReason\n raw_usage: RawProviderUsage\n provider_reported: Record<string, unknown> | undefined\n /** True when the step finished as 'other' with no raw reason: a cut-off stream. */\n cut_off: boolean\n}\n\n/**\n * Fold one stream part's accumulated state into `acc`: text deltas append,\n * tool-call parts push a RawToolCall, and the finish-step overwrites finish\n * reason, usage, and provider_reported. A finish-step of 'other' with no raw\n * finish reason is what a provider package reports when its stream ended\n * before the provider said why, so it marks the stream as cut off. Parts with\n * no accumulated state (error, abort, stream framing) are the caller's to\n * handle.\n */\nfunction accumulate_stream_part(part: TextStreamPart<ToolSet>, acc: StreamAccumulator): void {\n if (part.type === 'text-delta') {\n acc.text += part.text\n return\n }\n if (part.type === 'tool-call') {\n acc.tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n return\n }\n if (part.type === 'finish-step') {\n acc.finish_reason = map_finish_reason(part.finishReason)\n acc.raw_usage = to_raw_provider_usage(part.usage)\n acc.provider_reported = to_provider_reported(part.providerMetadata)\n acc.cut_off = part.finishReason === 'other' && part.rawFinishReason === undefined\n }\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes. Every turn\n * takes this path, so the dispatcher passes chunks on only when a consumer\n * is attached. A failure reaches the engine through the stream's error part,\n * so `onError` stays quiet rather than writing each one to console.error. A\n * stream cut off before the step finished throws the network shape, which\n * the engine retries when nothing consumed the chunks. Structured output is\n * parsed by the engine's own schema loop, since streamText parses `output`\n * only when it is read, which this never does.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n observe_chunk: (chunk: StreamChunk) => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText({ ...params, onError: () => {} })\n const acc: StreamAccumulator = {\n text: '',\n tool_calls: [],\n finish_reason: 'stop',\n raw_usage: {},\n provider_reported: undefined,\n cut_off: false,\n }\n for await (const part of stream_result.stream) {\n accumulate_stream_part(part, acc)\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index, adapter.normalize_usage)\n if (chunk === undefined) continue\n // The engine stamps the first dispatched chunk, not the first stream part:\n // the SDK opens every stream with `start` and `start-step` framing before\n // the model has produced a token, and a stamp there would leave prefill\n // inside the decode window throughput() measures. This is also the native\n // transport's rule (build_native_invoke observes in dispatch_chunk), so a\n // failure before the first token stays retryable on both.\n observe_chunk(chunk)\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n if (acc.cut_off) {\n throw network_failure(\n `${adapter.name} stream ended before the step finished; the result would be truncated`,\n )\n }\n // The step's content settles once the stream has drained, so it is read\n // only after the loop and never on a failed stream.\n const content = to_turn_content(await stream_result.content)\n return {\n text: acc.text,\n tool_calls: acc.tool_calls,\n finish_reason: acc.finish_reason,\n // provider_reported is the step's providerMetadata, copied key by key,\n // which is what the step_finish chunk's usage was normalized against.\n usage: adapter.normalize_usage(acc.raw_usage, acc.provider_reported),\n // Stryker disable next-line ConditionalExpression: an always-true spread only adds an explicit `provider_reported: undefined` key, which every reader of TurnResult treats identically to the absent key.\n ...(acc.provider_reported !== undefined ? { provider_reported: acc.provider_reported } : {}),\n ...(content !== undefined ? { content } : {}),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: ToolSchema | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly reasoning: EffortTranslation['reasoning']\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n /** Sees every chunk the turn dispatches, just before it goes out. */\n readonly observe_chunk: (chunk: StreamChunk) => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the streamText\n * call body behind the same neutral seam a native adapter's invoke_turn\n * implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (for example, Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what streamText consumes to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages, cfg.adapter.metadata_key ?? cfg.adapter.name),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n // The SDK's own effort option; the provider package maps the level per\n // model, and leaving it out is the provider's default.\n if (cfg.reasoning !== undefined) base_params.reasoning = cfg.reasoning\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.observe_chunk,\n internal_controller,\n cfg.adapter,\n )\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n"],"mappings":";;;;;;;;AAyCA,eAAsB,uBACpB,UACgD;CAChD,IAAI,CAAC,UAAU,SAAS,OAAO,KAAA;CAK/B,MAAM,MAAiC;EAAE,WAAW;EAAM,cAAc,CAAC,KAHjD,OADN,mBAAoC,cAAc,GAAA,CACxC,cAC1B,SAAS,WAAW,KAAA,IAAY,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC,CAEkB,CAAC;CAAE;CACtF,IAAI,SAAS,gBAAgB,KAAA,GAAW,IAAI,aAAa,SAAS;CAClE,IAAI,SAAS,kBAAkB,KAAA,GAAW,IAAI,eAAe,SA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B,KAAA,GAAW,YAAY,cAAc,IAAI;EACjE,IAAI,IAAI,eAAe,KAAA,GAAW,YAAY,kBAAkB,IAAI;EACpE,IAAI,IAAI,UAAU,KAAA,GAAW,YAAY,OAAO,IAAI;EAGpD,IAAI,IAAI,cAAc,KAAA,GAAW,YAAY,YAAY,IAAI;EAC7D,IAAI,cAAc,KAAA,GAIhB,YAAY,yBAAyB;EAKvC,IAAI;GACF,OAAO,MAAM,eACX,aACA,KAAK,YACL,IAAI,YACJ,KAAK,eACL,qBACA,IAAI,OACN;EACF,UAAU;GACR,KAAK,MAAM,oBAAoB,SAAS,oBAAoB;EAC9D;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"invoke-DnmWf8gE.js","names":["ai_tool"],"sources":["../src/engine/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts"],"sourcesContent":["/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes streamText, which every\n * turn takes, whether or not a consumer is attached.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type AssistantContent,\n type ContentPart,\n type ImagePart,\n type LanguageModel,\n type ModelMessage,\n type TextPart,\n type TextStreamPart,\n type ToolCallPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n AssistantContentPart,\n FinishReason,\n Message,\n ProviderOptions,\n StreamChunk,\n Tool,\n TurnResult,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport { split_leading_system_run } from '../../leading_system.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type RawProviderUsage,\n} from '../types.js'\nimport { is_own_reasoning, network_failure } from '../native_shared.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n// The SDK exports no name for an assistant reasoning part, so it is read off\n// the assistant content union.\ntype SdkReasoningPart = Extract<Exclude<AssistantContent, string>[number], { type: 'reasoning' }>\n\n/**\n * Attach a Fascicle part's provider_options to an SDK prompt part as its\n * providerOptions, the key the SDK reads a part's provider data back from.\n */\nfunction with_provider_options<part extends { providerOptions?: TextPart['providerOptions'] }>(\n sdk_part: part,\n provider_options: ProviderOptions | undefined,\n): part {\n if (provider_options === undefined) return sdk_part\n // ProviderOptions is the two-level provider map the SDK's shared provider\n // options spell with JSON values; the payloads are the SDK's own metadata.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return { ...sdk_part, providerOptions: provider_options as NonNullable<part['providerOptions']> }\n}\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Read a numeric field off an object by key, or undefined when it is absent or\n * not a number. The single typeof guard behind every usage-field read below.\n */\nfunction read_number(source: object, key: string): number | undefined {\n const value = Reflect.get(source, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read the AI SDK's nested `inputTokenDetails` (cache read/write counts) onto\n * `raw`. Present-but-empty details still seed `input_token_details` so the\n * \"the SDK reported details\" signal survives even when both counts are absent.\n */\nfunction read_input_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'inputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.input_token_details = {}\n const cache_read = read_number(details, 'cacheReadTokens')\n if (cache_read !== undefined) raw.input_token_details.cached_tokens = cache_read\n const cache_write = read_number(details, 'cacheWriteTokens')\n if (cache_write !== undefined) raw.input_token_details.cache_creation_input_tokens = cache_write\n}\n\n/**\n * Read the AI SDK's nested `outputTokenDetails` (reasoning-token count) onto\n * `raw`, seeding `output_token_details` whenever the details object is present.\n */\nfunction read_output_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'outputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.output_token_details = {}\n const reasoning = read_number(details, 'reasoningTokens')\n if (reasoning !== undefined) raw.output_token_details.reasoning_tokens = reasoning\n}\n\n/**\n * Read the flattened snake_case usage fields some provider mocks return\n * directly. The `input_tokens`/`output_tokens` flats are fallbacks: they fill\n * in only when the camelCase read did not already set the same total.\n */\nfunction read_flat_usage(usage: object, raw: RawProviderUsage): void {\n const cached = read_number(usage, 'cached_input_tokens')\n if (cached !== undefined) raw.cached_input_tokens = cached\n const cache_write = read_number(usage, 'cache_write_tokens')\n if (cache_write !== undefined) raw.cache_write_tokens = cache_write\n const reasoning = read_number(usage, 'reasoning_tokens')\n if (reasoning !== undefined) raw.reasoning_tokens = reasoning\n const input_flat = read_number(usage, 'input_tokens')\n if (raw.input_tokens === undefined && input_flat !== undefined) raw.input_tokens = input_flat\n const output_flat = read_number(usage, 'output_tokens')\n if (raw.output_tokens === undefined && output_flat !== undefined) raw.output_tokens = output_flat\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = read_number(usage, 'inputTokens')\n if (input_tokens !== undefined) raw.input_tokens = input_tokens\n const output_tokens = read_number(usage, 'outputTokens')\n if (output_tokens !== undefined) raw.output_tokens = output_tokens\n read_input_details(usage, raw)\n read_output_details(usage, raw)\n read_flat_usage(usage, raw)\n return raw\n}\n\n/**\n * Normalize an AI SDK `providerMetadata` value into the neutral\n * TurnResult.provider_reported shape.\n *\n * The SDK's metadata is already keyed by provider name, which is the shape\n * provider_reported documents, so the keys ride through untranslated and every\n * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,\n * anthropic's cache detail, openai's own fields. The payloads stay opaque\n * (callers narrow them at the use site), so this copies the top level and\n * inspects nothing below it. An absent or empty map returns undefined, keeping\n * \"the provider reported nothing\" spelled one way.\n */\nexport function to_provider_reported(metadata: unknown): Record<string, unknown> | undefined {\n if (metadata === null || typeof metadata !== 'object') return undefined\n const keys = Object.keys(metadata)\n if (keys.length === 0) return undefined\n const reported: Record<string, unknown> = {}\n for (const key of keys) reported[key] = Reflect.get(metadata, key)\n return reported\n}\n\n/**\n * Map a tool result to the SDK's tool message. A failed call's result goes as\n * `error-text`, a denial included, since @ai-sdk/anthropic turns `error-text`\n * into `is_error` and drops the flag for `execution-denied`; a success's goes\n * as `text`.\n */\nfunction to_sdk_tool_message(m: Extract<Message, { role: 'tool' }>): ModelMessage {\n return {\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: m.is_error === true ? 'error-text' : 'text', value: m.content },\n },\n ],\n }\n}\n\n/**\n * Map Fascicle's Message[] to the AI SDK's ModelMessage[] shape. Each\n * assistant part's provider_options go back as its providerOptions, which is\n * where the SDK reads a signature or a thought signature back from, and a\n * reasoning part goes back only when it carries data under `metadata_key`,\n * the key the adapter's package writes, so a turn only ever sends back its\n * own provider's reasoning.\n */\nexport function to_sdk_messages(\n messages: ReadonlyArray<Message>,\n metadata_key: string,\n): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<TextPart | ImagePart> = m.content.map((p) => {\n if (p.type === 'text') {\n return with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)\n }\n const image_part: ImagePart = { type: 'image', image: p.image }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return with_provider_options(image_part, p.provider_options)\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push(to_sdk_tool_message(m))\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.flatMap((p): Array<TextPart | SdkReasoningPart | ToolCallPart> => {\n if (p.type === 'text') {\n return [with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)]\n }\n if (p.type === 'reasoning') {\n // Another package's reasoning, or reasoning with no data, would draw a\n // warning or a refusal from this one.\n if (!is_own_reasoning(p, metadata_key)) return []\n return [\n with_provider_options<SdkReasoningPart>(\n { type: 'reasoning', text: p.text },\n p.provider_options,\n ),\n ]\n }\n // A block only its provider understands has no SDK part to ride.\n if (p.type === 'opaque') return []\n return [\n with_provider_options<ToolCallPart>(\n { type: 'tool-call', toolCallId: p.id, toolName: p.name, input: p.input },\n p.provider_options,\n ),\n ]\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). Fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (Fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n return split_leading_system_run(messages, (m) => m.content)\n}\n\n/**\n * Read a part's providerMetadata as provider_options, or undefined when it\n * carries none, so a part with nothing to send back stays bare.\n */\nfunction to_part_options(metadata: ProviderOptions | undefined): ProviderOptions | undefined {\n return metadata !== undefined && Object.keys(metadata).length > 0 ? metadata : undefined\n}\n\n/**\n * Map one SDK content part to an assistant part with its providerMetadata as\n * provider_options, or undefined for a kind with nothing to send back\n * (sources, files, tool results).\n */\nfunction to_turn_part(part: ContentPart<ToolSet>): AssistantContentPart | undefined {\n if (part.type === 'text') {\n return with_part_options({ type: 'text', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'reasoning') {\n return with_part_options({ type: 'reasoning', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'tool-call') {\n return with_part_options(\n { type: 'tool_call', id: part.toolCallId, name: part.toolName, input: part.input },\n part.providerMetadata,\n )\n }\n return undefined\n}\n\n/**\n * Give an assistant part the provider_options its metadata carries, leaving\n * the key off when there is none.\n */\nfunction with_part_options<part extends AssistantContentPart>(\n turn_part: part,\n metadata: ProviderOptions | undefined,\n): part {\n const provider_options = to_part_options(metadata)\n return provider_options === undefined ? turn_part : { ...turn_part, provider_options }\n}\n\n/**\n * Map an SDK step's content to TurnResult.content: its text, reasoning, and\n * tool calls in the order the provider sent them, each with its\n * providerMetadata as provider_options. Undefined when no part is reasoning\n * or carries data, so every other turn stays exactly what it was.\n */\nexport function to_turn_content(\n content: ReadonlyArray<ContentPart<ToolSet>>,\n): AssistantContentPart[] | undefined {\n const parts = content.flatMap((part) => to_turn_part(part) ?? [])\n const carries = parts.some(\n (part) => part.type === 'reasoning' || part.provider_options !== undefined,\n )\n return carries ? parts : undefined\n}\n\n/**\n * Map Fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model. A finish-step's usage goes\n * through `normalize_usage` with the step's providerMetadata, the adapter's\n * own mapper on a turn, so the step_finish chunk and the step record agree.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n normalize_usage: AiSdkProviderAdapter['normalize_usage'] = default_normalize_usage,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: normalize_usage(to_raw_provider_usage(part.usage), part.providerMetadata),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * The running TurnResult fields collect_stream builds as it consumes the SDK\n * stream: text and tool calls accrue across parts, while finish reason, usage,\n * and provider_reported are overwritten by the terminal finish-step.\n */\ntype StreamAccumulator = {\n text: string\n tool_calls: RawToolCall[]\n finish_reason: FinishReason\n raw_usage: RawProviderUsage\n provider_reported: Record<string, unknown> | undefined\n /** True when the step finished as 'other' with no raw reason: a cut-off stream. */\n cut_off: boolean\n}\n\n/**\n * Fold one stream part's accumulated state into `acc`: text deltas append,\n * tool-call parts push a RawToolCall, and the finish-step overwrites finish\n * reason, usage, and provider_reported. A finish-step of 'other' with no raw\n * finish reason is what a provider package reports when its stream ended\n * before the provider said why, so it marks the stream as cut off. Parts with\n * no accumulated state (error, abort, stream framing) are the caller's to\n * handle.\n */\nfunction accumulate_stream_part(part: TextStreamPart<ToolSet>, acc: StreamAccumulator): void {\n if (part.type === 'text-delta') {\n acc.text += part.text\n return\n }\n if (part.type === 'tool-call') {\n acc.tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n return\n }\n if (part.type === 'finish-step') {\n acc.finish_reason = map_finish_reason(part.finishReason)\n acc.raw_usage = to_raw_provider_usage(part.usage)\n acc.provider_reported = to_provider_reported(part.providerMetadata)\n acc.cut_off = part.finishReason === 'other' && part.rawFinishReason === undefined\n }\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes. Every turn\n * takes this path, so the dispatcher passes chunks on only when a consumer\n * is attached. A failure reaches the engine through the stream's error part,\n * so `onError` stays quiet rather than writing each one to console.error. A\n * stream cut off before the step finished throws the network shape, which\n * the engine retries when nothing consumed the chunks. Structured output is\n * parsed by the engine's own schema loop, since streamText parses `output`\n * only when it is read, which this never does.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n observe_chunk: (chunk: StreamChunk) => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText({ ...params, onError: () => {} })\n const acc: StreamAccumulator = {\n text: '',\n tool_calls: [],\n finish_reason: 'stop',\n raw_usage: {},\n provider_reported: undefined,\n cut_off: false,\n }\n for await (const part of stream_result.stream) {\n accumulate_stream_part(part, acc)\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index, adapter.normalize_usage)\n if (chunk === undefined) continue\n // The engine stamps the first dispatched chunk, not the first stream part:\n // the SDK opens every stream with `start` and `start-step` framing before\n // the model has produced a token, and a stamp there would leave prefill\n // inside the decode window throughput() measures. This is also the native\n // transport's rule (build_native_invoke observes in dispatch_chunk), so a\n // failure before the first token stays retryable on both.\n observe_chunk(chunk)\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n if (acc.cut_off) {\n throw network_failure(\n `${adapter.name} stream ended before the step finished; the result would be truncated`,\n )\n }\n // The step's content settles once the stream has drained, so it is read\n // only after the loop and never on a failed stream.\n const content = to_turn_content(await stream_result.content)\n return {\n text: acc.text,\n tool_calls: acc.tool_calls,\n finish_reason: acc.finish_reason,\n // provider_reported is the step's providerMetadata, copied key by key,\n // which is what the step_finish chunk's usage was normalized against.\n usage: adapter.normalize_usage(acc.raw_usage, acc.provider_reported),\n // Stryker disable next-line ConditionalExpression: an always-true spread only adds an explicit `provider_reported: undefined` key, which every reader of TurnResult treats identically to the absent key.\n ...(acc.provider_reported !== undefined ? { provider_reported: acc.provider_reported } : {}),\n ...(content !== undefined ? { content } : {}),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: ToolSchema | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly reasoning: EffortTranslation['reasoning']\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n /** Sees every chunk the turn dispatches, just before it goes out. */\n readonly observe_chunk: (chunk: StreamChunk) => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the streamText\n * call body behind the same neutral seam a native adapter's invoke_turn\n * implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (for example, Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what streamText consumes to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages, cfg.adapter.metadata_key ?? cfg.adapter.name),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n // The SDK's own effort option; the provider package maps the level per\n // model, and leaving it out is the provider's default.\n if (cfg.reasoning !== undefined) base_params.reasoning = cfg.reasoning\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.observe_chunk,\n internal_controller,\n cfg.adapter,\n )\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n"],"mappings":";;;;;;;;AAyCA,eAAsB,uBACpB,UACgD;CAChD,IAAI,CAAC,UAAU,SAAS,OAAO,KAAA;CAK/B,MAAM,MAAiC;EAAE,WAAW;EAAM,cAAc,CAAC,KAHjD,OADN,mBAAoC,cAAc,GAAA,CACxC,cAC1B,SAAS,WAAW,KAAA,IAAY,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC,CAEkB,CAAC;CAAE;CACtF,IAAI,SAAS,gBAAgB,KAAA,GAAW,IAAI,aAAa,SAAS;CAClE,IAAI,SAAS,kBAAkB,KAAA,GAAW,IAAI,eAAe,SAAS;CACtE,IAAI,SAAS,mBAAmB,KAAA,GAAW,IAAI,gBAAgB,SAAS;CACxE,IAAI,SAAS,aAAa,KAAA,GAAW,IAAI,WAAW,SAAS;CAC7D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;ACMA,SAAS,sBACP,UACA,kBACM;CACN,IAAI,qBAAqB,KAAA,GAAW,OAAO;CAI3C,OAAO;EAAE,GAAG;EAAU,iBAAiB;CAAyD;AAClG;;;;AAKA,SAAgB,kBAAkB,KAAuC;CACvE,QAAQ,KAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK,kBACH,OAAO;EACT,KAAK;EACL,KAAK,cACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;AAMA,SAAS,YAAY,QAAgB,KAAiC;CACpE,MAAM,QAAQ,QAAQ,IAAI,QAAQ,GAAG;CACrC,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;;;AAOA,SAAS,mBAAmB,OAAe,KAA6B;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