@agtlantis/core 0.5.0 → 0.5.1

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 (265) hide show
  1. package/dist/errors/index.d.ts +4 -0
  2. package/dist/errors/index.d.ts.map +1 -0
  3. package/dist/errors/index.js +3 -0
  4. package/dist/errors/index.js.map +1 -0
  5. package/dist/errors/types.d.ts +69 -0
  6. package/dist/errors/types.d.ts.map +1 -0
  7. package/dist/errors/types.js +119 -0
  8. package/dist/errors/types.js.map +1 -0
  9. package/dist/errors/utils.d.ts +17 -0
  10. package/dist/errors/utils.d.ts.map +1 -0
  11. package/dist/errors/utils.js +16 -0
  12. package/dist/errors/utils.js.map +1 -0
  13. package/dist/execution/constants.d.ts +7 -0
  14. package/dist/execution/constants.d.ts.map +1 -0
  15. package/dist/execution/constants.js +7 -0
  16. package/dist/execution/constants.js.map +1 -0
  17. package/dist/execution/index.d.ts +8 -0
  18. package/dist/execution/index.d.ts.map +1 -0
  19. package/dist/execution/index.js +7 -0
  20. package/dist/execution/index.js.map +1 -0
  21. package/dist/execution/mapping.d.ts +17 -0
  22. package/dist/execution/mapping.d.ts.map +1 -0
  23. package/dist/execution/mapping.js +197 -0
  24. package/dist/execution/mapping.js.map +1 -0
  25. package/dist/execution/shared.d.ts +86 -0
  26. package/dist/execution/shared.d.ts.map +1 -0
  27. package/dist/execution/shared.js +100 -0
  28. package/dist/execution/shared.js.map +1 -0
  29. package/dist/execution/simple-host.d.ts +56 -0
  30. package/dist/execution/simple-host.d.ts.map +1 -0
  31. package/dist/execution/simple-host.js +126 -0
  32. package/dist/execution/simple-host.js.map +1 -0
  33. package/dist/execution/streaming-host.d.ts +79 -0
  34. package/dist/execution/streaming-host.d.ts.map +1 -0
  35. package/dist/execution/streaming-host.js +276 -0
  36. package/dist/execution/streaming-host.js.map +1 -0
  37. package/dist/execution/testing/fixtures.d.ts +67 -0
  38. package/dist/execution/testing/fixtures.d.ts.map +1 -0
  39. package/dist/execution/testing/fixtures.js +145 -0
  40. package/dist/execution/testing/fixtures.js.map +1 -0
  41. package/dist/execution/testing/helpers.d.ts +218 -0
  42. package/dist/execution/testing/helpers.d.ts.map +1 -0
  43. package/dist/execution/testing/helpers.js +327 -0
  44. package/dist/execution/testing/helpers.js.map +1 -0
  45. package/dist/execution/testing/host-configs.d.ts +56 -0
  46. package/dist/execution/testing/host-configs.d.ts.map +1 -0
  47. package/dist/execution/testing/host-configs.js +154 -0
  48. package/dist/execution/testing/host-configs.js.map +1 -0
  49. package/dist/execution/testing/vitest-assertions.d.ts +102 -0
  50. package/dist/execution/testing/vitest-assertions.d.ts.map +1 -0
  51. package/dist/execution/testing/vitest-assertions.js +142 -0
  52. package/dist/execution/testing/vitest-assertions.js.map +1 -0
  53. package/dist/execution/types.d.ts +432 -0
  54. package/dist/execution/types.d.ts.map +1 -0
  55. package/dist/execution/types.js +2 -0
  56. package/dist/execution/types.js.map +1 -0
  57. package/dist/execution/utils.d.ts +68 -0
  58. package/dist/execution/utils.d.ts.map +1 -0
  59. package/dist/execution/utils.js +93 -0
  60. package/dist/execution/utils.js.map +1 -0
  61. package/dist/index.d.ts +10 -1506
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +9 -2979
  64. package/dist/index.js.map +1 -1
  65. package/dist/observability/index.d.ts +4 -0
  66. package/dist/observability/index.d.ts.map +1 -0
  67. package/dist/observability/index.js +2 -0
  68. package/dist/observability/index.js.map +1 -0
  69. package/dist/observability/logger.d.ts +161 -0
  70. package/dist/observability/logger.d.ts.map +1 -0
  71. package/dist/observability/logger.js +31 -0
  72. package/dist/observability/logger.js.map +1 -0
  73. package/dist/observability/types.d.ts +46 -0
  74. package/dist/observability/types.d.ts.map +1 -0
  75. package/dist/observability/types.js +2 -0
  76. package/dist/observability/types.js.map +1 -0
  77. package/dist/patterns/index.d.ts +2 -0
  78. package/dist/patterns/index.d.ts.map +1 -0
  79. package/dist/patterns/index.js +2 -0
  80. package/dist/patterns/index.js.map +1 -0
  81. package/dist/patterns/progressive/index.d.ts +2 -0
  82. package/dist/patterns/progressive/index.d.ts.map +1 -0
  83. package/dist/patterns/progressive/index.js +2 -0
  84. package/dist/patterns/progressive/index.js.map +1 -0
  85. package/dist/patterns/progressive/progressive-pattern.d.ts +174 -0
  86. package/dist/patterns/progressive/progressive-pattern.d.ts.map +1 -0
  87. package/dist/patterns/progressive/progressive-pattern.js +260 -0
  88. package/dist/patterns/progressive/progressive-pattern.js.map +1 -0
  89. package/dist/pricing/calculator.d.ts +71 -0
  90. package/dist/pricing/calculator.d.ts.map +1 -0
  91. package/dist/pricing/calculator.js +127 -0
  92. package/dist/pricing/calculator.js.map +1 -0
  93. package/dist/pricing/config.d.ts +61 -0
  94. package/dist/pricing/config.d.ts.map +1 -0
  95. package/dist/pricing/config.js +87 -0
  96. package/dist/pricing/config.js.map +1 -0
  97. package/dist/pricing/defaults.d.ts +29 -0
  98. package/dist/pricing/defaults.d.ts.map +1 -0
  99. package/dist/pricing/defaults.js +139 -0
  100. package/dist/pricing/defaults.js.map +1 -0
  101. package/dist/pricing/index.d.ts +40 -0
  102. package/dist/pricing/index.d.ts.map +1 -0
  103. package/dist/pricing/index.js +43 -0
  104. package/dist/pricing/index.js.map +1 -0
  105. package/dist/pricing/types.d.ts +96 -0
  106. package/dist/pricing/types.d.ts.map +1 -0
  107. package/dist/pricing/types.js +7 -0
  108. package/dist/pricing/types.js.map +1 -0
  109. package/dist/pricing/validator.d.ts +55 -0
  110. package/dist/pricing/validator.d.ts.map +1 -0
  111. package/dist/pricing/validator.js +84 -0
  112. package/dist/pricing/validator.js.map +1 -0
  113. package/dist/prompt/errors.d.ts +112 -0
  114. package/dist/prompt/errors.d.ts.map +1 -0
  115. package/dist/prompt/errors.js +175 -0
  116. package/dist/prompt/errors.js.map +1 -0
  117. package/dist/prompt/file-prompt-repository.d.ts +80 -0
  118. package/dist/prompt/file-prompt-repository.d.ts.map +1 -0
  119. package/dist/prompt/file-prompt-repository.js +287 -0
  120. package/dist/prompt/file-prompt-repository.js.map +1 -0
  121. package/dist/prompt/index.d.ts +34 -0
  122. package/dist/prompt/index.d.ts.map +1 -0
  123. package/dist/prompt/index.js +37 -0
  124. package/dist/prompt/index.js.map +1 -0
  125. package/dist/prompt/prompt-template.d.ts +64 -0
  126. package/dist/prompt/prompt-template.d.ts.map +1 -0
  127. package/dist/prompt/prompt-template.js +90 -0
  128. package/dist/prompt/prompt-template.js.map +1 -0
  129. package/dist/prompt/template.d.ts +23 -0
  130. package/dist/prompt/template.d.ts.map +1 -0
  131. package/dist/prompt/template.js +70 -0
  132. package/dist/prompt/template.js.map +1 -0
  133. package/dist/prompt/types.d.ts +148 -0
  134. package/dist/prompt/types.d.ts.map +1 -0
  135. package/dist/prompt/types.js +7 -0
  136. package/dist/prompt/types.js.map +1 -0
  137. package/dist/provider/base-provider.d.ts +41 -0
  138. package/dist/provider/base-provider.d.ts.map +1 -0
  139. package/dist/provider/base-provider.js +21 -0
  140. package/dist/provider/base-provider.js.map +1 -0
  141. package/dist/provider/file-cache.d.ts +14 -0
  142. package/dist/provider/file-cache.d.ts.map +1 -0
  143. package/dist/provider/file-cache.js +29 -0
  144. package/dist/provider/file-cache.js.map +1 -0
  145. package/dist/provider/file-source.d.ts +32 -0
  146. package/dist/provider/file-source.d.ts.map +1 -0
  147. package/dist/provider/file-source.js +180 -0
  148. package/dist/provider/file-source.js.map +1 -0
  149. package/dist/provider/google/factory.d.ts +107 -0
  150. package/dist/provider/google/factory.d.ts.map +1 -0
  151. package/dist/provider/google/factory.js +143 -0
  152. package/dist/provider/google/factory.js.map +1 -0
  153. package/dist/provider/google/file-manager.d.ts +14 -0
  154. package/dist/provider/google/file-manager.d.ts.map +1 -0
  155. package/dist/provider/google/file-manager.js +183 -0
  156. package/dist/provider/google/file-manager.js.map +1 -0
  157. package/dist/provider/google/index.d.ts +8 -0
  158. package/dist/provider/google/index.d.ts.map +1 -0
  159. package/dist/provider/google/index.js +10 -0
  160. package/dist/provider/google/index.js.map +1 -0
  161. package/dist/provider/hash.d.ts +3 -0
  162. package/dist/provider/hash.d.ts.map +1 -0
  163. package/dist/provider/hash.js +34 -0
  164. package/dist/provider/hash.js.map +1 -0
  165. package/dist/provider/index.d.ts +9 -0
  166. package/dist/provider/index.d.ts.map +1 -0
  167. package/dist/provider/index.js +11 -0
  168. package/dist/provider/index.js.map +1 -0
  169. package/dist/provider/noop-file-manager.d.ts +9 -0
  170. package/dist/provider/noop-file-manager.d.ts.map +1 -0
  171. package/dist/provider/noop-file-manager.js +28 -0
  172. package/dist/provider/noop-file-manager.js.map +1 -0
  173. package/dist/provider/openai/factory.d.ts +67 -0
  174. package/dist/provider/openai/factory.d.ts.map +1 -0
  175. package/dist/provider/openai/factory.js +95 -0
  176. package/dist/provider/openai/factory.js.map +1 -0
  177. package/dist/provider/openai/index.d.ts +7 -0
  178. package/dist/provider/openai/index.d.ts.map +1 -0
  179. package/dist/provider/openai/index.js +7 -0
  180. package/dist/provider/openai/index.js.map +1 -0
  181. package/dist/provider/types.d.ts +105 -0
  182. package/dist/provider/types.d.ts.map +1 -0
  183. package/dist/provider/types.js +19 -0
  184. package/dist/provider/types.js.map +1 -0
  185. package/dist/session/index.d.ts +7 -0
  186. package/dist/session/index.d.ts.map +1 -0
  187. package/dist/session/index.js +5 -0
  188. package/dist/session/index.js.map +1 -0
  189. package/dist/session/simple-session.d.ts +98 -0
  190. package/dist/session/simple-session.d.ts.map +1 -0
  191. package/dist/session/simple-session.js +299 -0
  192. package/dist/session/simple-session.js.map +1 -0
  193. package/dist/session/streaming-session.d.ts +90 -0
  194. package/dist/session/streaming-session.d.ts.map +1 -0
  195. package/dist/session/streaming-session.js +151 -0
  196. package/dist/session/streaming-session.js.map +1 -0
  197. package/dist/session/test-utils.d.ts +19 -0
  198. package/dist/session/test-utils.d.ts.map +1 -0
  199. package/dist/session/test-utils.js +65 -0
  200. package/dist/session/test-utils.js.map +1 -0
  201. package/dist/session/types.d.ts +219 -0
  202. package/dist/session/types.d.ts.map +1 -0
  203. package/dist/session/types.js +181 -0
  204. package/dist/session/types.js.map +1 -0
  205. package/dist/session/usage-extractors.d.ts +7 -0
  206. package/dist/session/usage-extractors.d.ts.map +1 -0
  207. package/dist/session/usage-extractors.js +71 -0
  208. package/dist/session/usage-extractors.js.map +1 -0
  209. package/dist/testing/fixtures.d.ts +34 -0
  210. package/dist/testing/fixtures.d.ts.map +1 -0
  211. package/dist/testing/fixtures.js +65 -0
  212. package/dist/testing/fixtures.js.map +1 -0
  213. package/dist/testing/helpers.d.ts +20 -0
  214. package/dist/testing/helpers.d.ts.map +1 -0
  215. package/dist/testing/helpers.js +32 -0
  216. package/dist/testing/helpers.js.map +1 -0
  217. package/dist/testing/index.d.ts +7 -519
  218. package/dist/testing/index.d.ts.map +1 -0
  219. package/dist/testing/index.js +21 -2123
  220. package/dist/testing/index.js.map +1 -1
  221. package/dist/testing/mock-provider.d.ts +79 -0
  222. package/dist/testing/mock-provider.d.ts.map +1 -0
  223. package/dist/testing/mock-provider.js +152 -0
  224. package/dist/testing/mock-provider.js.map +1 -0
  225. package/dist/testing/mock.d.ts +29 -0
  226. package/dist/testing/mock.d.ts.map +1 -0
  227. package/dist/testing/mock.js +154 -0
  228. package/dist/testing/mock.js.map +1 -0
  229. package/dist/testing/test-execution.d.ts +14 -0
  230. package/dist/testing/test-execution.d.ts.map +1 -0
  231. package/dist/testing/test-execution.js +108 -0
  232. package/dist/testing/test-execution.js.map +1 -0
  233. package/dist/utils/deep-merge.d.ts +6 -0
  234. package/dist/utils/deep-merge.d.ts.map +1 -0
  235. package/dist/utils/deep-merge.js +24 -0
  236. package/dist/utils/deep-merge.js.map +1 -0
  237. package/dist/validation/errors.d.ts +28 -0
  238. package/dist/validation/errors.d.ts.map +1 -0
  239. package/dist/validation/errors.js +39 -0
  240. package/dist/validation/errors.js.map +1 -0
  241. package/dist/validation/index.d.ts +5 -0
  242. package/dist/validation/index.d.ts.map +1 -0
  243. package/dist/validation/index.js +4 -0
  244. package/dist/validation/index.js.map +1 -0
  245. package/dist/validation/types.d.ts +49 -0
  246. package/dist/validation/types.d.ts.map +1 -0
  247. package/dist/validation/types.js +2 -0
  248. package/dist/validation/types.js.map +1 -0
  249. package/dist/validation/validation-history.d.ts +12 -0
  250. package/dist/validation/validation-history.d.ts.map +1 -0
  251. package/dist/validation/validation-history.js +29 -0
  252. package/dist/validation/validation-history.js.map +1 -0
  253. package/dist/validation/with-validation.d.ts +38 -0
  254. package/dist/validation/with-validation.d.ts.map +1 -0
  255. package/dist/validation/with-validation.js +58 -0
  256. package/dist/validation/with-validation.js.map +1 -0
  257. package/package.json +72 -76
  258. package/dist/base-provider-2TTw5HAa.d.cts +0 -1254
  259. package/dist/base-provider-2TTw5HAa.d.ts +0 -1254
  260. package/dist/index.cjs +0 -3085
  261. package/dist/index.cjs.map +0 -1
  262. package/dist/index.d.cts +0 -1506
  263. package/dist/testing/index.cjs +0 -2167
  264. package/dist/testing/index.cjs.map +0 -1
  265. package/dist/testing/index.d.cts +0 -520
