@agtlantis/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/README.md +18 -5
  2. package/dist/errors/index.d.ts +4 -0
  3. package/dist/errors/index.d.ts.map +1 -0
  4. package/dist/errors/index.js +3 -0
  5. package/dist/errors/index.js.map +1 -0
  6. package/dist/errors/types.d.ts +69 -0
  7. package/dist/errors/types.d.ts.map +1 -0
  8. package/dist/errors/types.js +116 -0
  9. package/dist/errors/types.js.map +1 -0
  10. package/dist/errors/utils.d.ts +17 -0
  11. package/dist/errors/utils.d.ts.map +1 -0
  12. package/dist/errors/utils.js +16 -0
  13. package/dist/errors/utils.js.map +1 -0
  14. package/dist/execution/constants.d.ts +7 -0
  15. package/dist/execution/constants.d.ts.map +1 -0
  16. package/dist/execution/constants.js +7 -0
  17. package/dist/execution/constants.js.map +1 -0
  18. package/dist/execution/index.d.ts +8 -0
  19. package/dist/execution/index.d.ts.map +1 -0
  20. package/dist/execution/index.js +7 -0
  21. package/dist/execution/index.js.map +1 -0
  22. package/dist/execution/mapping.d.ts +17 -0
  23. package/dist/execution/mapping.d.ts.map +1 -0
  24. package/dist/execution/mapping.js +197 -0
  25. package/dist/execution/mapping.js.map +1 -0
  26. package/dist/execution/shared.d.ts +86 -0
  27. package/dist/execution/shared.d.ts.map +1 -0
  28. package/dist/execution/shared.js +100 -0
  29. package/dist/execution/shared.js.map +1 -0
  30. package/dist/execution/simple-host.d.ts +56 -0
  31. package/dist/execution/simple-host.d.ts.map +1 -0
  32. package/dist/execution/simple-host.js +126 -0
  33. package/dist/execution/simple-host.js.map +1 -0
  34. package/dist/execution/streaming-host.d.ts +79 -0
  35. package/dist/execution/streaming-host.d.ts.map +1 -0
  36. package/dist/execution/streaming-host.js +276 -0
  37. package/dist/execution/streaming-host.js.map +1 -0
  38. package/dist/execution/testing/fixtures.d.ts +67 -0
  39. package/dist/execution/testing/fixtures.d.ts.map +1 -0
  40. package/dist/execution/testing/fixtures.js +145 -0
  41. package/dist/execution/testing/fixtures.js.map +1 -0
  42. package/dist/execution/testing/helpers.d.ts +218 -0
  43. package/dist/execution/testing/helpers.d.ts.map +1 -0
  44. package/dist/execution/testing/helpers.js +327 -0
  45. package/dist/execution/testing/helpers.js.map +1 -0
  46. package/dist/execution/testing/host-configs.d.ts +56 -0
  47. package/dist/execution/testing/host-configs.d.ts.map +1 -0
  48. package/dist/execution/testing/host-configs.js +154 -0
  49. package/dist/execution/testing/host-configs.js.map +1 -0
  50. package/dist/execution/testing/vitest-assertions.d.ts +102 -0
  51. package/dist/execution/testing/vitest-assertions.d.ts.map +1 -0
  52. package/dist/execution/testing/vitest-assertions.js +142 -0
  53. package/dist/execution/testing/vitest-assertions.js.map +1 -0
  54. package/dist/execution/types.d.ts +432 -0
  55. package/dist/execution/types.d.ts.map +1 -0
  56. package/dist/execution/types.js +2 -0
  57. package/dist/execution/types.js.map +1 -0
  58. package/dist/execution/utils.d.ts +68 -0
  59. package/dist/execution/utils.d.ts.map +1 -0
  60. package/dist/execution/utils.js +93 -0
  61. package/dist/execution/utils.js.map +1 -0
  62. package/dist/index.d.ts +10 -1506
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +9 -2979
  65. package/dist/index.js.map +1 -1
  66. package/dist/observability/index.d.ts +4 -0
  67. package/dist/observability/index.d.ts.map +1 -0
  68. package/dist/observability/index.js +2 -0
  69. package/dist/observability/index.js.map +1 -0
  70. package/dist/observability/logger.d.ts +161 -0
  71. package/dist/observability/logger.d.ts.map +1 -0
  72. package/dist/observability/logger.js +31 -0
  73. package/dist/observability/logger.js.map +1 -0
  74. package/dist/observability/types.d.ts +46 -0
  75. package/dist/observability/types.d.ts.map +1 -0
  76. package/dist/observability/types.js +2 -0
  77. package/dist/observability/types.js.map +1 -0
  78. package/dist/patterns/index.d.ts +2 -0
  79. package/dist/patterns/index.d.ts.map +1 -0
  80. package/dist/patterns/index.js +2 -0
  81. package/dist/patterns/index.js.map +1 -0
  82. package/dist/patterns/progressive/index.d.ts +2 -0
  83. package/dist/patterns/progressive/index.d.ts.map +1 -0
  84. package/dist/patterns/progressive/index.js +2 -0
  85. package/dist/patterns/progressive/index.js.map +1 -0
  86. package/dist/patterns/progressive/progressive-pattern.d.ts +174 -0
  87. package/dist/patterns/progressive/progressive-pattern.d.ts.map +1 -0
  88. package/dist/patterns/progressive/progressive-pattern.js +260 -0
  89. package/dist/patterns/progressive/progressive-pattern.js.map +1 -0
  90. package/dist/pricing/calculator.d.ts +71 -0
  91. package/dist/pricing/calculator.d.ts.map +1 -0
  92. package/dist/pricing/calculator.js +127 -0
  93. package/dist/pricing/calculator.js.map +1 -0
  94. package/dist/pricing/config.d.ts +61 -0
  95. package/dist/pricing/config.d.ts.map +1 -0
  96. package/dist/pricing/config.js +87 -0
  97. package/dist/pricing/config.js.map +1 -0
  98. package/dist/pricing/defaults.d.ts +29 -0
  99. package/dist/pricing/defaults.d.ts.map +1 -0
  100. package/dist/pricing/defaults.js +139 -0
  101. package/dist/pricing/defaults.js.map +1 -0
  102. package/dist/pricing/index.d.ts +40 -0
  103. package/dist/pricing/index.d.ts.map +1 -0
  104. package/dist/pricing/index.js +43 -0
  105. package/dist/pricing/index.js.map +1 -0
  106. package/dist/pricing/types.d.ts +96 -0
  107. package/dist/pricing/types.d.ts.map +1 -0
  108. package/dist/pricing/types.js +7 -0
  109. package/dist/pricing/types.js.map +1 -0
  110. package/dist/pricing/validator.d.ts +55 -0
  111. package/dist/pricing/validator.d.ts.map +1 -0
  112. package/dist/pricing/validator.js +84 -0
  113. package/dist/pricing/validator.js.map +1 -0
  114. package/dist/prompt/errors.d.ts +112 -0
  115. package/dist/prompt/errors.d.ts.map +1 -0
  116. package/dist/prompt/errors.js +174 -0
  117. package/dist/prompt/errors.js.map +1 -0
  118. package/dist/prompt/file-prompt-repository.d.ts +80 -0
  119. package/dist/prompt/file-prompt-repository.d.ts.map +1 -0
  120. package/dist/prompt/file-prompt-repository.js +287 -0
  121. package/dist/prompt/file-prompt-repository.js.map +1 -0
  122. package/dist/prompt/index.d.ts +34 -0
  123. package/dist/prompt/index.d.ts.map +1 -0
  124. package/dist/prompt/index.js +37 -0
  125. package/dist/prompt/index.js.map +1 -0
  126. package/dist/prompt/prompt-template.d.ts +64 -0
  127. package/dist/prompt/prompt-template.d.ts.map +1 -0
  128. package/dist/prompt/prompt-template.js +90 -0
  129. package/dist/prompt/prompt-template.js.map +1 -0
  130. package/dist/prompt/template.d.ts +23 -0
  131. package/dist/prompt/template.d.ts.map +1 -0
  132. package/dist/prompt/template.js +70 -0
  133. package/dist/prompt/template.js.map +1 -0
  134. package/dist/prompt/types.d.ts +148 -0
  135. package/dist/prompt/types.d.ts.map +1 -0
  136. package/dist/prompt/types.js +7 -0
  137. package/dist/prompt/types.js.map +1 -0
  138. package/dist/provider/base-file-manager.d.ts +14 -0
  139. package/dist/provider/base-file-manager.d.ts.map +1 -0
  140. package/dist/provider/base-file-manager.js +91 -0
  141. package/dist/provider/base-file-manager.js.map +1 -0
  142. package/dist/provider/base-provider.d.ts +41 -0
  143. package/dist/provider/base-provider.d.ts.map +1 -0
  144. package/dist/provider/base-provider.js +21 -0
  145. package/dist/provider/base-provider.js.map +1 -0
  146. package/dist/provider/file-cache.d.ts +14 -0
  147. package/dist/provider/file-cache.d.ts.map +1 -0
  148. package/dist/provider/file-cache.js +29 -0
  149. package/dist/provider/file-cache.js.map +1 -0
  150. package/dist/provider/file-source.d.ts +32 -0
  151. package/dist/provider/file-source.d.ts.map +1 -0
  152. package/dist/provider/file-source.js +180 -0
  153. package/dist/provider/file-source.js.map +1 -0
  154. package/dist/provider/file-utils.d.ts +5 -0
  155. package/dist/provider/file-utils.d.ts.map +1 -0
  156. package/dist/provider/file-utils.js +15 -0
  157. package/dist/provider/file-utils.js.map +1 -0
  158. package/dist/provider/google/factory.d.ts +107 -0
  159. package/dist/provider/google/factory.d.ts.map +1 -0
  160. package/dist/provider/google/factory.js +143 -0
  161. package/dist/provider/google/factory.js.map +1 -0
  162. package/dist/provider/google/file-manager.d.ts +10 -0
  163. package/dist/provider/google/file-manager.d.ts.map +1 -0
  164. package/dist/provider/google/file-manager.js +93 -0
  165. package/dist/provider/google/file-manager.js.map +1 -0
  166. package/dist/provider/google/index.d.ts +8 -0
  167. package/dist/provider/google/index.d.ts.map +1 -0
  168. package/dist/provider/google/index.js +10 -0
  169. package/dist/provider/google/index.js.map +1 -0
  170. package/dist/provider/hash.d.ts +3 -0
  171. package/dist/provider/hash.d.ts.map +1 -0
  172. package/dist/provider/hash.js +34 -0
  173. package/dist/provider/hash.js.map +1 -0
  174. package/dist/provider/index.d.ts +10 -0
  175. package/dist/provider/index.d.ts.map +1 -0
  176. package/dist/provider/index.js +12 -0
  177. package/dist/provider/index.js.map +1 -0
  178. package/dist/provider/noop-file-manager.d.ts +9 -0
  179. package/dist/provider/noop-file-manager.d.ts.map +1 -0
  180. package/dist/provider/noop-file-manager.js +28 -0
  181. package/dist/provider/noop-file-manager.js.map +1 -0
  182. package/dist/provider/openai/factory.d.ts +67 -0
  183. package/dist/provider/openai/factory.d.ts.map +1 -0
  184. package/dist/provider/openai/factory.js +100 -0
  185. package/dist/provider/openai/factory.js.map +1 -0
  186. package/dist/provider/openai/file-manager.d.ts +17 -0
  187. package/dist/provider/openai/file-manager.d.ts.map +1 -0
  188. package/dist/provider/openai/file-manager.js +108 -0
  189. package/dist/provider/openai/file-manager.js.map +1 -0
  190. package/dist/provider/openai/index.d.ts +8 -0
  191. package/dist/provider/openai/index.d.ts.map +1 -0
  192. package/dist/provider/openai/index.js +8 -0
  193. package/dist/provider/openai/index.js.map +1 -0
  194. package/dist/provider/types.d.ts +105 -0
  195. package/dist/provider/types.d.ts.map +1 -0
  196. package/dist/provider/types.js +19 -0
  197. package/dist/provider/types.js.map +1 -0
  198. package/dist/session/index.d.ts +7 -0
  199. package/dist/session/index.d.ts.map +1 -0
  200. package/dist/session/index.js +5 -0
  201. package/dist/session/index.js.map +1 -0
  202. package/dist/session/simple-session.d.ts +98 -0
  203. package/dist/session/simple-session.d.ts.map +1 -0
  204. package/dist/session/simple-session.js +299 -0
  205. package/dist/session/simple-session.js.map +1 -0
  206. package/dist/session/streaming-session.d.ts +90 -0
  207. package/dist/session/streaming-session.d.ts.map +1 -0
  208. package/dist/session/streaming-session.js +151 -0
  209. package/dist/session/streaming-session.js.map +1 -0
  210. package/dist/session/test-utils.d.ts +19 -0
  211. package/dist/session/test-utils.d.ts.map +1 -0
  212. package/dist/session/test-utils.js +65 -0
  213. package/dist/session/test-utils.js.map +1 -0
  214. package/dist/session/types.d.ts +219 -0
  215. package/dist/session/types.d.ts.map +1 -0
  216. package/dist/session/types.js +181 -0
  217. package/dist/session/types.js.map +1 -0
  218. package/dist/session/usage-extractors.d.ts +7 -0
  219. package/dist/session/usage-extractors.d.ts.map +1 -0
  220. package/dist/session/usage-extractors.js +71 -0
  221. package/dist/session/usage-extractors.js.map +1 -0
  222. package/dist/testing/fixtures.d.ts +34 -0
  223. package/dist/testing/fixtures.d.ts.map +1 -0
  224. package/dist/testing/fixtures.js +65 -0
  225. package/dist/testing/fixtures.js.map +1 -0
  226. package/dist/testing/helpers.d.ts +20 -0
  227. package/dist/testing/helpers.d.ts.map +1 -0
  228. package/dist/testing/helpers.js +32 -0
  229. package/dist/testing/helpers.js.map +1 -0
  230. package/dist/testing/index.d.ts +7 -519
  231. package/dist/testing/index.d.ts.map +1 -0
  232. package/dist/testing/index.js +21 -2123
  233. package/dist/testing/index.js.map +1 -1
  234. package/dist/testing/mock-provider.d.ts +79 -0
  235. package/dist/testing/mock-provider.d.ts.map +1 -0
  236. package/dist/testing/mock-provider.js +152 -0
  237. package/dist/testing/mock-provider.js.map +1 -0
  238. package/dist/testing/mock.d.ts +29 -0
  239. package/dist/testing/mock.d.ts.map +1 -0
  240. package/dist/testing/mock.js +154 -0
  241. package/dist/testing/mock.js.map +1 -0
  242. package/dist/testing/test-execution.d.ts +14 -0
  243. package/dist/testing/test-execution.d.ts.map +1 -0
  244. package/dist/testing/test-execution.js +108 -0
  245. package/dist/testing/test-execution.js.map +1 -0
  246. package/dist/utils/deep-merge.d.ts +6 -0
  247. package/dist/utils/deep-merge.d.ts.map +1 -0
  248. package/dist/utils/deep-merge.js +24 -0
  249. package/dist/utils/deep-merge.js.map +1 -0
  250. package/dist/validation/errors.d.ts +28 -0
  251. package/dist/validation/errors.d.ts.map +1 -0
  252. package/dist/validation/errors.js +38 -0
  253. package/dist/validation/errors.js.map +1 -0
  254. package/dist/validation/index.d.ts +5 -0
  255. package/dist/validation/index.d.ts.map +1 -0
  256. package/dist/validation/index.js +4 -0
  257. package/dist/validation/index.js.map +1 -0
  258. package/dist/validation/types.d.ts +49 -0
  259. package/dist/validation/types.d.ts.map +1 -0
  260. package/dist/validation/types.js +2 -0
  261. package/dist/validation/types.js.map +1 -0
  262. package/dist/validation/validation-history.d.ts +12 -0
  263. package/dist/validation/validation-history.d.ts.map +1 -0
  264. package/dist/validation/validation-history.js +29 -0
  265. package/dist/validation/validation-history.js.map +1 -0
  266. package/dist/validation/with-validation.d.ts +38 -0
  267. package/dist/validation/with-validation.d.ts.map +1 -0
  268. package/dist/validation/with-validation.js +58 -0
  269. package/dist/validation/with-validation.js.map +1 -0
  270. package/package.json +71 -75
  271. package/dist/base-provider-2TTw5HAa.d.cts +0 -1254
  272. package/dist/base-provider-2TTw5HAa.d.ts +0 -1254
  273. package/dist/index.cjs +0 -3085
  274. package/dist/index.cjs.map +0 -1
  275. package/dist/index.d.cts +0 -1506
  276. package/dist/testing/index.cjs +0 -2167
  277. package/dist/testing/index.cjs.map +0 -1
  278. package/dist/testing/index.d.cts +0 -520
