@praudent/dagma 0.0.0-stage → 0.1.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 (177) hide show
  1. package/dist/admin-ui/assets/index-CHJ8lsZp.js +120 -0
  2. package/dist/admin-ui/assets/index-XyqtD-IA.css +1 -0
  3. package/dist/admin-ui/index.html +12 -0
  4. package/dist/blueprint/agent.d.ts +148 -0
  5. package/dist/blueprint/agent.js +1 -0
  6. package/dist/blueprint/declaration-site.d.ts +7 -0
  7. package/dist/blueprint/declaration-site.js +8 -0
  8. package/dist/blueprint/declared-structure.d.ts +145 -0
  9. package/dist/blueprint/declared-structure.js +213 -0
  10. package/dist/blueprint/define-run-state.d.ts +79 -0
  11. package/dist/blueprint/define-run-state.js +89 -0
  12. package/dist/blueprint/load-blueprint.d.ts +28 -0
  13. package/dist/blueprint/load-blueprint.js +85 -0
  14. package/dist/blueprint/outcomes.d.ts +76 -0
  15. package/dist/blueprint/outcomes.js +10 -0
  16. package/dist/blueprint/phase.d.ts +153 -0
  17. package/dist/blueprint/phase.js +1 -0
  18. package/dist/blueprint/places.d.ts +26 -0
  19. package/dist/blueprint/places.js +37 -0
  20. package/dist/blueprint/prompt-file.d.ts +81 -0
  21. package/dist/blueprint/prompt-file.js +131 -0
  22. package/dist/blueprint/reply-reader.d.ts +36 -0
  23. package/dist/blueprint/reply-reader.js +38 -0
  24. package/dist/blueprint/run-settings.d.ts +38 -0
  25. package/dist/blueprint/run-settings.js +1 -0
  26. package/dist/blueprint/serializer.d.ts +14 -0
  27. package/dist/blueprint/serializer.js +4 -0
  28. package/dist/blueprint/write-scope.d.ts +39 -0
  29. package/dist/blueprint/write-scope.js +106 -0
  30. package/dist/command.d.ts +2 -0
  31. package/dist/command.js +148 -0
  32. package/dist/commands/calls-answering.d.ts +16 -0
  33. package/dist/commands/calls-answering.js +63 -0
  34. package/dist/commands/json-file.d.ts +6 -0
  35. package/dist/commands/json-file.js +19 -0
  36. package/dist/commands/run-command.d.ts +23 -0
  37. package/dist/commands/run-command.js +172 -0
  38. package/dist/commands/typed-answers.d.ts +10 -0
  39. package/dist/commands/typed-answers.js +43 -0
  40. package/dist/config.d.ts +27 -0
  41. package/dist/config.js +20 -0
  42. package/dist/devtool-server/app-pages.d.ts +12 -0
  43. package/dist/devtool-server/app-pages.js +68 -0
  44. package/dist/devtool-server/blueprint-description.d.ts +21 -0
  45. package/dist/devtool-server/blueprint-description.js +27 -0
  46. package/dist/devtool-server/connected-runs.d.ts +36 -0
  47. package/dist/devtool-server/connected-runs.js +201 -0
  48. package/dist/devtool-server/devtool-server.d.ts +17 -0
  49. package/dist/devtool-server/devtool-server.js +294 -0
  50. package/dist/devtool-server/devtool-shapes.d.ts +312 -0
  51. package/dist/devtool-server/devtool-shapes.js +24 -0
  52. package/dist/devtool-server/listed-runs.d.ts +17 -0
  53. package/dist/devtool-server/listed-runs.js +42 -0
  54. package/dist/devtool-server/print-blueprint.d.ts +1 -0
  55. package/dist/devtool-server/print-blueprint.js +36 -0
  56. package/dist/example/added-species.d.ts +21 -0
  57. package/dist/example/added-species.js +19 -0
  58. package/dist/example/cover.d.ts +21 -0
  59. package/dist/example/cover.js +67 -0
  60. package/dist/example/cross-references.d.ts +21 -0
  61. package/dist/example/cross-references.js +77 -0
  62. package/dist/example/entry-drafts.d.ts +21 -0
  63. package/dist/example/entry-drafts.js +63 -0
  64. package/dist/example/entry-merge.d.ts +108 -0
  65. package/dist/example/entry-merge.js +284 -0
  66. package/dist/example/field-guide.d.ts +26 -0
  67. package/dist/example/field-guide.js +40 -0
  68. package/dist/example/guide-page.d.ts +21 -0
  69. package/dist/example/guide-page.js +15 -0
  70. package/dist/example/missing-species.d.ts +21 -0
  71. package/dist/example/missing-species.js +59 -0
  72. package/dist/example/run-state.d.ts +803 -0
  73. package/dist/example/run-state.js +58 -0
  74. package/dist/example/serializers.d.ts +32 -0
  75. package/dist/example/serializers.js +42 -0
  76. package/dist/example/species-list.d.ts +47 -0
  77. package/dist/example/species-list.js +93 -0
  78. package/dist/index.d.ts +35 -0
  79. package/dist/index.js +25 -0
  80. package/dist/inference/anthropic-api.d.ts +37 -0
  81. package/dist/inference/anthropic-api.js +197 -0
  82. package/dist/inference/anthropic-prices.d.ts +18 -0
  83. package/dist/inference/anthropic-prices.js +39 -0
  84. package/dist/inference/anthropic-request.d.ts +51 -0
  85. package/dist/inference/anthropic-request.js +208 -0
  86. package/dist/inference/bedrock-api.d.ts +45 -0
  87. package/dist/inference/bedrock-api.js +242 -0
  88. package/dist/inference/bedrock-prices.d.ts +22 -0
  89. package/dist/inference/bedrock-prices.js +79 -0
  90. package/dist/inference/bedrock-request.d.ts +27 -0
  91. package/dist/inference/bedrock-request.js +193 -0
  92. package/dist/inference/call-queue-shapes.d.ts +273 -0
  93. package/dist/inference/call-queue-shapes.js +82 -0
  94. package/dist/inference/call-queue.d.ts +109 -0
  95. package/dist/inference/call-queue.js +408 -0
  96. package/dist/inference/gemini-api.d.ts +44 -0
  97. package/dist/inference/gemini-api.js +191 -0
  98. package/dist/inference/gemini-prices.d.ts +19 -0
  99. package/dist/inference/gemini-prices.js +33 -0
  100. package/dist/inference/gemini-request.d.ts +25 -0
  101. package/dist/inference/gemini-request.js +126 -0
  102. package/dist/inference/inference.d.ts +84 -0
  103. package/dist/inference/inference.js +9 -0
  104. package/dist/inference/openai-api.d.ts +29 -0
  105. package/dist/inference/openai-api.js +138 -0
  106. package/dist/inference/openai-prices.d.ts +12 -0
  107. package/dist/inference/openai-prices.js +25 -0
  108. package/dist/inference/openai-request.d.ts +50 -0
  109. package/dist/inference/openai-request.js +100 -0
  110. package/dist/inference/own-worker.d.ts +6 -0
  111. package/dist/inference/own-worker.js +16 -0
  112. package/dist/inference/scripted.d.ts +146 -0
  113. package/dist/inference/scripted.js +67 -0
  114. package/dist/run/assignments/agent-call.d.ts +32 -0
  115. package/dist/run/assignments/agent-call.js +218 -0
  116. package/dist/run/assignments/agent-phase.d.ts +14 -0
  117. package/dist/run/assignments/agent-phase.js +243 -0
  118. package/dist/run/assignments/assignment-memory.d.ts +42 -0
  119. package/dist/run/assignments/assignment-memory.js +52 -0
  120. package/dist/run/assignments/assignment.d.ts +17 -0
  121. package/dist/run/assignments/assignment.js +252 -0
  122. package/dist/run/assignments/model-settings.d.ts +39 -0
  123. package/dist/run/assignments/model-settings.js +57 -0
  124. package/dist/run/assignments/prepared-call.d.ts +28 -0
  125. package/dist/run/assignments/prepared-call.js +115 -0
  126. package/dist/run/assignments/tool-call.d.ts +26 -0
  127. package/dist/run/assignments/tool-call.js +108 -0
  128. package/dist/run/blueprint-mistake.d.ts +8 -0
  129. package/dist/run/blueprint-mistake.js +14 -0
  130. package/dist/run/code-phase.d.ts +11 -0
  131. package/dist/run/code-phase.js +59 -0
  132. package/dist/run/create-run.d.ts +36 -0
  133. package/dist/run/create-run.js +119 -0
  134. package/dist/run/execute-run.d.ts +7 -0
  135. package/dist/run/execute-run.js +158 -0
  136. package/dist/run/record/apply-event.d.ts +13 -0
  137. package/dist/run/record/apply-event.js +256 -0
  138. package/dist/run/record/events.d.ts +187 -0
  139. package/dist/run/record/events.js +1 -0
  140. package/dist/run/record/postgres-run-store.d.ts +13 -0
  141. package/dist/run/record/postgres-run-store.js +189 -0
  142. package/dist/run/record/progress-projection.d.ts +83 -0
  143. package/dist/run/record/progress-projection.js +167 -0
  144. package/dist/run/record/progress.d.ts +207 -0
  145. package/dist/run/record/progress.js +63 -0
  146. package/dist/run/record/run-store.d.ts +74 -0
  147. package/dist/run/record/run-store.js +1 -0
  148. package/dist/run/record/run-summary.d.ts +8 -0
  149. package/dist/run/record/run-summary.js +19 -0
  150. package/dist/run/record/run-types.d.ts +95 -0
  151. package/dist/run/record/run-types.js +1 -0
  152. package/dist/run/record/state-changes.d.ts +42 -0
  153. package/dist/run/record/state-changes.js +157 -0
  154. package/dist/run/resume-run.d.ts +25 -0
  155. package/dist/run/resume-run.js +99 -0
  156. package/dist/run/run-endings.d.ts +20 -0
  157. package/dist/run/run-endings.js +20 -0
  158. package/dist/run/run-option-shapes.d.ts +176 -0
  159. package/dist/run/run-option-shapes.js +47 -0
  160. package/dist/run/run-session.d.ts +144 -0
  161. package/dist/run/run-session.js +278 -0
  162. package/dist/worker/answer-queued-call.d.ts +19 -0
  163. package/dist/worker/answer-queued-call.js +100 -0
  164. package/dist/worker/launchers/claude-code.d.ts +7 -0
  165. package/dist/worker/launchers/claude-code.js +156 -0
  166. package/dist/worker/launchers/codex.d.ts +6 -0
  167. package/dist/worker/launchers/codex.js +141 -0
  168. package/dist/worker/launchers/launch.d.ts +31 -0
  169. package/dist/worker/launchers/launch.js +6 -0
  170. package/dist/worker/launchers/program-run.d.ts +30 -0
  171. package/dist/worker/launchers/program-run.js +92 -0
  172. package/dist/worker/launchers/tool-server.d.ts +26 -0
  173. package/dist/worker/launchers/tool-server.js +90 -0
  174. package/dist/worker/worker.d.ts +13 -0
  175. package/dist/worker/worker.js +170 -0
  176. package/package.json +43 -4
  177. package/README.md +0 -3