@@ -0,0 +1,260 @@
1
+ import { hasToolCall, tool } from 'ai';
2
+ import { z } from 'zod';
3
+ const TOOL_DESCRIPTIONS = {
4
+ reportProgress: '[OPTIONAL] Report progress during task execution. Use this to show intermediate work. You may call this multiple times, then you MUST call tools::submitResult.',
5
+ submitResult: '[REQUIRED] Submit the final result. You MUST call this exactly once to complete the task. Without this call, the task FAILS.',
6
+ };
7
+ export const TOOL_CALLING_PROTOCOL = `## CRITICAL INSTRUCTION - READ CAREFULLY
8
+
9
+ You have 2 tools available:
10
+ 1. reportProgress - [OPTIONAL] Show intermediate work (multiple times)
11
+ 2. submitResult - [REQUIRED] Submit your final answer
12
+
13
+ ⚠️ IMPORTANT RULES:
14
+ - You may call reportProgress 0-3 times to show progress
15
+ - You MUST call submitResult exactly once to complete the task
16
+ - After calling reportProgress, you MUST call submitResult in your NEXT response
17
+ - If you call reportProgress more than 3 times without submitResult, the task FAILS
18
+ - The task is NOT complete until submitResult is called
19
+
20
+ CORRECT SEQUENCE:
21
+ 1. [Optional] reportProgress
22
+ 2. [Required] submitResult (exactly once)
23
+
24
+ ❌ WRONG: reportProgress → reportProgress → reportProgress → reportProgress (no submitResult = FAIL)
25
+ ✅ CORRECT: reportProgress → submitResult (SUCCESS)`;
26
+ /**
27
+ * Creates a progressive pattern for streaming LLM responses with intermediate progress updates.
28
+ *
29
+ * The pattern automatically:
30
+ * - Injects `reportProgress` and `submitResult` tools
31
+ * - Stops when `submitResult` is called (via `hasToolCall('submitResult')`)
32
+ * - Appends protocol instructions to the system prompt
33
+ *
34
+ * @example Basic usage
35
+ * ```typescript
36
+ * const pattern = defineProgressivePattern({
37
+ * progressSchema: z.object({ stage: z.string(), message: z.string() }),
38
+ * resultSchema: z.object({ summary: z.string(), score: z.number() }),
39
+ * });
40
+ *
41
+ * for await (const event of pattern.run(provider, {
42
+ * system: 'You are an analyzer.',
43
+ * prompt: 'Analyze this...',
44
+ * })) {
45
+ * console.log(event.type, event.data);
46
+ * }
47
+ * ```
48
+ *
49
+ * @example With custom stopWhen (add step limit)
50
+ * ```typescript
51
+ * import { stepCountIs } from 'ai';
52
+ *
53
+ * for await (const event of pattern.run(provider, {
54
+ * prompt: 'Analyze...',
55
+ * stopWhen: stepCountIs(10), // Stop at submitResult OR after 10 steps
56
+ * })) { ... }
57
+ * ```
58
+ *
59
+ * @example With custom protocol
60
+ * ```typescript
61
+ * for await (const event of pattern.run(provider, {
62
+ * prompt: 'Analyze...',
63
+ * protocol: 'Call reportProgress for each step, then submitResult.',
64
+ * })) { ... }
65
+ * ```
66
+ *
67
+ * @example Composable (within a session)
68
+ * ```typescript
69
+ * provider.streamingExecution(async function*(session) {
70
+ * yield* pattern.runInSession(session, {
71
+ * system: 'You are an analyzer.',
72
+ * messages: [...],
73
+ * });
74
+ * });
75
+ * ```
76
+ */
77
+ export function defineProgressivePattern(config) {
78
+ return new ProgressivePattern(config.progressSchema, config.resultSchema);
79
+ }
80
+ export class ProgressivePattern {
81
+ progressSchema;
82
+ resultSchema;
83
+ constructor(progressSchema, resultSchema) {
84
+ this.progressSchema = progressSchema;
85
+ this.resultSchema = resultSchema;
86
+ }
87
+ lastParseError = null;
88
+ /**
89
+ * Runs the pattern within an existing session. Use this for composing
90
+ * multiple patterns or when you need fine-grained control over the session.
91
+ *
92
+ * @param session - The streaming session to run within
93
+ * @param options - Stream options including:
94
+ * - `stopWhen` - Additional stop conditions (combined with default `hasToolCall('submitResult')`)
95
+ * - `protocol` - Custom protocol instructions (replaces default `TOOL_CALLING_PROTOCOL`)
96
+ * - All other `streamText` options except `tools`, `toolChoice`, `stopWhen`
97
+ *
98
+ * @example Basic usage
99
+ * ```typescript
100
+ * provider.streamingExecution(async function*(session) {
101
+ * yield* pattern.runInSession(session, {
102
+ * system: 'You are an analyzer.',
103
+ * messages: [{ role: 'user', content: 'Analyze...' }],
104
+ * });
105
+ * });
106
+ * ```
107
+ *
108
+ * @example With custom stopWhen
109
+ * ```typescript
110
+ * yield* pattern.runInSession(session, {
111
+ * prompt: 'Analyze...',
112
+ * stopWhen: stepCountIs(5), // Combined: submitResult OR 5 steps
113
+ * });
114
+ * ```
115
+ */
116
+ async *runInSession(session, options) {
117
+ const { tools: userTools, system, stopWhen: userStopWhen, protocol, ...restOptions } = options;
118
+ const internalTools = this.createTools();
119
+ const allTools = { ...userTools, ...internalTools };
120
+ const systemString = typeof system === 'string' ? system : undefined;
121
+ const fullSystem = this.renderSystemPrompt(systemString, protocol);
122
+ const defaultStopCondition = hasToolCall('submitResult');
123
+ const stopConditions = this.combineStopConditions(defaultStopCondition, userStopWhen);
124
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
125
+ const stream = session.streamText({
126
+ ...restOptions,
127
+ system: fullSystem,
128
+ tools: allTools,
129
+ toolChoice: 'required',
130
+ stopWhen: stopConditions,
131
+ });
132
+ let result = null;
133
+ for await (const part of stream.fullStream) {
134
+ if (part.type === 'tool-call') {
135
+ if (part.toolName === 'reportProgress') {
136
+ const input = 'input' in part ? part.input : undefined;
137
+ const progressData = this.parseProgressInput(input);
138
+ if (progressData !== null) {
139
+ // Cast required: TypeScript can't know that TEvent includes a 'progress' variant
140
+ yield session.emit({
141
+ type: 'progress',
142
+ data: progressData,
143
+ });
144
+ }
145
+ }
146
+ else if (part.toolName === 'submitResult') {
147
+ const input = 'input' in part ? part.input : undefined;
148
+ result = this.parseResultInput(input);
149
+ }
150
+ }
151
+ }
152
+ if (result === null) {
153
+ const baseMsg = 'ProgressivePattern: No result received.';
154
+ const detail = this.lastParseError
155
+ ? ` Last parse error: ${this.lastParseError.message}`
156
+ : ' The LLM did not call submitResult tool.';
157
+ throw new Error(baseMsg + detail);
158
+ }
159
+ const completeEvent = await session.done(result);
160
+ yield completeEvent;
161
+ return completeEvent;
162
+ }
163
+ /**
164
+ * Standalone execution that creates a new session internally.
165
+ * Use this for simple, single-pattern executions.
166
+ *
167
+ * @param provider - The AI provider to use
168
+ * @param options - Stream options including:
169
+ * - `stopWhen` - Additional stop conditions (combined with default `hasToolCall('submitResult')`)
170
+ * - `protocol` - Custom protocol instructions (replaces default `TOOL_CALLING_PROTOCOL`)
171
+ *
172
+ * @example Basic usage
173
+ * ```typescript
174
+ * for await (const event of pattern.run(provider, {
175
+ * system: 'You are an analyzer.',
176
+ * prompt: 'Analyze this document...',
177
+ * })) {
178
+ * if (event.type === 'progress') {
179
+ * console.log('Progress:', event.data);
180
+ * } else if (event.type === 'complete') {
181
+ * console.log('Result:', event.data);
182
+ * }
183
+ * }
184
+ * ```
185
+ *
186
+ * @example With step limit
187
+ * ```typescript
188
+ * import { stepCountIs } from 'ai';
189
+ *
190
+ * for await (const event of pattern.run(provider, {
191
+ * prompt: 'Analyze...',
192
+ * stopWhen: stepCountIs(10),
193
+ * })) { ... }
194
+ * ```
195
+ */
196
+ run(provider, options) {
197
+ const self = this;
198
+ const execution = provider.streamingExecution(async function* (session) {
199
+ return yield* self.runInSession(session, options);
200
+ });
201
+ return execution.stream();
202
+ }
203
+ createTools() {
204
+ return {
205
+ reportProgress: tool({
206
+ description: TOOL_DESCRIPTIONS.reportProgress,
207
+ inputSchema: z.object({
208
+ data: this.progressSchema,
209
+ }),
210
+ execute: async () => ({
211
+ status: 'progress_recorded',
212
+ instruction: 'After all progress reports, you MUST call tools::submitResult to complete the task.',
213
+ }),
214
+ }),
215
+ submitResult: tool({
216
+ description: TOOL_DESCRIPTIONS.submitResult,
217
+ inputSchema: z.object({
218
+ data: this.resultSchema,
219
+ }),
220
+ execute: async () => ({
221
+ status: 'result_submitted',
222
+ message: 'Task completed successfully.',
223
+ }),
224
+ }),
225
+ };
226
+ }
227
+ parseJsonWrapper(input, schema) {
228
+ try {
229
+ if (!input || typeof input !== 'object')
230
+ return null;
231
+ const wrapper = input;
232
+ if (wrapper.data === undefined)
233
+ return null;
234
+ const parsed = typeof wrapper.data === 'string' ? JSON.parse(wrapper.data) : wrapper.data;
235
+ return schema.parse(parsed);
236
+ }
237
+ catch (error) {
238
+ this.lastParseError = error instanceof Error ? error : new Error(String(error));
239
+ return null;
240
+ }
241
+ }
242
+ parseProgressInput(input) {
243
+ return this.parseJsonWrapper(input, this.progressSchema);
244
+ }
245
+ parseResultInput(input) {
246
+ return this.parseJsonWrapper(input, this.resultSchema);
247
+ }
248
+ combineStopConditions(defaultCondition, userConditions) {
249
+ if (!userConditions) {
250
+ return [defaultCondition];
251
+ }
252
+ const userArray = Array.isArray(userConditions) ? userConditions : [userConditions];
253
+ return [defaultCondition, ...userArray];
254
+ }
255
+ renderSystemPrompt(userSystem, protocol) {
256
+ const protocolText = protocol ?? TOOL_CALLING_PROTOCOL;
257
+ return userSystem ? `${userSystem}\n\n${protocolText}` : protocolText;
258
+ }
259
+ }
260
+ //# sourceMappingURL=progressive-pattern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"progressive-pattern.js","sourceRoot":"","sources":["../../../src/patterns/progressive/progressive-pattern.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,WAAW,EAAE,IAAI,EAAE,M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AAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC;QACpF,OAAO,CAAC,gBAAgB,EAAE,GAAG,SAAS,CAAC,CAAC;IAAA,CAC3C;IAEO,kBAAkB,CAAC,UAAmB,EAAE,QAAiB,EAAU;QACvE,MAAM,YAAY,GAAG,QAAQ,IAAI,qBAAqB,CAAC;QACvD,OAAO,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IAAA,CACzE;CACJ"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Cost calculation functions.
3
+ *
4
+ * @module pricing/calculator
5
+ *
6
+ * NOTE: Cost calculations use standard JavaScript floating-point arithmetic.
7
+ * For high-volume usage tracking, accumulated totals may have minor precision drift.
8
+ * For financial reporting, consider rounding results to appropriate decimal places
9
+ * (e.g., `Math.round(cost * 100) / 100` for cents).
10
+ */
11
+ import type { LanguageModelUsage } from 'ai';
12
+ import type { CalculateCostParams, CostResult, ModelPricing, ProviderPricing, ProviderType } from './types.js';
13
+ /**
14
+ * Get pricing for a specific model.
15
+ *
16
+ * Resolution order:
17
+ * 1. Provider-level config (providerPricing param)
18
+ * 2. Global config (configurePricing)
19
+ * 3. Built-in defaults
20
+ * 4. Fallback pricing
21
+ */
22
+ export declare function getModelPricing(model: string, provider: ProviderType, providerPricing?: ProviderPricing): ModelPricing;
23
+ /**
24
+ * Calculate cost from token counts.
25
+ *
26
+ * @throws Error if token counts are negative, non-finite, or if cachedInputTokens > inputTokens
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const cost = calculateCost({
31
+ * inputTokens: 1000,
32
+ * outputTokens: 500,
33
+ * cachedInputTokens: 200,
34
+ * model: 'gemini-2.5-flash',
35
+ * provider: 'google',
36
+ * });
37
+ * console.log(cost.total); // 0.000315
38
+ * ```
39
+ */
40
+ export declare function calculateCost(params: CalculateCostParams, providerPricing?: ProviderPricing): CostResult;
41
+ /**
42
+ * Calculate cost from AI SDK LanguageModelUsage.
43
+ *
44
+ * Convenience function that extracts token counts from the
45
+ * AI SDK's LanguageModelUsage type and calculates the cost.
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const usage = await result.usage;
50
+ * const cost = calculateCostFromUsage(usage, 'gemini-2.5-flash', 'google');
51
+ * ```
52
+ */
53
+ export declare function calculateCostFromUsage(usage: LanguageModelUsage, model: string, provider: ProviderType, providerPricing?: ProviderPricing): CostResult;
54
+ /**
55
+ * Calculate total cost for multiple LLM calls.
56
+ *
57
+ * Aggregates costs from multiple calls, grouping by model.
58
+ *
59
+ * @returns Object with:
60
+ * - `totalCost`: Sum of all call costs in USD
61
+ * - `costByModel`: Map where key format is `${provider}/${model}`
62
+ */
63
+ export declare function calculateTotalCost(calls: Array<{
64
+ usage: LanguageModelUsage;
65
+ model: string;
66
+ provider: ProviderType;
67
+ }>, providerPricing?: ProviderPricing): {
68
+ totalCost: number;
69
+ costByModel: Record<string, number>;
70
+ };
71
+ //# sourceMappingURL=calculator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculator.d.ts","sourceRoot":"","sources":["../../src/pricing/calculator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAC7C,OAAO,KAAK,EACV,mBAAmB,EACnB,UAAU,EACV,YAAY,EACZ,eAAe,EACf,YAAY,EACb,MAAM,YAAY,CAAC;AAMpB;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,YAAY,EACtB,eAAe,CAAC,EAAE,eAAe,GAChC,YAAY,CAoBd;AAsBD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,mBAAmB,EAC3B,eAAe,CAAC,EAAE,eAAe,GAChC,UAAU,CA8BZ;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,kBAAkB,EACzB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,YAAY,EACtB,eAAe,CAAC,EAAE,eAAe,GAChC,UAAU,CAWZ;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,KAAK,CAAC;IACX,KAAK,EAAE,kBAAkB,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,YAAY,CAAC;CACxB,CAAC,EACF,eAAe,CAAC,EAAE,eAAe,GAChC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,CAkB5D"}
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Cost calculation functions.
3
+ *
4
+ * @module pricing/calculator
5
+ *
6
+ * NOTE: Cost calculations use standard JavaScript floating-point arithmetic.
7
+ * For high-volume usage tracking, accumulated totals may have minor precision drift.
8
+ * For financial reporting, consider rounding results to appropriate decimal places
9
+ * (e.g., `Math.round(cost * 100) / 100` for cents).
10
+ */
11
+ import { DEFAULT_PRICING_CONFIG, DEFAULT_FALLBACK_PRICING } from './defaults.js';
12
+ import { getPricingConfig } from './config.js';
13
+ const TOKENS_PER_MILLION = 1_000_000;
14
+ /**
15
+ * Get pricing for a specific model.
16
+ *
17
+ * Resolution order:
18
+ * 1. Provider-level config (providerPricing param)
19
+ * 2. Global config (configurePricing)
20
+ * 3. Built-in defaults
21
+ * 4. Fallback pricing
22
+ */
23
+ export function getModelPricing(model, provider, providerPricing) {
24
+ if (providerPricing?.[model]) {
25
+ return providerPricing[model];
26
+ }
27
+ const globalConfig = getPricingConfig();
28
+ if (globalConfig?.providers?.[provider]?.[model]) {
29
+ return globalConfig.providers[provider][model];
30
+ }
31
+ const defaultProviderPricing = DEFAULT_PRICING_CONFIG.providers[provider];
32
+ if (defaultProviderPricing?.[model]) {
33
+ return defaultProviderPricing[model];
34
+ }
35
+ return (globalConfig?.fallback ??
36
+ DEFAULT_PRICING_CONFIG.fallback ??
37
+ DEFAULT_FALLBACK_PRICING);
38
+ }
39
+ function validateCostParams(params) {
40
+ const { inputTokens, outputTokens, cachedInputTokens = 0 } = params;
41
+ if (inputTokens < 0 || outputTokens < 0 || cachedInputTokens < 0) {
42
+ throw new Error('Token counts must be non-negative');
43
+ }
44
+ if (cachedInputTokens > inputTokens) {
45
+ throw new Error('cachedInputTokens cannot exceed inputTokens');
46
+ }
47
+ if (!Number.isFinite(inputTokens) ||
48
+ !Number.isFinite(outputTokens) ||
49
+ !Number.isFinite(cachedInputTokens)) {
50
+ throw new Error('Token counts must be finite numbers');
51
+ }
52
+ }
53
+ /**
54
+ * Calculate cost from token counts.
55
+ *
56
+ * @throws Error if token counts are negative, non-finite, or if cachedInputTokens > inputTokens
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const cost = calculateCost({
61
+ * inputTokens: 1000,
62
+ * outputTokens: 500,
63
+ * cachedInputTokens: 200,
64
+ * model: 'gemini-2.5-flash',
65
+ * provider: 'google',
66
+ * });
67
+ * console.log(cost.total); // 0.000315
68
+ * ```
69
+ */
70
+ export function calculateCost(params, providerPricing) {
71
+ validateCostParams(params);
72
+ const { inputTokens, outputTokens, cachedInputTokens = 0, model, provider, } = params;
73
+ const pricing = getModelPricing(model, provider, providerPricing);
74
+ const nonCachedInputTokens = inputTokens - cachedInputTokens;
75
+ const inputCost = (nonCachedInputTokens / TOKENS_PER_MILLION) * pricing.inputPricePerMillion;
76
+ const outputCost = (outputTokens / TOKENS_PER_MILLION) * pricing.outputPricePerMillion;
77
+ const cachedInputPricePerMillion = pricing.cachedInputPricePerMillion ?? pricing.inputPricePerMillion;
78
+ const cachedInputCost = (cachedInputTokens / TOKENS_PER_MILLION) * cachedInputPricePerMillion;
79
+ return {
80
+ total: inputCost + outputCost + cachedInputCost,
81
+ inputCost,
82
+ outputCost,
83
+ cachedInputCost,
84
+ };
85
+ }
86
+ /**
87
+ * Calculate cost from AI SDK LanguageModelUsage.
88
+ *
89
+ * Convenience function that extracts token counts from the
90
+ * AI SDK's LanguageModelUsage type and calculates the cost.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const usage = await result.usage;
95
+ * const cost = calculateCostFromUsage(usage, 'gemini-2.5-flash', 'google');
96
+ * ```
97
+ */
98
+ export function calculateCostFromUsage(usage, model, provider, providerPricing) {
99
+ return calculateCost({
100
+ inputTokens: usage.inputTokens ?? 0,
101
+ outputTokens: usage.outputTokens ?? 0,
102
+ cachedInputTokens: usage.inputTokenDetails?.cacheReadTokens ?? 0,
103
+ model,
104
+ provider,
105
+ }, providerPricing);
106
+ }
107
+ /**
108
+ * Calculate total cost for multiple LLM calls.
109
+ *
110
+ * Aggregates costs from multiple calls, grouping by model.
111
+ *
112
+ * @returns Object with:
113
+ * - `totalCost`: Sum of all call costs in USD
114
+ * - `costByModel`: Map where key format is `${provider}/${model}`
115
+ */
116
+ export function calculateTotalCost(calls, providerPricing) {
117
+ const costByModel = {};
118
+ let totalCost = 0;
119
+ for (const call of calls) {
120
+ const cost = calculateCostFromUsage(call.usage, call.model, call.provider, providerPricing);
121
+ totalCost += cost.total;
122
+ const key = `${call.provider}/${call.model}`;
123
+ costByModel[key] = (costByModel[key] ?? 0) + cost.total;
124
+ }
125
+ return { totalCost, costByModel };
126
+ }
127
+ //# sourceMappingURL=calculator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculator.js","sourceRoot":"","sources":["../../src/pricing/calculator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAUH,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,kBAAkB,GAAG,SAAS,CAAC;AAErC;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAC7B,KAAa,EACb,QAAsB,EACtB,eAAiC,E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kBAAkB,CAChC,KAIE,EACF,eAAiC,EAC2B;IAC5D,MAAM,WAAW,GAA2B,EAAE,CAAC;IAC/C,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,sBAAsB,CACjC,IAAI,CAAC,KAAK,EACV,IAAI,CAAC,KAAK,EACV,IAAI,CAAC,QAAQ,EACb,eAAe,CAChB,CAAC;QACF,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC;QAExB,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QAC7C,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC;IAC1D,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AAAA,CACnC"}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Global pricing configuration.
3
+ *
4
+ * Priority order (highest to lowest):
5
+ * 1. Provider.withPricing() - per-provider override
6
+ * 2. configurePricing() - global override
7
+ * 3. Built-in defaults (defaults.ts)
8
+ * 4. Fallback pricing
9
+ *
10
+ * @module pricing/config
11
+ */
12
+ import type { ModelPricing, PricingConfig, ProviderType } from './types.js';
13
+ /**
14
+ * Configure global pricing overrides.
15
+ *
16
+ * WARNING: This uses global mutable state and is not thread-safe.
17
+ * For multi-tenant scenarios or concurrent requests with different pricing,
18
+ * use `Provider.withPricing()` instead for proper isolation.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * configurePricing({
23
+ * providers: {
24
+ * google: {
25
+ * 'gemini-2.5-flash': { inputPricePerMillion: 0.5, outputPricePerMillion: 3.0 },
26
+ * },
27
+ * },
28
+ * });
29
+ *
30
+ * // Reset to built-in defaults
31
+ * configurePricing(undefined);
32
+ * ```
33
+ */
34
+ export declare function configurePricing(config: PricingConfig | undefined): void;
35
+ export declare function getPricingConfig(): PricingConfig | undefined;
36
+ /**
37
+ * Reset global pricing configuration.
38
+ * Useful for testing to ensure clean state between tests.
39
+ */
40
+ export declare function resetPricingConfig(): void;
41
+ export type PricingSource = 'global' | 'default' | 'fallback';
42
+ export interface EffectivePricingResult {
43
+ pricing: ModelPricing;
44
+ source: PricingSource;
45
+ }
46
+ /**
47
+ * Get effective pricing for a model with source information.
48
+ * Useful for debugging to understand which pricing layer is applied.
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * const result = getEffectivePricing('gemini-2.5-flash', 'google');
53
+ * console.log(result.source); // 'default' (using built-in pricing)
54
+ *
55
+ * configurePricing({ providers: { google: { 'gemini-2.5-flash': {...} } } });
56
+ * const result2 = getEffectivePricing('gemini-2.5-flash', 'google');
57
+ * console.log(result2.source); // 'global' (using configured override)
58
+ * ```
59
+ */
60
+ export declare function getEffectivePricing(model: string, provider: ProviderType): EffectivePricingResult;
61
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/pricing/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAM5E;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS,GAAG,IAAI,CAKxE;AAED,wBAAgB,gBAAgB,IAAI,aAAa,GAAG,SAAS,CAE5D;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC;AAED,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAE9D,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,YAAY,CAAC;IACtB,MAAM,EAAE,aAAa,CAAC;CACvB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,YAAY,GACrB,sBAAsB,CAuBxB"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Global pricing configuration.
3
+ *
4
+ * Priority order (highest to lowest):
5
+ * 1. Provider.withPricing() - per-provider override
6
+ * 2. configurePricing() - global override
7
+ * 3. Built-in defaults (defaults.ts)
8
+ * 4. Fallback pricing
9
+ *
10
+ * @module pricing/config
11
+ */
12
+ import { validatePricingConfig } from './validator.js';
13
+ import { DEFAULT_PRICING_CONFIG, DEFAULT_FALLBACK_PRICING } from './defaults.js';
14
+ let globalConfig;
15
+ /**
16
+ * Configure global pricing overrides.
17
+ *
18
+ * WARNING: This uses global mutable state and is not thread-safe.
19
+ * For multi-tenant scenarios or concurrent requests with different pricing,
20
+ * use `Provider.withPricing()` instead for proper isolation.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * configurePricing({
25
+ * providers: {
26
+ * google: {
27
+ * 'gemini-2.5-flash': { inputPricePerMillion: 0.5, outputPricePerMillion: 3.0 },
28
+ * },
29
+ * },
30
+ * });
31
+ *
32
+ * // Reset to built-in defaults
33
+ * configurePricing(undefined);
34
+ * ```
35
+ */
36
+ export function configurePricing(config) {
37
+ if (config) {
38
+ validatePricingConfig(config);
39
+ }
40
+ globalConfig = config;
41
+ }
42
+ export function getPricingConfig() {
43
+ return globalConfig;
44
+ }
45
+ /**
46
+ * Reset global pricing configuration.
47
+ * Useful for testing to ensure clean state between tests.
48
+ */
49
+ export function resetPricingConfig() {
50
+ globalConfig = undefined;
51
+ }
52
+ /**
53
+ * Get effective pricing for a model with source information.
54
+ * Useful for debugging to understand which pricing layer is applied.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const result = getEffectivePricing('gemini-2.5-flash', 'google');
59
+ * console.log(result.source); // 'default' (using built-in pricing)
60
+ *
61
+ * configurePricing({ providers: { google: { 'gemini-2.5-flash': {...} } } });
62
+ * const result2 = getEffectivePricing('gemini-2.5-flash', 'google');
63
+ * console.log(result2.source); // 'global' (using configured override)
64
+ * ```
65
+ */
66
+ export function getEffectivePricing(model, provider) {
67
+ if (globalConfig?.providers?.[provider]?.[model]) {
68
+ return {
69
+ pricing: globalConfig.providers[provider][model],
70
+ source: 'global',
71
+ };
72
+ }
73
+ const defaultPricing = DEFAULT_PRICING_CONFIG.providers[provider];
74
+ if (defaultPricing?.[model]) {
75
+ return {
76
+ pricing: defaultPricing[model],
77
+ source: 'default',
78
+ };
79
+ }
80
+ return {
81
+ pricing: globalConfig?.fallback ??
82
+ DEFAULT_PRICING_CONFIG.fallback ??
83
+ DEFAULT_FALLBACK_PRICING,
84
+ source: 'fallback',
85
+ };
86
+ }
87
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/pricing/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEjF,IAAI,YAAuC,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAiC,EAAQ;IACxE,IAAI,MAAM,EAAE,CAAC;QACX,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAChC,CAAC;IACD,YAAY,GAAG,MAAM,CAAC;AAAA,CACvB;AAED,MAAM,UAAU,gBAAgB,GAA8B;IAC5D,OAAO,YAAY,CAAC;AAAA,CACrB;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,GAAS;IACzC,YAAY,GAAG,SAAS,CAAC;AAAA,CAC1B;AASD;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,mBAAmB,CACjC,KAAa,EACb,QAAsB,EACE;IACxB,IAAI,YAAY,EAAE,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,OAAO;YACL,OAAO,EAAE,YAAY,CAAC,SAAS,CAAC,QAAQ,CAAE,CAAC,KAAK,CAAC;YACjD,MAAM,EAAE,QAAQ;SACjB,CAAC;IACJ,CAAC;IAED,MAAM,cAAc,GAAG,sBAAsB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAClE,IAAI,cAAc,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO;YACL,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC;YAC9B,MAAM,EAAE,SAAS;SAClB,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO,EACL,YAAY,EAAE,QAAQ;YACtB,sBAAsB,CAAC,QAAQ;YAC/B,wBAAwB;QAC1B,MAAM,EAAE,UAAU;KACnB,CAAC;AAAA,CACH"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Built-in pricing tables (USD per million tokens).
3
+ *
4
+ * These are the default prices for common models. They can be overridden
5
+ * using `configurePricing()` (global) or `Provider.withPricing()` (per-provider).
6
+ *
7
+ * Last updated: January 2025
8
+ *
9
+ * @module pricing/defaults
10
+ */
11
+ import type { ModelPricing, PricingConfig, ProviderPricing } from './types.js';
12
+ /**
13
+ * OpenAI model pricing.
14
+ * @see https://openai.com/pricing
15
+ */
16
+ export declare const OPENAI_PRICING: ProviderPricing;
17
+ /**
18
+ * Google Gemini model pricing.
19
+ * @see https://ai.google.dev/gemini-api/docs/pricing
20
+ */
21
+ export declare const GOOGLE_PRICING: ProviderPricing;
22
+ /**
23
+ * Anthropic Claude model pricing.
24
+ * @see https://www.anthropic.com/pricing
25
+ */
26
+ export declare const ANTHROPIC_PRICING: ProviderPricing;
27
+ export declare const DEFAULT_PRICING_CONFIG: Required<PricingConfig>;
28
+ export declare const DEFAULT_FALLBACK_PRICING: ModelPricing;
29
+ //# sourceMappingURL=defaults.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/pricing/defaults.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE/E;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,eAoB5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,eA0C5B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,iBAAiB,EAAE,eAoC/B,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,aAAa,CAU1D,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,YAGtC,CAAC"}