@@ -1,1254 +0,0 @@
1
- import { LanguageModelUsage, CallSettings, ToolSet, generateText, streamText, generateObject, FilePart, ImagePart, LanguageModel } from 'ai';
2
- import * as zod from 'zod';
3
-
4
- /**
5
- * Timing metrics attached to each streaming event.
6
- * Enables performance monitoring and latency debugging.
7
- *
8
- * @example
9
- * ```typescript
10
- * const event = {
11
- * type: 'progress',
12
- * message: 'Processing...',
13
- * metrics: {
14
- * timestamp: Date.now(),
15
- * elapsedMs: 150,
16
- * deltaMs: 50,
17
- * },
18
- * };
19
- * ```
20
- */
21
- interface EventMetrics {
22
- timestamp: number;
23
- elapsedMs: number;
24
- deltaMs: number;
25
- }
26
-
27
- /**
28
- * Metadata collected during agent execution.
29
- * Available after execution completes via `getSummary()`.
30
- *
31
- * @example
32
- * ```typescript
33
- * const metadata: ExecutionMetadata = {
34
- * duration: 1250,
35
- * usage: {
36
- * inputTokens: 500,
37
- * outputTokens: 200,
38
- * totalTokens: 700,
39
- * },
40
- * };
41
- * ```
42
- */
43
- interface ExecutionMetadata {
44
- duration: number;
45
- languageModelUsage?: LanguageModelUsage;
46
- [key: string]: unknown;
47
- }
48
-
49
- /**
50
- * Pricing types for cost calculation.
51
- *
52
- * @module pricing/types
53
- */
54
- /**
55
- * AI provider type identifier.
56
- *
57
- * Common values: 'google', 'openai', 'anthropic', 'mock'
58
- * Extensible to support custom providers.
59
- */
60
- type ProviderType = string;
61
- /**
62
- * Pricing for a specific model in USD per million tokens.
63
- *
64
- * @example
65
- * ```typescript
66
- * const gpt4Pricing: ModelPricing = {
67
- * inputPricePerMillion: 2.5,
68
- * outputPricePerMillion: 10.0,
69
- * cachedInputPricePerMillion: 1.25, // 50% discount for cached tokens
70
- * };
71
- * ```
72
- */
73
- interface ModelPricing {
74
- inputPricePerMillion: number;
75
- outputPricePerMillion: number;
76
- /** Defaults to inputPricePerMillion if not set */
77
- cachedInputPricePerMillion?: number;
78
- }
79
- /**
80
- * Pricing map for a provider's models.
81
- *
82
- * @example
83
- * ```typescript
84
- * const googlePricing: ProviderPricing = {
85
- * 'gemini-2.5-flash': { inputPricePerMillion: 0.3, outputPricePerMillion: 2.5 },
86
- * 'gemini-2.5-pro': { inputPricePerMillion: 1.25, outputPricePerMillion: 10.0 },
87
- * };
88
- * ```
89
- */
90
- type ProviderPricing = Record<string, ModelPricing>;
91
- /**
92
- * Global pricing configuration.
93
- *
94
- * Allows overriding built-in pricing defaults for any provider/model.
95
- * Used with `configurePricing()` for global overrides or
96
- * `Provider.withPricing()` for provider-level overrides.
97
- *
98
- * @example
99
- * ```typescript
100
- * const config: PricingConfig = {
101
- * providers: {
102
- * google: {
103
- * 'gemini-2.5-flash': { inputPricePerMillion: 0.5, outputPricePerMillion: 3.0 },
104
- * },
105
- * },
106
- * fallback: {
107
- * inputPricePerMillion: 1.0,
108
- * outputPricePerMillion: 5.0,
109
- * },
110
- * };
111
- * ```
112
- */
113
- interface PricingConfig {
114
- providers?: Partial<Record<ProviderType, ProviderPricing>>;
115
- fallback?: ModelPricing;
116
- }
117
- /**
118
- * Parameters for cost calculation.
119
- */
120
- interface CalculateCostParams {
121
- /**
122
- * Total input tokens INCLUDING cached tokens.
123
- * The cost calculator subtracts cachedInputTokens to get non-cached tokens.
124
- */
125
- inputTokens: number;
126
- outputTokens: number;
127
- /**
128
- * Cached input tokens count (optional).
129
- * Must be <= inputTokens. Cached tokens are billed at a lower rate.
130
- */
131
- cachedInputTokens?: number;
132
- model: string;
133
- provider: ProviderType;
134
- }
135
- /**
136
- * Result of cost calculation.
137
- */
138
- interface CostResult {
139
- total: number;
140
- inputCost: number;
141
- outputCost: number;
142
- cachedInputCost: number;
143
- }
144
-
145
- /**
146
- * Standard AI SDK generation parameters that can be set as defaults at the Provider level.
147
- * Per-call parameters override these defaults via simple spread merge.
148
- */
149
- type GenerationOptions = Pick<CallSettings, 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed'>;
150
- /**
151
- * Structural interface matching AI SDK's internal Output<OUTPUT, PARTIAL>.
152
- *
153
- * AI SDK exports `output as Output` (runtime value), not the interface directly.
154
- * We define this compatible interface to enable structural typing.
155
- *
156
- * CRITICAL: Method signatures MUST exactly match AI SDK's internal interface
157
- * for generic type inference to work.
158
- *
159
- * @see AI SDK source: node_modules/ai/dist/index.d.ts lines 572-596
160
- */
161
- interface OutputSpec<OUTPUT = unknown, PARTIAL = unknown> {
162
- responseFormat: PromiseLike<unknown>;
163
- parseCompleteOutput(options: {
164
- text: string;
165
- }, context: {
166
- response: unknown;
167
- usage: unknown;
168
- finishReason: unknown;
169
- }): Promise<OUTPUT>;
170
- parsePartialOutput(options: {
171
- text: string;
172
- }): Promise<{
173
- partial: PARTIAL;
174
- } | undefined>;
175
- }
176
- type DefaultOutput = OutputSpec<string, string>;
177
- type InferOutputComplete<T> = T extends OutputSpec<infer O, unknown> ? O : string;
178
- type GenerateTextResultTyped<TOOLS extends ToolSet, OUTPUT extends OutputSpec> = Awaited<ReturnType<typeof generateText<TOOLS>>> & {
179
- output: InferOutputComplete<OUTPUT> | undefined;
180
- };
181
- type StreamTextResultTyped<TOOLS extends ToolSet, OUTPUT extends OutputSpec> = ReturnType<typeof streamText<TOOLS>> & {
182
- output: Promise<InferOutputComplete<OUTPUT> | undefined>;
183
- };
184
- /**
185
- * Parameters for session.generateText().
186
- * Mirrors AI SDK's generateText() with 'model' excluded (injected by session).
187
- */
188
- type GenerateTextParams<TOOLS extends ToolSet = {}, OUTPUT extends OutputSpec = DefaultOutput> = Omit<Parameters<typeof generateText<TOOLS>>[0], 'model' | 'output'> & {
189
- model?: string;
190
- output?: OUTPUT;
191
- };
192
-
193
- /**
194
- * Parameters for session.streamText().
195
- * Mirrors AI SDK's streamText() with 'model' excluded (injected by session).
196
- */
197
- type StreamTextParams<TOOLS extends ToolSet = {}, OUTPUT extends OutputSpec = DefaultOutput> = Omit<Parameters<typeof streamText<TOOLS>>[0], 'model' | 'output'> & {
198
- model?: string;
199
- output?: OUTPUT;
200
- };
201
-
202
- /**
203
- * @deprecated Use generateText with Output.object instead
204
- */
205
- type GenerateObjectParams = Omit<Parameters<typeof generateObject>[0], 'model'>;
206
-
207
- interface ToolCallSummary {
208
- name: string;
209
- duration?: number;
210
- success: boolean;
211
- error?: string;
212
- }
213
- type LLMCallType = 'generateText' | 'streamText' | 'generateObject' | 'manual';
214
- interface LLMCallRecord {
215
- startTime: number;
216
- endTime: number;
217
- duration: number;
218
- usage: LanguageModelUsage;
219
- type: LLMCallType;
220
- model: string;
221
- provider: ProviderType;
222
- }
223
- /**
224
- * Aggregated summary of all activity within an execution session.
225
- * Used for cost tracking, performance analysis, and metadata reporting.
226
- */
227
- interface AdditionalCost {
228
- type: string;
229
- cost: number;
230
- label?: string;
231
- metadata?: Record<string, unknown>;
232
- timestamp: number;
233
- }
234
- /**
235
- * Internal data structure for SessionSummary constructor.
236
- */
237
- interface SessionSummaryData {
238
- totalLLMUsage: LanguageModelUsage;
239
- llmCalls: LLMCallRecord[];
240
- toolCalls: ToolCallSummary[];
241
- customRecords: Record<string, unknown>[];
242
- llmCost: number;
243
- additionalCosts: AdditionalCost[];
244
- metadata: Record<string, unknown>;
245
- costByModel: Record<string, number>;
246
- }
247
- /**
248
- * Aggregated summary of all activity within an execution session.
249
- * Used for cost tracking, performance analysis, and metadata reporting.
250
- *
251
- * This is an immutable Value Object. All mutation methods return new instances.
252
- */
253
- declare class SessionSummary {
254
- readonly totalLLMUsage: LanguageModelUsage;
255
- readonly llmCallCount: number;
256
- readonly llmCalls: readonly LLMCallRecord[];
257
- readonly toolCalls: readonly ToolCallSummary[];
258
- readonly customRecords: readonly Record<string, unknown>[];
259
- readonly llmCost: number;
260
- readonly additionalCosts: readonly AdditionalCost[];
261
- readonly metadata: Readonly<Record<string, unknown>>;
262
- /** Cost breakdown by model. Key format: `${provider}/${model}` */
263
- readonly costByModel: Readonly<Record<string, number>>;
264
- private readonly startTime;
265
- private constructor();
266
- /**
267
- * Total duration from session start to now (computed dynamically).
268
- */
269
- get totalDuration(): number;
270
- /**
271
- * Creates an empty SessionSummary.
272
- */
273
- static empty(startTime: number): SessionSummary;
274
- /**
275
- * Creates a SessionSummary with custom data for testing purposes.
276
- * @internal For testing only - do not use in production code.
277
- */
278
- static forTest(data: Partial<SessionSummaryData> & {
279
- startTime?: number;
280
- }): SessionSummary;
281
- /**
282
- * Total cost of all additional (non-LLM) operations.
283
- */
284
- get totalAdditionalCost(): number;
285
- /**
286
- * Total cost including LLM and additional costs.
287
- */
288
- get totalCost(): number;
289
- /**
290
- * Returns a new SessionSummary with an LLM call added.
291
- */
292
- withLLMCall(call: LLMCallRecord, newLlmCost: number, newCostByModel: Record<string, number>, newTotalUsage: LanguageModelUsage): SessionSummary;
293
- /**
294
- * Returns a new SessionSummary with an additional cost recorded.
295
- */
296
- withAdditionalCost(cost: AdditionalCost): SessionSummary;
297
- /**
298
- * Returns a new SessionSummary with metadata updated.
299
- */
300
- withMetadata(key: string, value: unknown): SessionSummary;
301
- /**
302
- * Returns a new SessionSummary with a tool call added.
303
- */
304
- withToolCall(call: ToolCallSummary): SessionSummary;
305
- /**
306
- * Returns a new SessionSummary with a custom record added.
307
- */
308
- withCustomRecord(record: Record<string, unknown>): SessionSummary;
309
- /**
310
- * Serializes to plain JSON object for database storage.
311
- */
312
- toJSON(): SessionSummaryJSON;
313
- }
314
- /**
315
- * JSON representation of SessionSummary for database storage.
316
- */
317
- interface SessionSummaryJSON {
318
- totalDuration: number;
319
- totalLLMUsage: LanguageModelUsage;
320
- llmCallCount: number;
321
- llmCalls: LLMCallRecord[];
322
- toolCalls: ToolCallSummary[];
323
- customRecords: Record<string, unknown>[];
324
- llmCost: number;
325
- additionalCosts: AdditionalCost[];
326
- metadata: Record<string, unknown>;
327
- costByModel: Record<string, number>;
328
- totalCost: number;
329
- totalAdditionalCost: number;
330
- }
331
- /**
332
- * Session for tracking LLM calls, tool calls, and custom records.
333
- * Provides AI SDK wrappers with auto-tracking and manual recording methods.
334
- */
335
- interface ExecutionSession {
336
- generateText(params: GenerateTextParams): Promise<Awaited<ReturnType<typeof generateText>>>;
337
- streamText(params: StreamTextParams): ReturnType<typeof streamText>;
338
- generateObject<T>(params: GenerateObjectParams & {
339
- schema: zod.ZodType<T>;
340
- }): Promise<Awaited<ReturnType<typeof generateObject>>>;
341
- recordToolCall(summary: ToolCallSummary): void;
342
- recordLLMCall(record: Omit<LLMCallRecord, 'type'> & {
343
- type?: LLMCallType;
344
- }): void;
345
- record(data: Record<string, unknown>): void;
346
- recordAdditionalCost(cost: Omit<AdditionalCost, 'timestamp'>): void;
347
- setMetadata(key: string, value: unknown): void;
348
- setMetadata(data: Record<string, unknown>): void;
349
- summary(): Promise<SessionSummary>;
350
- }
351
- /**
352
- * Metadata passed to done() and fail() in StreamGeneratorControl.
353
- * Union of SessionSummary and ExecutionMetadata for flexible usage.
354
- */
355
- type DoneMetadata = SessionSummary | ExecutionMetadata;
356
-
357
- /**
358
- * Logger interface for observability.
359
- * All methods are optional - implement only the events you care about.
360
- *
361
- * @example
362
- * ```typescript
363
- * const myLogger: Logger = {
364
- * onLLMCallEnd(event) {
365
- * console.log(`${event.modelId}: ${event.response.duration}ms`);
366
- * },
367
- * onExecutionDone(event) {
368
- * console.log('Total duration:', event.duration);
369
- * },
370
- * };
371
- * ```
372
- */
373
- interface Logger {
374
- onLLMCallStart?(event: LLMCallStartEvent): void;
375
- onLLMCallEnd?(event: LLMCallEndEvent): void;
376
- onExecutionStart?(event: ExecutionStartEvent): void;
377
- onExecutionEmit?<TEvent>(event: ExecutionEmitEvent<TEvent>): void;
378
- onExecutionDone?<TResult>(event: ExecutionDoneEvent<TResult>): void;
379
- onExecutionError?<TResult>(event: ExecutionErrorEvent<TResult>): void;
380
- log?(level: LogLevel, message: string, data?: Record<string, unknown>): void;
381
- }
382
- type LogLevel = 'debug' | 'info' | 'warn' | 'error';
383
- type LLMCallLogType = 'generateText' | 'streamText';
384
- /**
385
- * Event emitted when an LLM call starts.
386
- *
387
- * @example
388
- * ```typescript
389
- * logger.onLLMCallStart?.({
390
- * type: 'llm_call_start',
391
- * callType: 'generateText',
392
- * modelId: 'gemini-2.5-flash',
393
- * timestamp: Date.now(),
394
- * request: { params: { prompt: 'Hello' } },
395
- * });
396
- * ```
397
- */
398
- interface LLMCallStartEvent {
399
- type: 'llm_call_start';
400
- callType: LLMCallLogType;
401
- modelId: string;
402
- timestamp: number;
403
- request: {
404
- params: Record<string, unknown>;
405
- };
406
- }
407
- /**
408
- * Event emitted when an LLM call ends (success or error).
409
- *
410
- * @example Success case:
411
- * ```typescript
412
- * logger.onLLMCallEnd?.({
413
- * type: 'llm_call_end',
414
- * callType: 'generateText',
415
- * modelId: 'gemini-2.5-flash',
416
- * timestamp: Date.now(),
417
- * response: {
418
- * duration: 1500,
419
- * usage: { inputTokens: 100, outputTokens: 50, totalTokens: 150 },
420
- * raw: result,
421
- * },
422
- * });
423
- * ```
424
- *
425
- * @example Error case:
426
- * ```typescript
427
- * logger.onLLMCallEnd?.({
428
- * type: 'llm_call_end',
429
- * callType: 'streamText',
430
- * modelId: 'gpt-4o',
431
- * timestamp: Date.now(),
432
- * response: {
433
- * duration: 500,
434
- * error: new Error('Rate limit exceeded'),
435
- * raw: null,
436
- * },
437
- * });
438
- * ```
439
- */
440
- interface LLMCallEndEvent {
441
- type: 'llm_call_end';
442
- callType: LLMCallLogType;
443
- modelId: string;
444
- timestamp: number;
445
- response: {
446
- duration: number;
447
- usage?: LanguageModelUsage;
448
- raw: unknown;
449
- error?: Error;
450
- };
451
- }
452
- interface ExecutionStartEvent {
453
- type: 'execution_start';
454
- timestamp: number;
455
- }
456
- /**
457
- * Event emitted for each intermediate event during execution.
458
- * @typeParam TEvent - The type of the emitted event (includes metrics)
459
- */
460
- interface ExecutionEmitEvent<TEvent = unknown> {
461
- type: 'execution_emit';
462
- event: TEvent;
463
- }
464
- /**
465
- * Event emitted when execution completes successfully.
466
- * @typeParam TResult - The type of the execution result
467
- */
468
- interface ExecutionDoneEvent<TResult = unknown> {
469
- type: 'execution_done';
470
- timestamp: number;
471
- duration: number;
472
- data: TResult;
473
- summary: SessionSummary;
474
- }
475
- /**
476
- * Event emitted when execution fails with an error.
477
- * @typeParam TResult - The type of partial result data (if available)
478
- */
479
- interface ExecutionErrorEvent<TResult = unknown> {
480
- type: 'execution_error';
481
- timestamp: number;
482
- duration: number;
483
- error: Error;
484
- data?: TResult;
485
- summary?: SessionSummary;
486
- }
487
- /**
488
- * No-op logger (default when no logger provided).
489
- *
490
- * @example
491
- * ```typescript
492
- * const provider = createGoogleProvider({
493
- * apiKey: 'xxx',
494
- * logger: noopLogger,
495
- * });
496
- * ```
497
- */
498
- declare const noopLogger: Logger;
499
- /**
500
- * Helper to create a logger with only the handlers you need.
501
- *
502
- * @example
503
- * ```typescript
504
- * const metricsLogger = createLogger({
505
- * onLLMCallEnd(event) {
506
- * metrics.recordLatency(event.response.duration);
507
- * },
508
- * onExecutionDone(event) {
509
- * metrics.recordTokens(event.summary.totalLLMUsage.totalTokens);
510
- * },
511
- * });
512
- * ```
513
- */
514
- declare function createLogger(handlers: Partial<Logger>): Logger;
515
-
516
- /** Result of uploading a file to a provider's file storage */
517
- interface UploadedFile {
518
- /** Unique identifier from the provider (used for deletion, null for external URLs) */
519
- id: string | null;
520
- /** AI SDK part ready for use in prompts */
521
- part: FilePart | ImagePart;
522
- }
523
- /** Provider-agnostic file manager interface for upload/delete operations */
524
- interface FileManager {
525
- upload(files: FileSource[]): Promise<UploadedFile[]>;
526
- delete(fileId: string): Promise<void>;
527
- clear(): Promise<void>;
528
- getUploadedFiles(): UploadedFile[];
529
- }
530
- /** Cache for uploaded files to prevent duplicate uploads */
531
- interface FileCache {
532
- get(hash: string): UploadedFile | null;
533
- set(hash: string, file: UploadedFile, ttl?: number): void;
534
- delete(hash: string): void;
535
- clear(): void;
536
- }
537
- interface FileManagerOptions {
538
- cache?: FileCache;
539
- }
540
- interface FileSourcePath {
541
- source: 'path';
542
- path: string;
543
- mediaType?: string;
544
- filename?: string;
545
- hash?: string;
546
- }
547
- interface FileSourceData {
548
- source: 'data';
549
- data: Buffer | Uint8Array;
550
- mediaType: string;
551
- filename?: string;
552
- hash?: string;
553
- }
554
- interface FileSourceBase64 {
555
- source: 'base64';
556
- data: string;
557
- mediaType: string;
558
- filename?: string;
559
- hash?: string;
560
- }
561
- interface FileSourceUrl {
562
- source: 'url';
563
- url: string;
564
- mediaType?: string;
565
- filename?: string;
566
- hash?: string;
567
- }
568
- /** Union of all file part types. Use `source` to discriminate. */
569
- type FileSource = FileSourcePath | FileSourceData | FileSourceBase64 | FileSourceUrl;
570
- declare function isFileSource(v: unknown): v is FileSource;
571
- declare function isFileSourcePath(v: FileSource): v is FileSourcePath;
572
- declare function isFileSourceData(v: FileSource): v is FileSourceData;
573
- declare function isFileSourceBase64(v: FileSource): v is FileSourceBase64;
574
- declare function isFileSourceUrl(v: FileSource): v is FileSourceUrl;
575
- /** Provider interface with fluent configuration for AI model operations */
576
- interface Provider {
577
- withDefaultModel(modelId: string): Provider;
578
- withLogger(logger: Logger): Provider;
579
- withPricing(pricing: ProviderPricing): Provider;
580
- /**
581
- * Set default provider-specific options for all LLM calls.
582
- * These options will be deep-merged with per-call providerOptions.
583
- * The actual options type depends on the provider (Google, OpenAI, etc.).
584
- */
585
- withDefaultOptions(options: Record<string, unknown>): Provider;
586
- /**
587
- * Set default generation options (standard AI SDK parameters) for all LLM calls.
588
- * Per-call parameters override these defaults.
589
- */
590
- withDefaultGenerationOptions(options: GenerationOptions): Provider;
591
- streamingExecution<TEvent extends {
592
- type: string;
593
- }>(generator: (session: StreamingSession<TEvent>) => AsyncGenerator<SessionEvent<TEvent>, SessionEvent<TEvent> | Promise<SessionEvent<TEvent>>>, options?: ExecutionOptions): StreamingExecution<TEvent>;
594
- /**
595
- * Execute a non-streaming function with the provider.
596
- * Returns immediately (sync) - execution starts in the background.
597
- *
598
- * Breaking change: Previously returned Promise<Execution<TResult>>.
599
- * Now returns SimpleExecution<TResult> directly (no await needed).
600
- *
601
- * @example
602
- * ```typescript
603
- * // Before (v1.x):
604
- * const execution = provider.simpleExecution(fn);
605
- *
606
- * // After (v2.x):
607
- * const execution = provider.simpleExecution(fn);
608
- * execution.cancel(); // Can cancel in-progress LLM calls
609
- * const result = await execution.result();
610
- * ```
611
- */
612
- simpleExecution<TResult>(fn: (session: SimpleSession) => Promise<TResult>, options?: ExecutionOptions): SimpleExecution<TResult>;
613
- }
614
-
615
- /**
616
- * Provider-specific options type.
617
- * Maps provider names (e.g., 'google', 'openai') to their option objects.
618
- */
619
- type ProviderOptions$1 = Record<string, Record<string, unknown>>;
620
- interface SimpleSessionOptions {
621
- defaultLanguageModel?: LanguageModel | null;
622
- modelFactory?: (modelId: string) => LanguageModel;
623
- providerType: ProviderType;
624
- providerPricing?: ProviderPricing;
625
- fileManager: FileManager;
626
- logger?: Logger;
627
- startTime?: number;
628
- /**
629
- * AbortSignal for cancelling AI SDK calls.
630
- * When aborted, ongoing generateText/streamText calls will be cancelled.
631
- */
632
- signal?: AbortSignal;
633
- /**
634
- * Default provider-specific options to apply to all LLM calls.
635
- * These will be deep-merged with per-call providerOptions (per-call takes precedence).
636
- */
637
- defaultProviderOptions?: ProviderOptions$1;
638
- /**
639
- * Default tools to apply to all LLM calls (e.g., google_search, url_context).
640
- * These will be merged with per-call tools (per-call takes precedence).
641
- */
642
- defaultTools?: ToolSet;
643
- /**
644
- * Default generation options (standard AI SDK parameters) for all LLM calls.
645
- * Per-call parameters override these defaults via simple spread.
646
- */
647
- defaultGenerationOptions?: GenerationOptions;
648
- }
649
- declare class SimpleSession {
650
- private readonly defaultLanguageModel;
651
- private readonly modelFactory;
652
- private readonly providerType;
653
- private readonly providerPricing;
654
- private readonly defaultProviderOptions;
655
- private readonly defaultTools;
656
- private readonly defaultGenerationOptions;
657
- private readonly _fileManager;
658
- private readonly logger;
659
- private readonly sessionStartTime;
660
- private readonly signal?;
661
- private summary;
662
- private readonly pendingUsagePromises;
663
- private readonly onDoneFns;
664
- constructor(options: SimpleSessionOptions);
665
- private getModel;
666
- private extractModelId;
667
- generateText<TOOLS extends ToolSet = {}, OUTPUT extends OutputSpec = DefaultOutput>(params: GenerateTextParams<TOOLS, OUTPUT>): Promise<GenerateTextResultTyped<TOOLS, OUTPUT>>;
668
- streamText<TOOLS extends ToolSet = {}, OUTPUT extends OutputSpec = DefaultOutput>(params: StreamTextParams<TOOLS, OUTPUT>): StreamTextResultTyped<TOOLS, OUTPUT>;
669
- get fileManager(): FileManager;
670
- record(data: Record<string, unknown>): void;
671
- recordToolCall(toolCallSummary: ToolCallSummary): void;
672
- recordLLMCall(record: Omit<LLMCallRecord, 'type'> & {
673
- type?: LLMCallType;
674
- }): void;
675
- recordAdditionalCost(cost: Omit<AdditionalCost, 'timestamp'>): void;
676
- setMetadata(key: string, value: unknown): void;
677
- setMetadata(data: Record<string, unknown>): void;
678
- private updateSummaryWithLLMCall;
679
- onDone(fn: () => Promise<void> | void): void;
680
- runOnDoneHooks(): Promise<void>;
681
- getSummary(): Promise<SessionSummary>;
682
- /**
683
- * Notifies Logger of execution start.
684
- * @internal Called by SimpleExecutionHost - not intended for direct use.
685
- */
686
- notifyExecutionStart(): void;
687
- /**
688
- * Notifies Logger of execution completion with result data and summary.
689
- * @param data - The execution result data
690
- * @param startTime - Execution start timestamp for duration calculation
691
- * @internal Called by SimpleExecutionHost - not intended for direct use.
692
- */
693
- notifyExecutionDone<T>(data: T, startTime: number): Promise<void>;
694
- /**
695
- * Notifies Logger of execution error with error details and summary (if available).
696
- * Gracefully handles getSummary() failures - summary will be undefined if it fails.
697
- * @param error - The error that occurred
698
- * @param startTime - Execution start timestamp for duration calculation
699
- * @internal Called by SimpleExecutionHost - not intended for direct use.
700
- */
701
- notifyExecutionError(error: Error, startTime: number): Promise<void>;
702
- protected get _logger(): Logger;
703
- protected get _startTime(): number;
704
- protected get _modelId(): string;
705
- }
706
-
707
- type ProviderOptions = Record<string, Record<string, unknown>>;
708
- interface StreamingSessionOptions {
709
- defaultLanguageModel?: LanguageModel | null;
710
- modelFactory?: (modelId: string) => LanguageModel;
711
- providerType: ProviderType;
712
- providerPricing?: ProviderPricing;
713
- fileManager: FileManager;
714
- logger?: Logger;
715
- startTime?: number;
716
- signal?: AbortSignal;
717
- defaultProviderOptions?: ProviderOptions;
718
- defaultTools?: ToolSet;
719
- defaultGenerationOptions?: GenerationOptions;
720
- }
721
- declare class StreamingSession<TEvent extends {
722
- type: string;
723
- }> extends SimpleSession {
724
- private lastEventTime;
725
- private _terminated;
726
- constructor(options: StreamingSessionOptions);
727
- /**
728
- * Emits a streaming event with automatically attached metrics.
729
- *
730
- * Reserved types ('complete', 'error') throw at runtime - use session.done()
731
- * or session.fail() instead.
732
- *
733
- * @param event - The event to emit (metrics will be added automatically)
734
- * @returns The complete event with metrics attached
735
- * @throws Error when attempting to emit reserved types ('complete', 'error')
736
- */
737
- emit(event: EmittableEventInput<TEvent>): SessionEvent<TEvent>;
738
- /**
739
- * Internal emit method - bypasses reserved type check.
740
- * Used by done() and fail() to emit terminal events.
741
- */
742
- private emitInternal;
743
- /**
744
- * Signals successful completion of the streaming execution.
745
- * Emits a 'complete' event with the result data and session summary.
746
- * Also triggers Logger.onExecutionDone for observability.
747
- * @param data - The final result data
748
- * @returns The complete event with data and summary
749
- */
750
- done(data: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>>;
751
- /**
752
- * Signals that the streaming execution failed with an error.
753
- * Emits an 'error' event and triggers Logger.onExecutionError for observability.
754
- * Gracefully handles getSummary() failures - summary will be undefined if it fails.
755
- * @param error - The error that caused the failure
756
- * @param data - Optional partial result data (if any was produced before failure)
757
- * @returns The error event
758
- */
759
- fail(error: Error, data?: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>>;
760
- private createMetrics;
761
- }
762
- interface StreamingSessionInternal<TEvent extends {
763
- type: string;
764
- }> {
765
- generateText: SimpleSession['generateText'];
766
- streamText: SimpleSession['streamText'];
767
- fileManager: FileManager;
768
- onDone: SimpleSession['onDone'];
769
- record: SimpleSession['record'];
770
- recordToolCall: SimpleSession['recordToolCall'];
771
- emit(event: EmittableEventInput<TEvent>): SessionEvent<TEvent>;
772
- done(data: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>>;
773
- fail(error: Error, data?: ExtractResult<TEvent>): Promise<SessionEvent<TEvent>>;
774
- runOnDoneHooks(): Promise<void>;
775
- getSummary(): Promise<SessionSummary>;
776
- }
777
- interface CreateStreamingSessionOptions {
778
- defaultLanguageModel: LanguageModel;
779
- providerType: ProviderType;
780
- fileManager: FileManager;
781
- logger?: Logger;
782
- startTime?: number;
783
- signal?: AbortSignal;
784
- }
785
- declare function createStreamingSession<TEvent extends {
786
- type: string;
787
- }>(options: CreateStreamingSessionOptions): StreamingSessionInternal<TEvent>;
788
-
789
- /**
790
- * Agent execution types for @agtlantis/core.
791
- * Provides abstractions for streaming and non-streaming agent execution.
792
- */
793
-
794
- /**
795
- * Distributive version of Omit that properly handles union types.
796
- *
797
- * Standard `Omit<A | B, K>` loses unique properties from union members.
798
- * `DistributiveOmit<A | B, K>` preserves them by distributing over the union.
799
- *
800
- * @example
801
- * ```typescript
802
- * type A = { type: 'a'; foo: string; metrics: EventMetrics };
803
- * type B = { type: 'b'; bar: number; metrics: EventMetrics };
804
- * type Union = A | B;
805
- *
806
- * // ❌ Standard Omit - loses foo and bar
807
- * type Bad = Omit<Union, 'metrics'>;
808
- * // Result: { type: 'a' | 'b' }
809
- *
810
- * // ✅ DistributiveOmit - preserves unique properties
811
- * type Good = DistributiveOmit<Union, 'metrics'>;
812
- * // Result: { type: 'a'; foo: string } | { type: 'b'; bar: number }
813
- * ```
814
- */
815
- type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
816
- /**
817
- * Adds `metrics: EventMetrics` to event types.
818
- * The framework uses this internally to wrap user-defined events with timing info.
819
- *
820
- * **For most use cases, you don't need this type.** Simply define your events
821
- * without metrics, and the framework handles the wrapping automatically.
822
- *
823
- * **When you need SessionEvent:**
824
- * - Creating mock/stub streaming executions for testing
825
- * - Explicitly typing `StreamingResult.events` arrays
826
- *
827
- * @example
828
- * ```typescript
829
- * // User defines pure event types (recommended)
830
- * type MyEvent =
831
- * | { type: 'progress'; step: string }
832
- * | { type: 'complete'; data: string };
833
- *
834
- * // Framework internally wraps as SessionEvent<MyEvent>
835
- * // StreamingResult.events returns SessionEvent<MyEvent>[]
836
- *
837
- * // Testing: Create mock events with explicit metrics
838
- * const mockEvents: SessionEvent<MyEvent>[] = [
839
- * { type: 'progress', step: 'loading', metrics: { timestamp: Date.now(), elapsedMs: 0, deltaMs: 0 } },
840
- * ];
841
- * ```
842
- */
843
- type SessionEvent<T extends {
844
- type: string;
845
- }> = T & {
846
- metrics: EventMetrics;
847
- };
848
- /**
849
- * Input type for session.emit() - removes metrics from event types.
850
- * Uses DistributiveOmit to properly handle union types.
851
- *
852
- * @example
853
- * ```typescript
854
- * type MyAgentEvent = SessionEvent<ProgressEvent | CompleteEvent | ErrorEvent>;
855
- *
856
- * // For emit input, metrics is not required
857
- * type EmitInput = SessionEventInput<MyAgentEvent>;
858
- *
859
- * // Usage in session.emit()
860
- * session.emit({ type: 'progress', step: 'reading', message: 'Loading...' });
861
- * // No casting needed!
862
- * ```
863
- */
864
- /**
865
- * @deprecated TEvent no longer requires metrics constraint - use TEvent directly
866
- * This type is kept for backwards compatibility during migration
867
- */
868
- type SessionEventInput<T extends {
869
- type: string;
870
- }> = T;
871
- /**
872
- * Reserved event types that cannot be emitted directly via session.emit().
873
- * These types are controlled internally by session.done() and session.fail().
874
- */
875
- type ReservedEventType = 'complete' | 'error';
876
- /**
877
- * Input type for emit() - excludes reserved event types.
878
- * Users define pure domain events; framework adds metrics wrapper.
879
- */
880
- type EmittableEventInput<T extends {
881
- type: string;
882
- }> = T extends {
883
- type: ReservedEventType;
884
- } ? never : T;
885
- /**
886
- * Completion event emitted by session.done().
887
- * Include this in your event union to define the result type.
888
- *
889
- * @example
890
- * ```typescript
891
- * type MyEvent =
892
- * | { type: 'progress'; step: string }
893
- * | CompletionEvent<MyResult>;
894
- *
895
- * // session.done(result) emits { type: 'complete', data: result, summary }
896
- * ```
897
- */
898
- type CompletionEvent<TResult> = {
899
- type: 'complete';
900
- data: TResult;
901
- summary: SessionSummary;
902
- };
903
- /**
904
- * Error event emitted by session.fail().
905
- * Auto-added to stream() return type — users don't need to include this in their event union.
906
- *
907
- * @example
908
- * ```typescript
909
- * for await (const event of execution.stream()) {
910
- * if (event.type === 'error') {
911
- * console.error(event.error.message);
912
- * }
913
- * }
914
- * ```
915
- */
916
- type ErrorEvent = {
917
- type: 'error';
918
- error: Error;
919
- summary?: SessionSummary;
920
- data?: unknown;
921
- };
922
- /**
923
- * Extract the result type from an event union containing CompletionEvent<T>.
924
- * Returns `never` if no CompletionEvent member exists (making session.done() uncallable).
925
- *
926
- * @example
927
- * ```typescript
928
- * type MyEvent =
929
- * | { type: 'progress'; step: string }
930
- * | CompletionEvent<{ answer: string }>;
931
- *
932
- * type Result = ExtractResult<MyEvent>;
933
- * // Result = { answer: string }
934
- * ```
935
- */
936
- type ExtractResult<TEvent extends {
937
- type: string;
938
- }> = Extract<TEvent, {
939
- type: 'complete';
940
- }> extends {
941
- data: infer R;
942
- } ? R : never;
943
- /**
944
- * Options for execution.
945
- * Used by both simpleExecution and streamingExecution.
946
- */
947
- interface ExecutionOptions {
948
- /**
949
- * AbortSignal for cancellation.
950
- * Combined with internal AbortController - both can trigger cancellation.
951
- *
952
- * @example
953
- * ```typescript
954
- * const controller = new AbortController();
955
- *
956
- * // Pass signal to execution
957
- * const execution = provider.simpleExecution(fn, { signal: controller.signal });
958
- *
959
- * // Cancel externally
960
- * setTimeout(() => controller.abort(), 5000);
961
- *
962
- * // Or use execution.cancel() directly
963
- * execution.cancel();
964
- * ```
965
- */
966
- signal?: AbortSignal;
967
- }
968
- /**
969
- * Status of an execution after completion.
970
- * - `succeeded`: Execution completed normally with a result
971
- * - `failed`: Execution threw an error
972
- * - `canceled`: Execution was canceled via cancel() or AbortSignal
973
- */
974
- type ExecutionStatus = 'succeeded' | 'failed' | 'canceled';
975
- /**
976
- * Discriminated union representing the outcome of an execution.
977
- * Summary is always available, regardless of execution status.
978
- *
979
- * @typeParam T - The result type on success
980
- *
981
- * @example
982
- * ```typescript
983
- * const result = await execution.result();
984
- *
985
- * if (result.status === 'succeeded') {
986
- * console.log(result.value);
987
- * } else if (result.status === 'failed') {
988
- * console.error(result.error);
989
- * }
990
- *
991
- * // Summary always available
992
- * console.log(`Cost: $${result.summary.totalCost}`);
993
- * ```
994
- */
995
- type ExecutionResult<T> = {
996
- status: 'succeeded';
997
- value: T;
998
- summary: SessionSummary;
999
- } | {
1000
- status: 'failed';
1001
- error: Error;
1002
- summary: SessionSummary;
1003
- } | {
1004
- status: 'canceled';
1005
- summary: SessionSummary;
1006
- };
1007
- /**
1008
- * Result type for SimpleExecution.
1009
- * Alias for ExecutionResult for clarity in type annotations.
1010
- */
1011
- type SimpleResult<T> = ExecutionResult<T>;
1012
- /**
1013
- * Result type for StreamingExecution.
1014
- * Extends ExecutionResult with readonly events array.
1015
- * Events are always available, even on failure or cancellation.
1016
- *
1017
- * @typeParam TEvent - Event type
1018
- * @typeParam T - Result type on success
1019
- *
1020
- * @example
1021
- * ```typescript
1022
- * const result = await execution.result();
1023
- *
1024
- * // Events always available, regardless of status
1025
- * console.log(`Received ${result.events.length} events`);
1026
- *
1027
- * if (result.status === 'succeeded') {
1028
- * console.log(result.value);
1029
- * }
1030
- * ```
1031
- */
1032
- type StreamingResult<TEvent, T> = ExecutionResult<T> & {
1033
- readonly events: readonly TEvent[];
1034
- };
1035
- /**
1036
- * Base interface for all execution types.
1037
- * Both streaming and non-streaming executions implement this interface,
1038
- * enabling unified handling at outer layers.
1039
- *
1040
- * @typeParam TResult - The final result type
1041
- *
1042
- * @example
1043
- * ```typescript
1044
- * // Option 1: Automatic cleanup with await using (recommended)
1045
- * await using execution = agent.execute(input);
1046
- * const result = await execution.result();
1047
- * if (result.status === 'succeeded') {
1048
- * console.log(result.value, result.summary.totalCost);
1049
- * }
1050
- * // cleanup() called automatically on scope exit
1051
- *
1052
- * // Option 2: Manual cleanup with try/finally
1053
- * const execution = agent.execute(input);
1054
- * try {
1055
- * const result = await execution.result();
1056
- * } finally {
1057
- * await execution.cleanup();
1058
- * }
1059
- * ```
1060
- */
1061
- interface Execution<TResult> extends AsyncDisposable {
1062
- /**
1063
- * Get the execution result with status and summary.
1064
- * Returns a discriminated union that always includes the summary,
1065
- * regardless of whether execution succeeded, failed, or was canceled.
1066
- *
1067
- * For streaming executions, this waits for all events to complete.
1068
- *
1069
- * @example
1070
- * ```typescript
1071
- * const result = await execution.result();
1072
- *
1073
- * if (result.status === 'succeeded') {
1074
- * console.log(result.value);
1075
- * } else if (result.status === 'failed') {
1076
- * console.error(result.error);
1077
- * }
1078
- *
1079
- * // Summary always available
1080
- * console.log(`Cost: $${result.summary.totalCost}`);
1081
- * ```
1082
- */
1083
- result(): Promise<ExecutionResult<TResult>>;
1084
- /**
1085
- * Request cancellation of the execution.
1086
- * Aborts the current operation if in progress.
1087
- * Works even if custom signal was provided (signals are combined).
1088
- *
1089
- * No-op if execution already completed.
1090
- */
1091
- cancel(): void;
1092
- /**
1093
- * Cleanup resources (uploaded files, connections, etc.).
1094
- * Should always be called after execution, even on error.
1095
- * Safe to call multiple times.
1096
- */
1097
- cleanup(): Promise<void>;
1098
- /**
1099
- * Async disposal for `await using` syntax (TS 5.2+).
1100
- * Delegates to cleanup().
1101
- */
1102
- [Symbol.asyncDispose](): Promise<void>;
1103
- }
1104
- /**
1105
- * Simple (non-streaming) execution.
1106
- * Starts eagerly on construction - execution begins immediately.
1107
- *
1108
- * @typeParam TResult - The final result type
1109
- *
1110
- * @example
1111
- * ```typescript
1112
- * // Start execution (sync - no await, starts immediately)
1113
- * const execution = provider.simpleExecution(async (session) => {
1114
- * const response = await session.generateText({ prompt: 'Hello' });
1115
- * return response.text;
1116
- * });
1117
- *
1118
- * // Cancel if needed
1119
- * setTimeout(() => execution.cancel(), 5000);
1120
- *
1121
- * // Get result (status-based, never throws)
1122
- * const result = await execution.result();
1123
- *
1124
- * if (result.status === 'succeeded') {
1125
- * console.log(result.value);
1126
- * } else if (result.status === 'canceled') {
1127
- * console.log('Execution was canceled');
1128
- * }
1129
- *
1130
- * // Summary always available
1131
- * console.log(`Cost: $${result.summary.totalCost}`);
1132
- * ```
1133
- */
1134
- interface SimpleExecution<TResult> extends Execution<TResult> {
1135
- /**
1136
- * Get the execution result with status and summary.
1137
- *
1138
- * @example
1139
- * ```typescript
1140
- * const execution = provider.simpleExecution(async (session) => {
1141
- * const response = await session.generateText({ prompt: 'Hello' });
1142
- * return response.text;
1143
- * });
1144
- *
1145
- * const result = await execution.result();
1146
- *
1147
- * if (result.status === 'succeeded') {
1148
- * console.log(result.value);
1149
- * } else if (result.status === 'failed') {
1150
- * console.error(result.error);
1151
- * }
1152
- *
1153
- * // Summary always available
1154
- * console.log(`Cost: $${result.summary.totalCost}`);
1155
- * ```
1156
- */
1157
- result(): Promise<SimpleResult<TResult>>;
1158
- }
1159
- /**
1160
- * Represents a streaming execution that emits events as they occur.
1161
- * TEvent is the user's pure domain event type (without metrics).
1162
- * stream() and result() return SessionEvent<TEvent> which includes metrics.
1163
- */
1164
- interface StreamingExecution<TEvent extends {
1165
- type: string;
1166
- }> extends Execution<ExtractResult<TEvent>> {
1167
- /**
1168
- * Get the event stream.
1169
- * Returns an AsyncIterable that yields all events with metrics:
1170
- * - Events already in the buffer (from eager execution)
1171
- * - Real-time events as they occur
1172
- * - ErrorEvent is auto-included — no need to add it to your event union
1173
- *
1174
- * Can be called multiple times - each call replays buffered events.
1175
- * After execution completes, replays all events from buffer.
1176
- *
1177
- * @example
1178
- * ```typescript
1179
- * type MyEvent =
1180
- * | { type: 'progress'; step: number }
1181
- * | CompletionEvent<MyResult>;
1182
- *
1183
- * const execution = provider.streamingExecution<MyEvent>(...);
1184
- *
1185
- * for await (const event of execution.stream()) {
1186
- * // event is SessionEvent<MyEvent | ErrorEvent>
1187
- * console.log(`[${event.metrics.elapsedMs}ms] ${event.type}`);
1188
- * }
1189
- * ```
1190
- */
1191
- stream(): AsyncIterable<SessionEvent<TEvent | ErrorEvent>>;
1192
- /**
1193
- * Get the execution result with status, summary, and all events.
1194
- *
1195
- * @example
1196
- * ```typescript
1197
- * const result = await execution.result();
1198
- *
1199
- * // Events always available
1200
- * console.log(`Received ${result.events.length} events`);
1201
- *
1202
- * if (result.status === 'succeeded') {
1203
- * console.log(result.value);
1204
- * }
1205
- *
1206
- * console.log(`Cost: $${result.summary.totalCost}`);
1207
- * ```
1208
- */
1209
- result(): Promise<StreamingResult<SessionEvent<TEvent | ErrorEvent>, ExtractResult<TEvent>>>;
1210
- }
1211
- /**
1212
- * Generator function type for streaming executions.
1213
- * TEvent is the user's pure domain event type (without metrics).
1214
- * The generator yields SessionEvent<TEvent> which includes metrics.
1215
- */
1216
- type SessionStreamGeneratorFn<TEvent extends {
1217
- type: string;
1218
- }> = (session: StreamingSession<TEvent>) => AsyncGenerator<SessionEvent<TEvent>, SessionEvent<TEvent> | Promise<SessionEvent<TEvent>> | undefined, unknown>;
1219
-
1220
- /**
1221
- * Abstract base class for AI providers.
1222
- *
1223
- * Provides common streamingExecution and simpleExecution implementation.
1224
- * Subclasses implement session creation and fluent configuration methods.
1225
- */
1226
- declare abstract class BaseProvider implements Provider {
1227
- /**
1228
- * Create a SimpleSession for non-streaming execution.
1229
- * @param signal - AbortSignal for cancellation support
1230
- */
1231
- protected abstract createSimpleSession(signal?: AbortSignal): SimpleSession;
1232
- /**
1233
- * Create a StreamingSession for streaming execution.
1234
- * @param signal - AbortSignal for cancellation support
1235
- */
1236
- protected abstract createStreamingSession<TEvent extends {
1237
- type: string;
1238
- }>(signal?: AbortSignal): StreamingSession<TEvent>;
1239
- abstract withDefaultModel(modelId: string): Provider;
1240
- abstract withLogger(logger: Logger): Provider;
1241
- abstract withPricing(pricing: ProviderPricing): Provider;
1242
- abstract withDefaultOptions(options: Record<string, unknown>): Provider;
1243
- abstract withDefaultGenerationOptions(options: GenerationOptions): Provider;
1244
- streamingExecution<TEvent extends {
1245
- type: string;
1246
- }>(generator: (session: StreamingSession<TEvent>) => AsyncGenerator<SessionEvent<TEvent>, SessionEvent<TEvent> | Promise<SessionEvent<TEvent>>>, options?: ExecutionOptions): StreamingExecution<TEvent>;
1247
- /**
1248
- * Execute a non-streaming function with cancellation support.
1249
- * Returns immediately - execution starts in the background.
1250
- */
1251
- simpleExecution<TResult>(fn: (session: SimpleSession) => Promise<TResult>, options?: ExecutionOptions): SimpleExecution<TResult>;
1252
- }
1253
-
1254
- export { isFileSourceData as $, type LLMCallStartEvent as A, BaseProvider as B, type CalculateCostParams as C, type DistributiveOmit as D, type ErrorEvent as E, type FileSource as F, type GenerationOptions as G, type LLMCallEndEvent as H, type ExecutionStartEvent as I, type ExecutionEmitEvent as J, type ExecutionDoneEvent as K, type Logger as L, type ModelPricing as M, type ExecutionErrorEvent as N, noopLogger as O, type ProviderType as P, createLogger as Q, type ReservedEventType as R, type StreamingExecution as S, type Provider as T, type UploadedFile as U, type FileSourcePath as V, type FileSourceData as W, type FileSourceBase64 as X, type FileSourceUrl as Y, isFileSource as Z, isFileSourcePath as _, type PricingConfig as a, isFileSourceBase64 as a0, isFileSourceUrl as a1, type SimpleSessionOptions as a2, createStreamingSession as a3, type StreamingSessionOptions as a4, type CreateStreamingSessionOptions as a5, type StreamingSessionInternal as a6, type OutputSpec as a7, type DefaultOutput as a8, type InferOutputComplete as a9, type GenerateTextResultTyped as aa, type StreamTextResultTyped as ab, type GenerateTextParams as ac, type GenerateObjectParams as ad, type ToolCallSummary as ae, type LLMCallType as af, type LLMCallRecord as ag, type AdditionalCost as ah, SessionSummary as ai, type SessionSummaryJSON as aj, type ExecutionSession as ak, type DoneMetadata as al, type ProviderPricing as b, type CostResult as c, StreamingSession as d, type SessionStreamGeneratorFn as e, type SessionEvent as f, type StreamingResult as g, type ExtractResult as h, type SimpleExecution as i, SimpleSession as j, type SimpleResult as k, type ExecutionStatus as l, type CompletionEvent as m, type StreamTextParams as n, type FileCache as o, type FileManager as p, type FileManagerOptions as q, type Execution as r, type ExecutionOptions as s, type ExecutionResult as t, type SessionEventInput as u, type EmittableEventInput as v, type EventMetrics as w, type ExecutionMetadata as x, type LogLevel as y, type LLMCallLogType as z };