@@ -0,0 +1,51 @@
1
+ export declare const DEFAULT_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
2
+ export declare const ANTHROPIC_API_VERSION = "2023-06-01";
3
+ export type AnthropicContentBlock = {
4
+ type: 'text';
5
+ text: string;
6
+ } | {
7
+ type: 'tool_use';
8
+ id: string;
9
+ name: string;
10
+ input: unknown;
11
+ } | {
12
+ type: 'thinking';
13
+ thinking: string;
14
+ signature?: string;
15
+ } | {
16
+ type: 'redacted_thinking';
17
+ data: string;
18
+ };
19
+ export type AnthropicUsage = {
20
+ input_tokens?: number;
21
+ cache_creation_input_tokens?: number;
22
+ cache_creation?: {
23
+ ephemeral_5m_input_tokens?: number;
24
+ ephemeral_1h_input_tokens?: number;
25
+ };
26
+ cache_read_input_tokens?: number;
27
+ output_tokens?: number;
28
+ };
29
+ export type AnthropicMessageResponse = {
30
+ id: string;
31
+ model?: string;
32
+ content: AnthropicContentBlock[];
33
+ stop_reason?: string | null;
34
+ usage: AnthropicUsage;
35
+ };
36
+ export type AnthropicResponseStatus = 'completed' | 'failed' | 'incomplete';
37
+ /**
38
+ * Sends one streaming request to the Anthropic Messages API and returns the assembled message.
39
+ * `onResponse` is called for every response that produced a message id (including failed or
40
+ * truncated replies) before any error is thrown, so every billable response is accounted for.
41
+ */
42
+ export declare function completedAnthropicMessage({ apiKey, baseUrl, body, signal, onResponse, }: {
43
+ apiKey: string;
44
+ baseUrl?: string;
45
+ body: unknown;
46
+ signal: AbortSignal;
47
+ onResponse: (result: {
48
+ response: AnthropicMessageResponse;
49
+ status: AnthropicResponseStatus;
50
+ }) => void | Promise<void>;
51
+ }): Promise<AnthropicMessageResponse>;
@@ -0,0 +1,208 @@
1
+ import { ProviderConnectionError } from './inference.js';
2
+ export const DEFAULT_ANTHROPIC_MESSAGES_URL = 'https://api.anthropic.com/v1/messages';
3
+ export const ANTHROPIC_API_VERSION = '2023-06-01';
4
+ const RETRYABLE_STREAM_ERROR_TYPES = new Set([
5
+ 'overloaded_error',
6
+ 'rate_limit_error',
7
+ 'api_error',
8
+ ]);
9
+ function finalizeBlock(block) {
10
+ if (block.type === 'text')
11
+ return { type: 'text', text: block.text };
12
+ if (block.type === 'thinking')
13
+ return {
14
+ type: 'thinking',
15
+ thinking: block.thinking,
16
+ ...(block.signature ? { signature: block.signature } : {}),
17
+ };
18
+ if (block.type === 'redacted_thinking')
19
+ return { type: 'redacted_thinking', data: block.data };
20
+ let input = block.initialInput ?? {};
21
+ if (block.inputJson.trim()) {
22
+ try {
23
+ input = JSON.parse(block.inputJson);
24
+ }
25
+ catch {
26
+ input = block.inputJson;
27
+ }
28
+ }
29
+ return { type: 'tool_use', id: block.id, name: block.name, input };
30
+ }
31
+ function mergeUsage(target, incoming) {
32
+ if (!incoming)
33
+ return;
34
+ if (typeof incoming.input_tokens === 'number')
35
+ target.input_tokens = incoming.input_tokens;
36
+ if (typeof incoming.cache_creation_input_tokens === 'number')
37
+ target.cache_creation_input_tokens = incoming.cache_creation_input_tokens;
38
+ if (incoming.cache_creation) {
39
+ target.cache_creation = {
40
+ ...target.cache_creation,
41
+ ...incoming.cache_creation,
42
+ };
43
+ }
44
+ if (typeof incoming.cache_read_input_tokens === 'number')
45
+ target.cache_read_input_tokens = incoming.cache_read_input_tokens;
46
+ if (typeof incoming.output_tokens === 'number')
47
+ target.output_tokens = incoming.output_tokens;
48
+ }
49
+ /**
50
+ * Sends one streaming request to the Anthropic Messages API and returns the assembled message.
51
+ * `onResponse` is called for every response that produced a message id (including failed or
52
+ * truncated replies) before any error is thrown, so every billable response is accounted for.
53
+ */
54
+ export async function completedAnthropicMessage({ apiKey, baseUrl = DEFAULT_ANTHROPIC_MESSAGES_URL, body, signal, onResponse, }) {
55
+ let response;
56
+ try {
57
+ response = await fetch(baseUrl, {
58
+ method: 'POST',
59
+ headers: {
60
+ 'x-api-key': apiKey,
61
+ 'anthropic-version': ANTHROPIC_API_VERSION,
62
+ 'content-type': 'application/json',
63
+ },
64
+ body: JSON.stringify(body),
65
+ signal,
66
+ });
67
+ }
68
+ catch (error) {
69
+ signal.throwIfAborted();
70
+ throw new ProviderConnectionError(`The Anthropic API could not be reached: ${error instanceof Error ? error.message : String(error)}`);
71
+ }
72
+ if (!response.ok) {
73
+ const detail = await response.text().catch(() => '');
74
+ const message = `The Anthropic API answered ${response.status}: ${detail.slice(0, 500)}`;
75
+ if (response.status === 429 || response.status >= 500 || response.status === 529)
76
+ throw new ProviderConnectionError(message);
77
+ throw new Error(message);
78
+ }
79
+ const decoder = new TextDecoder();
80
+ let buffered = '';
81
+ let messageId;
82
+ let messageModel;
83
+ let stopReason;
84
+ const usage = {};
85
+ const blocks = new Map();
86
+ let stopped = false;
87
+ let failure;
88
+ try {
89
+ for await (const chunk of response.body) {
90
+ buffered += decoder.decode(chunk, { stream: true }).replaceAll('\r\n', '\n');
91
+ for (;;) {
92
+ const end = buffered.indexOf('\n\n');
93
+ if (end < 0)
94
+ break;
95
+ const rawEvent = buffered.slice(0, end);
96
+ buffered = buffered.slice(end + 2);
97
+ const data = rawEvent
98
+ .split('\n')
99
+ .filter((line) => line.startsWith('data:'))
100
+ .map((line) => line.slice('data:'.length).trim())
101
+ .join('');
102
+ if (!data)
103
+ continue;
104
+ const event = JSON.parse(data);
105
+ if (event.type === 'message_start' && event.message) {
106
+ messageId = event.message.id;
107
+ messageModel = event.message.model;
108
+ mergeUsage(usage, event.message.usage);
109
+ continue;
110
+ }
111
+ if (event.type === 'content_block_start' && typeof event.index === 'number' && event.content_block) {
112
+ const cb = event.content_block;
113
+ if (cb.type === 'text')
114
+ blocks.set(event.index, { type: 'text', text: cb.text ?? '' });
115
+ else if (cb.type === 'tool_use')
116
+ blocks.set(event.index, {
117
+ type: 'tool_use',
118
+ id: cb.id ?? '',
119
+ name: cb.name ?? '',
120
+ inputJson: '',
121
+ initialInput: cb.input,
122
+ });
123
+ else if (cb.type === 'thinking')
124
+ blocks.set(event.index, {
125
+ type: 'thinking',
126
+ thinking: cb.thinking ?? '',
127
+ signature: cb.signature ?? '',
128
+ });
129
+ else if (cb.type === 'redacted_thinking')
130
+ blocks.set(event.index, { type: 'redacted_thinking', data: cb.data ?? '' });
131
+ continue;
132
+ }
133
+ if (event.type === 'content_block_delta' && typeof event.index === 'number' && event.delta) {
134
+ const block = blocks.get(event.index);
135
+ if (!block)
136
+ continue;
137
+ if (block.type === 'text' && event.delta.type === 'text_delta' && event.delta.text)
138
+ block.text += event.delta.text;
139
+ else if (block.type === 'tool_use' &&
140
+ event.delta.type === 'input_json_delta' &&
141
+ event.delta.partial_json)
142
+ block.inputJson += event.delta.partial_json;
143
+ else if (block.type === 'thinking' && event.delta.type === 'thinking_delta' && event.delta.thinking)
144
+ block.thinking += event.delta.thinking;
145
+ else if (block.type === 'thinking' &&
146
+ event.delta.type === 'signature_delta' &&
147
+ event.delta.signature)
148
+ block.signature += event.delta.signature;
149
+ continue;
150
+ }
151
+ if (event.type === 'message_delta') {
152
+ if (event.delta?.stop_reason !== undefined)
153
+ stopReason = event.delta.stop_reason;
154
+ mergeUsage(usage, event.usage);
155
+ continue;
156
+ }
157
+ if (event.type === 'message_stop') {
158
+ stopped = true;
159
+ continue;
160
+ }
161
+ if (event.type === 'error') {
162
+ const errorType = event.error?.type ?? '';
163
+ const message = `The Anthropic API failed the request: ${event.error?.message ?? (errorType || 'no reason given')}`;
164
+ failure = RETRYABLE_STREAM_ERROR_TYPES.has(errorType)
165
+ ? new ProviderConnectionError(message)
166
+ : new Error(message);
167
+ }
168
+ }
169
+ }
170
+ }
171
+ catch (error) {
172
+ signal.throwIfAborted();
173
+ if (!failure && !stopped)
174
+ throw new ProviderConnectionError(`The Anthropic API's reply was cut off: ${error instanceof Error ? error.message : String(error)}`);
175
+ }
176
+ const orderedContent = [...blocks.entries()]
177
+ .sort(([a], [b]) => a - b)
178
+ .map(([, block]) => finalizeBlock(block));
179
+ const assembled = messageId
180
+ ? {
181
+ id: messageId,
182
+ ...(messageModel ? { model: messageModel } : {}),
183
+ content: orderedContent,
184
+ ...(stopReason !== undefined ? { stop_reason: stopReason } : {}),
185
+ usage,
186
+ }
187
+ : undefined;
188
+ if (failure) {
189
+ if (assembled)
190
+ await onResponse({ response: assembled, status: 'failed' });
191
+ throw failure;
192
+ }
193
+ if (!stopped || !assembled) {
194
+ if (assembled)
195
+ await onResponse({ response: assembled, status: 'incomplete' });
196
+ throw new ProviderConnectionError('The Anthropic API closed the reply before its end.');
197
+ }
198
+ if (stopReason === 'max_tokens') {
199
+ await onResponse({ response: assembled, status: 'incomplete' });
200
+ throw new Error('The Anthropic API ended the reply early: max_tokens');
201
+ }
202
+ if (stopReason === 'refusal') {
203
+ await onResponse({ response: assembled, status: 'failed' });
204
+ throw new Error('The Anthropic API refused the request.');
205
+ }
206
+ await onResponse({ response: assembled, status: 'completed' });
207
+ return assembled;
208
+ }
@@ -0,0 +1,45 @@
1
+ import { BedrockRuntimeClient } from '@aws-sdk/client-bedrock-runtime';
2
+ import type { Tokens } from '../run/record/events.js';
3
+ import { type BedrockResponseStatus, type BedrockStreamSender } from './bedrock-request.js';
4
+ import type { Infer, InferenceCall } from './inference.js';
5
+ export type BedrockCacheTokens = {
6
+ uncachedInput: number;
7
+ cacheWriteDefault: number;
8
+ cacheWrite1h: number;
9
+ cacheRead: number;
10
+ };
11
+ export type BedrockBeforeRequest = (input: {
12
+ call: InferenceCall;
13
+ requestIndex: number;
14
+ model: string;
15
+ }) => void | Promise<void>;
16
+ export type BedrockProviderResponse = (input: {
17
+ call: InferenceCall;
18
+ responseId: string;
19
+ model: string;
20
+ tokens: Tokens;
21
+ cacheTokens: BedrockCacheTokens;
22
+ costUsd?: number;
23
+ status: BedrockResponseStatus;
24
+ }) => void | Promise<void>;
25
+ /**
26
+ * Answers calls with the AWS Bedrock ConverseStream API (Amazon Ergo-1.0, Claude on Bedrock, etc.).
27
+ * Translates `promptBlocks` into Bedrock `cachePoint` blocks (omitting `ttl` on models like
28
+ * Ergo-1.0 that use a fixed native 30m TTL), places a rolling `cachePoint` on multi-turn tool
29
+ * results, and reports per-response billing hooks.
30
+ */
31
+ export declare function bedrockApiInference({ region, client, send: customSend, defaultModel, outputSchema, maxOutputTokens, beforeRequest, onProviderResponse, }?: {
32
+ region?: string;
33
+ client?: BedrockRuntimeClient;
34
+ /** Injectable ConverseStream sender for tests. */
35
+ send?: BedrockStreamSender;
36
+ defaultModel?: string;
37
+ /** Optional JSON Schema (object) constraining the final text output. */
38
+ outputSchema?: {
39
+ name?: string;
40
+ schema: unknown;
41
+ };
42
+ maxOutputTokens?: number;
43
+ beforeRequest?: BedrockBeforeRequest;
44
+ onProviderResponse?: BedrockProviderResponse;
45
+ }): Infer;
@@ -0,0 +1,242 @@
1
+ import { BedrockRuntimeClient, } from '@aws-sdk/client-bedrock-runtime';
2
+ import { bedrockRequestCostUsd, bedrockSupportsExtendedTtl, hasBedrockPrice, } from './bedrock-prices.js';
3
+ import { bedrockClientSender, completedBedrockConverse, } from './bedrock-request.js';
4
+ const DEFAULT_MAX_OUTPUT_TOKENS = 16_384;
5
+ const MAX_CACHE_BREAKPOINTS = 4;
6
+ function imageFormatFor(mediaType) {
7
+ if (mediaType === 'image/jpeg' || mediaType === 'image/jpg')
8
+ return 'jpeg';
9
+ if (mediaType === 'image/gif')
10
+ return 'gif';
11
+ if (mediaType === 'image/webp')
12
+ return 'webp';
13
+ return 'png';
14
+ }
15
+ function cachePointFor({ ttl, supportsExtendedTtl, }) {
16
+ if (supportsExtendedTtl && ttl === '1h')
17
+ return { cachePoint: { type: 'default', ttl: '1h' } };
18
+ // Omit `ttl` for default checkpoints and for models (like Ergo-1.0) that use a fixed native TTL;
19
+ // Bedrock throws `ValidationException` when an unsupported `ttl` value is sent.
20
+ return { cachePoint: { type: 'default' } };
21
+ }
22
+ function initialUserContent({ call, supportsExtendedTtl, }) {
23
+ const blocks = call.promptBlocks?.length
24
+ ? call.promptBlocks
25
+ : [{ text: call.prompt }];
26
+ let sawShortTtl = false;
27
+ let staticBreakpoints = 0;
28
+ const content = [];
29
+ for (const block of blocks) {
30
+ if (!block.text)
31
+ continue;
32
+ if (block.cache === '1h' && sawShortTtl)
33
+ throw new Error(`${call.agent} puts a 1h cache breakpoint after a 5m cache breakpoint; longer TTLs must come first.`);
34
+ if (block.cache === '5m')
35
+ sawShortTtl = true;
36
+ content.push({ text: block.text });
37
+ if (block.cache) {
38
+ staticBreakpoints += 1;
39
+ if (staticBreakpoints > MAX_CACHE_BREAKPOINTS)
40
+ throw new Error(`${call.agent} defines more than ${MAX_CACHE_BREAKPOINTS} prompt cache breakpoints.`);
41
+ content.push(cachePointFor({ ttl: block.cache, supportsExtendedTtl }));
42
+ }
43
+ }
44
+ for (const { mediaType, bytes } of call.images)
45
+ content.push({
46
+ image: {
47
+ format: imageFormatFor(mediaType),
48
+ source: { bytes },
49
+ },
50
+ });
51
+ return { content, staticBreakpoints };
52
+ }
53
+ function extractCacheTokens(usage) {
54
+ const uncachedInput = typeof usage?.inputTokens === 'number' ? usage.inputTokens : 0;
55
+ const cacheRead = typeof usage?.cacheReadInputTokens === 'number' ? usage.cacheReadInputTokens : 0;
56
+ const details = usage?.cacheDetails;
57
+ if (details?.length) {
58
+ let cacheWrite1h = 0;
59
+ let cacheWriteDefault = 0;
60
+ for (const detail of details) {
61
+ const count = typeof detail.inputTokens === 'number' ? detail.inputTokens : 0;
62
+ if (detail.ttl === '1h')
63
+ cacheWrite1h += count;
64
+ else
65
+ cacheWriteDefault += count;
66
+ }
67
+ return { uncachedInput, cacheWriteDefault, cacheWrite1h, cacheRead };
68
+ }
69
+ const cacheWriteDefault = typeof usage?.cacheWriteInputTokens === 'number' ? usage.cacheWriteInputTokens : 0;
70
+ return { uncachedInput, cacheWriteDefault, cacheWrite1h: 0, cacheRead };
71
+ }
72
+ /**
73
+ * Answers calls with the AWS Bedrock ConverseStream API (Amazon Ergo-1.0, Claude on Bedrock, etc.).
74
+ * Translates `promptBlocks` into Bedrock `cachePoint` blocks (omitting `ttl` on models like
75
+ * Ergo-1.0 that use a fixed native 30m TTL), places a rolling `cachePoint` on multi-turn tool
76
+ * results, and reports per-response billing hooks.
77
+ */
78
+ export function bedrockApiInference({ region, client, send: customSend, defaultModel, outputSchema, maxOutputTokens, beforeRequest, onProviderResponse, } = {}) {
79
+ let resolvedSender = customSend;
80
+ const getSender = () => {
81
+ if (!resolvedSender) {
82
+ const sdkClient = client ?? new BedrockRuntimeClient(region ? { region } : {});
83
+ resolvedSender = bedrockClientSender(sdkClient);
84
+ }
85
+ return resolvedSender;
86
+ };
87
+ return async ({ call, callTool, signal, onRequestCounted }) => {
88
+ const model = call.model ?? defaultModel;
89
+ if (!model || !hasBedrockPrice({ model }))
90
+ throw new Error(`${call.agent} names ${model ?? 'no model'}, which has no price on the AWS Bedrock API.`);
91
+ const supportsExtendedTtl = bedrockSupportsExtendedTtl({ model });
92
+ const { content: firstContent, staticBreakpoints } = initialUserContent({
93
+ call,
94
+ supportsExtendedTtl,
95
+ });
96
+ const messages = [{ role: 'user', content: firstContent }];
97
+ const tokens = {};
98
+ const reasoning = [];
99
+ let costUsd;
100
+ let toolCallsAnswered = 0;
101
+ const countRequest = async ({ response, status, }) => {
102
+ const usage = response.usage;
103
+ const cacheTokens = extractCacheTokens(usage);
104
+ const totalInput = cacheTokens.uncachedInput +
105
+ cacheTokens.cacheWriteDefault +
106
+ cacheTokens.cacheWrite1h +
107
+ cacheTokens.cacheRead;
108
+ const reported = {};
109
+ if (typeof usage?.inputTokens === 'number' ||
110
+ typeof usage?.cacheWriteInputTokens === 'number' ||
111
+ typeof usage?.cacheReadInputTokens === 'number')
112
+ reported.input = totalInput;
113
+ if (cacheTokens.cacheRead > 0 || typeof usage?.cacheReadInputTokens === 'number')
114
+ reported.cached = cacheTokens.cacheRead;
115
+ if (typeof usage?.outputTokens === 'number')
116
+ reported.output = usage.outputTokens;
117
+ for (const name of ['input', 'cached', 'output'])
118
+ if (typeof reported[name] === 'number')
119
+ tokens[name] = (tokens[name] ?? 0) + reported[name];
120
+ let responseCostUsd;
121
+ if (typeof reported.input === 'number' && typeof reported.output === 'number') {
122
+ responseCostUsd = bedrockRequestCostUsd({
123
+ model,
124
+ uncachedInputTokens: cacheTokens.uncachedInput,
125
+ cacheWriteDefaultTokens: cacheTokens.cacheWriteDefault,
126
+ cacheWrite1hTokens: cacheTokens.cacheWrite1h,
127
+ cacheReadTokens: cacheTokens.cacheRead,
128
+ outputTokens: reported.output,
129
+ });
130
+ costUsd = (costUsd ?? 0) + responseCostUsd;
131
+ }
132
+ let toolCallsBefore = toolCallsAnswered;
133
+ for (const block of response.content) {
134
+ if (block.toolUse)
135
+ toolCallsBefore += 1;
136
+ else if (block.reasoningContent?.reasoningText?.text)
137
+ reasoning.push({
138
+ text: block.reasoningContent.reasoningText.text,
139
+ afterToolCalls: toolCallsBefore,
140
+ });
141
+ }
142
+ onRequestCounted?.({
143
+ tokens: { ...tokens },
144
+ ...(costUsd !== undefined ? { costUsd } : {}),
145
+ reasoning: [...reasoning],
146
+ });
147
+ await onProviderResponse?.({
148
+ call,
149
+ responseId: response.responseId,
150
+ model,
151
+ tokens: reported,
152
+ cacheTokens,
153
+ ...(responseCostUsd !== undefined ? { costUsd: responseCostUsd } : {}),
154
+ status,
155
+ });
156
+ };
157
+ const toolConfig = call.tools.length
158
+ ? {
159
+ tools: call.tools.map((tool) => ({
160
+ toolSpec: {
161
+ name: tool.name,
162
+ description: tool.description,
163
+ inputSchema: { json: tool.inputSchema },
164
+ },
165
+ })),
166
+ }
167
+ : undefined;
168
+ const effort = call.effort === 'low' || call.effort === 'medium' || call.effort === 'high'
169
+ ? call.effort
170
+ : undefined;
171
+ const outputConfig = outputSchema || effort
172
+ ? {
173
+ ...(outputSchema
174
+ ? {
175
+ textFormat: {
176
+ type: 'json_schema',
177
+ structure: {
178
+ jsonSchema: {
179
+ name: outputSchema.name ?? 'response',
180
+ schema: JSON.stringify(outputSchema.schema),
181
+ },
182
+ },
183
+ },
184
+ }
185
+ : {}),
186
+ ...(effort ? { effort } : {}),
187
+ }
188
+ : undefined;
189
+ const send = getSender();
190
+ for (let requestIndex = 1;; requestIndex += 1) {
191
+ await beforeRequest?.({ call, requestIndex, model });
192
+ const response = await completedBedrockConverse({
193
+ send,
194
+ signal,
195
+ onResponse: countRequest,
196
+ input: {
197
+ modelId: model,
198
+ messages,
199
+ inferenceConfig: {
200
+ maxTokens: maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
201
+ },
202
+ ...(toolConfig ? { toolConfig } : {}),
203
+ ...(outputConfig ? { outputConfig } : {}),
204
+ },
205
+ });
206
+ const toolUses = response.content.flatMap((block) => (block.toolUse ? [block.toolUse] : []));
207
+ if (!toolUses.length) {
208
+ const replyText = response.content
209
+ .map((block) => block.text ?? '')
210
+ .join('');
211
+ return { replyText, tokens, ...(costUsd !== undefined ? { costUsd } : {}), reasoning };
212
+ }
213
+ // Preserve exact assistant blocks (including reasoningContent + signatures) for the next turn.
214
+ messages.push({ role: 'assistant', content: response.content });
215
+ // Remove any previous rolling cachePoint from earlier tool-result turns before adding the new one.
216
+ for (let i = 1; i < messages.length; i += 1) {
217
+ const message = messages[i];
218
+ if (message.role === 'user' && message.content)
219
+ message.content = message.content.filter((block) => !block.cachePoint);
220
+ }
221
+ const toolResults = [];
222
+ for (const toolUse of toolUses) {
223
+ signal.throwIfAborted();
224
+ const result = await callTool({ name: toolUse.name ?? '', args: toolUse.input });
225
+ toolCallsAnswered += 1;
226
+ toolResults.push({
227
+ toolResult: {
228
+ toolUseId: toolUse.toolUseId ?? '',
229
+ content: [
230
+ typeof result === 'string'
231
+ ? { text: result }
232
+ : { text: JSON.stringify(result ?? null) },
233
+ ],
234
+ },
235
+ });
236
+ }
237
+ if (staticBreakpoints < MAX_CACHE_BREAKPOINTS && toolResults.length > 0)
238
+ toolResults.push({ cachePoint: { type: 'default' } });
239
+ messages.push({ role: 'user', content: toolResults });
240
+ }
241
+ };
242
+ }
@@ -0,0 +1,22 @@
1
+ /** Whether the Bedrock API route can price a model. A run on the API is refused before any call
2
+ * when an agent names a model that has no price. */
3
+ export declare function hasBedrockPrice({ model }: {
4
+ model: string;
5
+ }): boolean;
6
+ /** Whether a Bedrock model accepts an explicit `ttl: '1h'` field on `cachePoint` blocks.
7
+ * Bedrock throws `ValidationException` when `ttl` is sent to models that only support their default TTL. */
8
+ export declare function bedrockSupportsExtendedTtl({ model }: {
9
+ model: string;
10
+ }): boolean;
11
+ /**
12
+ * The cost in dollars of one request to AWS Bedrock Converse, priced by its own token counts.
13
+ * Bedrock's `inputTokens` counts uncached input tokens (separate from cache write and cache read).
14
+ */
15
+ export declare function bedrockRequestCostUsd({ model, uncachedInputTokens, cacheWriteDefaultTokens, cacheWrite1hTokens, cacheReadTokens, outputTokens, }: {
16
+ model: string;
17
+ uncachedInputTokens: number;
18
+ cacheWriteDefaultTokens?: number;
19
+ cacheWrite1hTokens?: number;
20
+ cacheReadTokens?: number;
21
+ outputTokens: number;
22
+ }): number;
@@ -0,0 +1,79 @@
1
+ const PRICES = {
2
+ 'global.amazon.ergo-1.0': {
3
+ input: 1,
4
+ output: 3,
5
+ cacheWrite: 1.25,
6
+ cacheRead: 0.03,
7
+ supportsExtendedTtl: false,
8
+ },
9
+ 'amazon.ergo-1.0': {
10
+ input: 1,
11
+ output: 3,
12
+ cacheWrite: 1.25,
13
+ cacheRead: 0.03,
14
+ supportsExtendedTtl: false,
15
+ },
16
+ 'us.amazon.ergo-1.0': {
17
+ input: 1.1,
18
+ output: 3.3,
19
+ cacheWrite: 1.375,
20
+ cacheRead: 0.033,
21
+ supportsExtendedTtl: false,
22
+ },
23
+ 'global.anthropic.claude-sonnet-4-6': {
24
+ input: 3,
25
+ output: 15,
26
+ cacheWrite: 3.75,
27
+ cacheWrite1h: 6,
28
+ cacheRead: 0.3,
29
+ supportsExtendedTtl: true,
30
+ },
31
+ 'us.anthropic.claude-sonnet-4-6': {
32
+ input: 3.3,
33
+ output: 16.5,
34
+ cacheWrite: 4.125,
35
+ cacheWrite1h: 6.6,
36
+ cacheRead: 0.33,
37
+ supportsExtendedTtl: true,
38
+ },
39
+ 'global.anthropic.claude-opus-4-6': {
40
+ input: 5,
41
+ output: 25,
42
+ cacheWrite: 6.25,
43
+ cacheWrite1h: 10,
44
+ cacheRead: 0.5,
45
+ supportsExtendedTtl: true,
46
+ },
47
+ 'us.anthropic.claude-opus-4-6': {
48
+ input: 5.5,
49
+ output: 27.5,
50
+ cacheWrite: 6.875,
51
+ cacheWrite1h: 11,
52
+ cacheRead: 0.55,
53
+ supportsExtendedTtl: true,
54
+ },
55
+ };
56
+ /** Whether the Bedrock API route can price a model. A run on the API is refused before any call
57
+ * when an agent names a model that has no price. */
58
+ export function hasBedrockPrice({ model }) {
59
+ return Object.hasOwn(PRICES, model);
60
+ }
61
+ /** Whether a Bedrock model accepts an explicit `ttl: '1h'` field on `cachePoint` blocks.
62
+ * Bedrock throws `ValidationException` when `ttl` is sent to models that only support their default TTL. */
63
+ export function bedrockSupportsExtendedTtl({ model }) {
64
+ return Object.hasOwn(PRICES, model) ? PRICES[model].supportsExtendedTtl : false;
65
+ }
66
+ /**
67
+ * The cost in dollars of one request to AWS Bedrock Converse, priced by its own token counts.
68
+ * Bedrock's `inputTokens` counts uncached input tokens (separate from cache write and cache read).
69
+ */
70
+ export function bedrockRequestCostUsd({ model, uncachedInputTokens, cacheWriteDefaultTokens = 0, cacheWrite1hTokens = 0, cacheReadTokens = 0, outputTokens, }) {
71
+ const rates = PRICES[model];
72
+ const write1hRate = rates.cacheWrite1h ?? rates.cacheWrite;
73
+ return ((uncachedInputTokens * rates.input +
74
+ cacheWriteDefaultTokens * rates.cacheWrite +
75
+ cacheWrite1hTokens * write1hRate +
76
+ cacheReadTokens * rates.cacheRead +
77
+ outputTokens * rates.output) /
78
+ 1_000_000);
79
+ }
@@ -0,0 +1,27 @@
1
+ import { type BedrockRuntimeClient, type ContentBlock, type ConverseStreamCommandInput, type ConverseStreamCommandOutput, type StopReason, type TokenUsage } from '@aws-sdk/client-bedrock-runtime';
2
+ export type BedrockResponseStatus = 'completed' | 'failed' | 'incomplete';
3
+ export type BedrockConverseResult = {
4
+ responseId: string;
5
+ content: ContentBlock[];
6
+ stopReason?: StopReason;
7
+ usage?: TokenUsage;
8
+ };
9
+ export type BedrockStreamSender = (input: ConverseStreamCommandInput, options: {
10
+ abortSignal: AbortSignal;
11
+ }) => Promise<ConverseStreamCommandOutput>;
12
+ /** Creates a `BedrockStreamSender` backed by an AWS SDK `BedrockRuntimeClient`. */
13
+ export declare function bedrockClientSender(client: BedrockRuntimeClient): BedrockStreamSender;
14
+ /**
15
+ * Sends one streaming ConverseStream request to AWS Bedrock and returns the assembled assistant
16
+ * content blocks. `onResponse` is called for every response that returned metadata/usage before
17
+ * any error is thrown, so every billable response is accounted for.
18
+ */
19
+ export declare function completedBedrockConverse({ send, input, signal, onResponse, }: {
20
+ send: BedrockStreamSender;
21
+ input: ConverseStreamCommandInput;
22
+ signal: AbortSignal;
23
+ onResponse: (result: {
24
+ response: BedrockConverseResult;
25
+ status: BedrockResponseStatus;
26
+ }) => void | Promise<void>;
27
+ }): Promise<BedrockConverseResult>;