lsd-pi 1.1.9 → 1.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/resources/extensions/slash-commands/context.js +15 -8
- package/dist/resources/extensions/slash-commands/plan.js +12 -6
- package/dist/resources/extensions/slash-commands/tools.js +51 -12
- package/dist/startup-model-validation.d.ts +1 -1
- package/package.json +1 -1
- package/packages/pi-agent-core/dist/types.d.ts +2 -1
- package/packages/pi-agent-core/dist/types.d.ts.map +1 -1
- package/packages/pi-agent-core/dist/types.js.map +1 -1
- package/packages/pi-agent-core/src/types.ts +2 -1
- package/packages/pi-ai/dist/providers/amazon-bedrock.js +10 -3
- package/packages/pi-ai/dist/providers/amazon-bedrock.js.map +1 -1
- package/packages/pi-ai/dist/providers/anthropic-shared.d.ts +1 -1
- package/packages/pi-ai/dist/providers/anthropic-shared.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/anthropic-shared.js +4 -1
- package/packages/pi-ai/dist/providers/anthropic-shared.js.map +1 -1
- package/packages/pi-ai/dist/providers/anthropic.d.ts +2 -2
- package/packages/pi-ai/dist/providers/anthropic.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/anthropic.js +2 -2
- package/packages/pi-ai/dist/providers/anthropic.js.map +1 -1
- package/packages/pi-ai/dist/providers/azure-openai-responses.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/azure-openai-responses.js +2 -1
- package/packages/pi-ai/dist/providers/azure-openai-responses.js.map +1 -1
- package/packages/pi-ai/dist/providers/google-gemini-cli.js +2 -0
- package/packages/pi-ai/dist/providers/google-gemini-cli.js.map +1 -1
- package/packages/pi-ai/dist/providers/google-vertex.js +2 -0
- package/packages/pi-ai/dist/providers/google-vertex.js.map +1 -1
- package/packages/pi-ai/dist/providers/google.js +2 -0
- package/packages/pi-ai/dist/providers/google.js.map +1 -1
- package/packages/pi-ai/dist/providers/openai-codex-responses.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/openai-codex-responses.js +2 -1
- package/packages/pi-ai/dist/providers/openai-codex-responses.js.map +1 -1
- package/packages/pi-ai/dist/providers/openai-completions.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/openai-completions.js +2 -1
- package/packages/pi-ai/dist/providers/openai-completions.js.map +1 -1
- package/packages/pi-ai/dist/providers/openai-responses.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/openai-responses.js +2 -1
- package/packages/pi-ai/dist/providers/openai-responses.js.map +1 -1
- package/packages/pi-ai/dist/providers/simple-options.d.ts +1 -1
- package/packages/pi-ai/dist/providers/simple-options.d.ts.map +1 -1
- package/packages/pi-ai/dist/providers/simple-options.js +6 -2
- package/packages/pi-ai/dist/providers/simple-options.js.map +1 -1
- package/packages/pi-ai/dist/types.d.ts +1 -1
- package/packages/pi-ai/dist/types.d.ts.map +1 -1
- package/packages/pi-ai/dist/types.js.map +1 -1
- package/packages/pi-ai/src/providers/amazon-bedrock.ts +11 -4
- package/packages/pi-ai/src/providers/anthropic-shared.ts +5 -2
- package/packages/pi-ai/src/providers/anthropic.ts +2 -2
- package/packages/pi-ai/src/providers/azure-openai-responses.ts +2 -1
- package/packages/pi-ai/src/providers/google-gemini-cli.ts +3 -1
- package/packages/pi-ai/src/providers/google-vertex.ts +3 -1
- package/packages/pi-ai/src/providers/google.ts +3 -1
- package/packages/pi-ai/src/providers/openai-codex-responses.ts +2 -1
- package/packages/pi-ai/src/providers/openai-completions.ts +2 -1
- package/packages/pi-ai/src/providers/openai-responses.ts +2 -1
- package/packages/pi-ai/src/providers/simple-options.ts +5 -3
- package/packages/pi-ai/src/types.ts +1 -1
- package/packages/pi-coding-agent/dist/cli/args.js +1 -1
- package/packages/pi-coding-agent/dist/cli/args.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session.d.ts +10 -0
- package/packages/pi-coding-agent/dist/core/agent-session.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/agent-session.js +46 -15
- package/packages/pi-coding-agent/dist/core/agent-session.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/classifier-service.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/classifier-service.js +34 -61
- package/packages/pi-coding-agent/dist/core/classifier-service.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/utils.d.ts +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/utils.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/compaction/utils.js +3 -1
- package/packages/pi-coding-agent/dist/core/compaction/utils.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/sdk.js +4 -16
- package/packages/pi-coding-agent/dist/core/sdk.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/settings-manager.d.ts +6 -3
- package/packages/pi-coding-agent/dist/core/settings-manager.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/settings-manager.js +14 -2
- package/packages/pi-coding-agent/dist/core/settings-manager.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.d.ts +6 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/core/system-prompt.js +28 -68
- package/packages/pi-coding-agent/dist/core/system-prompt.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/tools/bash-interceptor.js +1 -1
- package/packages/pi-coding-agent/dist/core/tools/bash-interceptor.js.map +1 -1
- package/packages/pi-coding-agent/dist/core/tools/bash-interceptor.test.js +5 -0
- package/packages/pi-coding-agent/dist/core/tools/bash-interceptor.test.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/bash-execution.js +28 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/settings-selector.d.ts +4 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/settings-selector.js +17 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/thinking-selector.js +1 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.js +28 -0
- package/packages/pi-coding-agent/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.js +28 -1
- package/packages/pi-coding-agent/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/theme/theme.d.ts +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/packages/pi-coding-agent/dist/modes/interactive/theme/theme.js +2 -0
- package/packages/pi-coding-agent/dist/modes/interactive/theme/theme.js.map +1 -1
- package/packages/pi-coding-agent/src/cli/args.ts +1 -1
- package/packages/pi-coding-agent/src/core/agent-session.ts +49 -14
- package/packages/pi-coding-agent/src/core/classifier-service.ts +35 -63
- package/packages/pi-coding-agent/src/core/compaction/utils.ts +3 -1
- package/packages/pi-coding-agent/src/core/sdk.ts +4 -16
- package/packages/pi-coding-agent/src/core/settings-manager.ts +19 -6
- package/packages/pi-coding-agent/src/core/system-prompt.ts +39 -82
- package/packages/pi-coding-agent/src/core/tools/bash-interceptor.test.ts +6 -0
- package/packages/pi-coding-agent/src/core/tools/bash-interceptor.ts +1 -1
- package/packages/pi-coding-agent/src/modes/interactive/components/bash-execution.ts +26 -0
- package/packages/pi-coding-agent/src/modes/interactive/components/settings-selector.ts +22 -1
- package/packages/pi-coding-agent/src/modes/interactive/components/thinking-selector.ts +1 -0
- package/packages/pi-coding-agent/src/modes/interactive/components/tool-execution.ts +30 -0
- package/packages/pi-coding-agent/src/modes/interactive/interactive-mode.ts +28 -1
- package/packages/pi-coding-agent/src/modes/interactive/theme/theme.ts +3 -1
- package/pkg/dist/modes/interactive/theme/theme.d.ts +1 -1
- package/pkg/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/pkg/dist/modes/interactive/theme/theme.js +2 -0
- package/pkg/dist/modes/interactive/theme/theme.js.map +1 -1
- package/src/resources/extensions/slash-commands/context.ts +15 -8
- package/src/resources/extensions/slash-commands/plan.ts +11 -5
- package/src/resources/extensions/slash-commands/tools.ts +52 -12
|
@@ -48,19 +48,23 @@ export default function contextCommand(pi) {
|
|
|
48
48
|
const descLen = t.description?.length ?? 0;
|
|
49
49
|
const schemaLen = JSON.stringify(t.parameters ?? {}).length;
|
|
50
50
|
const totalChars = nameLen + descLen + schemaLen;
|
|
51
|
+
const isActive = activeToolNames.has(t.name ?? "");
|
|
51
52
|
const tokens = Math.ceil(totalChars / 4);
|
|
52
53
|
return {
|
|
53
54
|
name: t.name ?? "(unnamed)",
|
|
55
|
+
totalChars,
|
|
54
56
|
tokens,
|
|
55
57
|
descTokens: Math.ceil(descLen / 4),
|
|
56
58
|
schemaTokens: Math.ceil((nameLen + schemaLen) / 4),
|
|
57
|
-
isActive
|
|
59
|
+
isActive,
|
|
58
60
|
};
|
|
59
61
|
});
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const
|
|
62
|
+
const activeSchemaBytes = toolSizes
|
|
63
|
+
.filter((t) => t.isActive)
|
|
64
|
+
.reduce((sum, t) => sum + t.totalChars, 0);
|
|
65
|
+
const registeredSchemaBytes = toolSizes.reduce((sum, t) => sum + t.totalChars, 0);
|
|
66
|
+
const activeToolsTokens = Math.ceil(activeSchemaBytes / 4);
|
|
67
|
+
const registeredToolsTokens = Math.ceil(registeredSchemaBytes / 4);
|
|
64
68
|
const largestActiveTools = toolSizes
|
|
65
69
|
.filter((t) => t.isActive)
|
|
66
70
|
.sort((a, b) => b.tokens - a.tokens)
|
|
@@ -84,7 +88,7 @@ export default function contextCommand(pi) {
|
|
|
84
88
|
const windowSize = model?.contextWindow ?? null;
|
|
85
89
|
const usedTokens = contextUsage?.tokens ?? null;
|
|
86
90
|
const percentUsed = contextUsage?.percent ?? null;
|
|
87
|
-
const fallbackUsedTokens = systemPromptTokens +
|
|
91
|
+
const fallbackUsedTokens = systemPromptTokens + activeToolsTokens + historyTokens;
|
|
88
92
|
const effectiveUsedTokens = usedTokens ?? fallbackUsedTokens;
|
|
89
93
|
const estimatedLabel = usedTokens === null ? " (estimated)" : "";
|
|
90
94
|
const freeTokens = windowSize !== null ? windowSize - effectiveUsedTokens : null;
|
|
@@ -129,8 +133,11 @@ export default function contextCommand(pi) {
|
|
|
129
133
|
}
|
|
130
134
|
lines.push("");
|
|
131
135
|
lines.push(`Tools ${activeToolsCount} active / ${totalToolsCount} registered`);
|
|
132
|
-
lines.push(`
|
|
133
|
-
lines.push(` Est. tokens: ~${
|
|
136
|
+
lines.push(` Active schema bytes: ${activeSchemaBytes.toLocaleString()}`);
|
|
137
|
+
lines.push(` Est. tokens: ~${activeToolsTokens.toLocaleString()}`);
|
|
138
|
+
if (activeToolsCount !== totalToolsCount) {
|
|
139
|
+
lines.push(` Registered total: ${registeredSchemaBytes.toLocaleString()} bytes · ~${registeredToolsTokens.toLocaleString()} tok`);
|
|
140
|
+
}
|
|
134
141
|
if (largestActiveTools.length > 0) {
|
|
135
142
|
lines.push(" Largest active tools:");
|
|
136
143
|
for (const tool of largestActiveTools) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
-
import { getAgentDir, getPermissionMode, isToolCallEventType, setPermissionMode, } from "@gsd/pi-coding-agent";
|
|
2
|
+
import { getAgentDir, getPermissionMode, isToolCallEventType, setPermissionMode, SettingsManager, } from "@gsd/pi-coding-agent";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
const PLAN_ENTRY_TYPE = "plan-mode-state";
|
|
5
5
|
const PLAN_APPROVAL_ACTION_QUESTION_ID = "plan_mode_approval_action";
|
|
@@ -133,6 +133,13 @@ function resolveModelFromContext(ctx, modelRef) {
|
|
|
133
133
|
}
|
|
134
134
|
function setPermissionModeAndEnv(mode) {
|
|
135
135
|
setPermissionMode(mode);
|
|
136
|
+
try {
|
|
137
|
+
const settingsManager = SettingsManager.create();
|
|
138
|
+
settingsManager.setPermissionMode(mode);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// Best-effort persistence; if settings manager is unavailable, proceed with in-memory only
|
|
142
|
+
}
|
|
136
143
|
process.env.LUCENT_CODE_PERMISSION_MODE = mode;
|
|
137
144
|
}
|
|
138
145
|
function saveState(pi) {
|
|
@@ -223,13 +230,12 @@ function buildExecutionKickoffMessage(options) {
|
|
|
223
230
|
return details.join(" ");
|
|
224
231
|
}
|
|
225
232
|
const codingModel = readPlanModeCodingModel();
|
|
226
|
-
const
|
|
227
|
-
? `
|
|
228
|
-
:
|
|
233
|
+
const agentInvocationInstruction = codingModel
|
|
234
|
+
? `Invoke the subagent tool with agent "worker" and model="${codingModel}" to implement the plan end-to-end.`
|
|
235
|
+
: `Invoke the subagent tool with agent "worker" to implement the plan end-to-end.`;
|
|
229
236
|
const details = [
|
|
230
237
|
"Plan approved. Exit plan mode and execute the approved plan with a subagent now.",
|
|
231
|
-
|
|
232
|
-
modelInstruction,
|
|
238
|
+
agentInvocationInstruction,
|
|
233
239
|
`Execution permission mode is now \"${permissionMode}\".`,
|
|
234
240
|
];
|
|
235
241
|
if (task)
|
|
@@ -11,10 +11,34 @@ function getCoreToolNames(activeToolNames) {
|
|
|
11
11
|
? ["hashline_read", "bash", "lsp", "tool_search", "tool_enable"]
|
|
12
12
|
: ["read", "bash", "lsp", "tool_search", "tool_enable"];
|
|
13
13
|
}
|
|
14
|
-
function
|
|
14
|
+
function getBalancedToolNames(activeToolNames) {
|
|
15
15
|
return isHashlineMode(activeToolNames)
|
|
16
|
-
? [
|
|
17
|
-
|
|
16
|
+
? [
|
|
17
|
+
"hashline_read",
|
|
18
|
+
"bash",
|
|
19
|
+
"hashline_edit",
|
|
20
|
+
"write",
|
|
21
|
+
"lsp",
|
|
22
|
+
"bg_shell",
|
|
23
|
+
"tool_search",
|
|
24
|
+
"tool_enable",
|
|
25
|
+
"Skill",
|
|
26
|
+
"subagent",
|
|
27
|
+
"await_subagent",
|
|
28
|
+
]
|
|
29
|
+
: [
|
|
30
|
+
"read",
|
|
31
|
+
"bash",
|
|
32
|
+
"edit",
|
|
33
|
+
"write",
|
|
34
|
+
"lsp",
|
|
35
|
+
"bg_shell",
|
|
36
|
+
"tool_search",
|
|
37
|
+
"tool_enable",
|
|
38
|
+
"Skill",
|
|
39
|
+
"subagent",
|
|
40
|
+
"await_subagent",
|
|
41
|
+
];
|
|
18
42
|
}
|
|
19
43
|
function scoreTool(query, tool) {
|
|
20
44
|
const name = (tool.name ?? "").toLowerCase();
|
|
@@ -134,25 +158,29 @@ export default function toolSearchExtension(pi) {
|
|
|
134
158
|
const input = args.trim();
|
|
135
159
|
const settings = getSettingsManager();
|
|
136
160
|
const currentActive = pi.getActiveTools();
|
|
137
|
-
const
|
|
161
|
+
const toolProfile = settings.getToolProfile();
|
|
162
|
+
const toolSearchEnabled = toolProfile === "minimal";
|
|
138
163
|
if (!input) {
|
|
139
164
|
pi.sendMessage({
|
|
140
165
|
customType: "tools:status",
|
|
141
166
|
content: [
|
|
167
|
+
`Tool profile: ${toolProfile}`,
|
|
142
168
|
`Tool search mode: ${toolSearchEnabled ? "on" : "off"}`,
|
|
143
169
|
`Active tools: ${currentActive.length}`,
|
|
144
170
|
currentActive.length > 0 ? currentActive.join(", ") : "(none)",
|
|
145
171
|
"",
|
|
146
172
|
"Usage:",
|
|
147
|
-
" /tools on
|
|
148
|
-
" /tools off
|
|
173
|
+
" /tools on Enable lazy tool-search mode and switch to a small core tool set",
|
|
174
|
+
" /tools off Disable lazy tool-search mode and restore the balanced tool profile",
|
|
175
|
+
" /tools balanced Switch to the balanced tool profile",
|
|
176
|
+
" /tools minimal Switch to the minimal core tool profile",
|
|
149
177
|
].join("\n"),
|
|
150
178
|
display: true,
|
|
151
179
|
});
|
|
152
180
|
return;
|
|
153
181
|
}
|
|
154
182
|
if (["on", "enable", "mode on"].includes(input)) {
|
|
155
|
-
settings.
|
|
183
|
+
settings.setToolProfile("minimal");
|
|
156
184
|
const nextActive = getCoreToolNames(currentActive);
|
|
157
185
|
pi.setActiveTools(nextActive);
|
|
158
186
|
pi.sendMessage({
|
|
@@ -162,20 +190,31 @@ export default function toolSearchExtension(pi) {
|
|
|
162
190
|
});
|
|
163
191
|
return;
|
|
164
192
|
}
|
|
165
|
-
if (["off", "disable", "mode off"].includes(input)) {
|
|
166
|
-
settings.
|
|
167
|
-
const nextActive =
|
|
193
|
+
if (["off", "disable", "mode off", "balanced", "default"].includes(input)) {
|
|
194
|
+
settings.setToolProfile("balanced");
|
|
195
|
+
const nextActive = getBalancedToolNames(currentActive);
|
|
168
196
|
pi.setActiveTools(nextActive);
|
|
169
197
|
pi.sendMessage({
|
|
170
198
|
customType: "tools:mode",
|
|
171
|
-
content: `
|
|
199
|
+
content: `Balanced tool profile active: ${pi.getActiveTools().join(", ")}`,
|
|
200
|
+
display: true,
|
|
201
|
+
});
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (["minimal", "core"].includes(input)) {
|
|
205
|
+
settings.setToolProfile("minimal");
|
|
206
|
+
const nextActive = getCoreToolNames(currentActive);
|
|
207
|
+
pi.setActiveTools(nextActive);
|
|
208
|
+
pi.sendMessage({
|
|
209
|
+
customType: "tools:mode",
|
|
210
|
+
content: `Minimal tool profile active: ${pi.getActiveTools().join(", ")}`,
|
|
172
211
|
display: true,
|
|
173
212
|
});
|
|
174
213
|
return;
|
|
175
214
|
}
|
|
176
215
|
pi.sendMessage({
|
|
177
216
|
customType: "tools:help",
|
|
178
|
-
content: `Unknown /tools subcommand: ${input}\n\nTry /tools, /tools on, or /tools
|
|
217
|
+
content: `Unknown /tools subcommand: ${input}\n\nTry /tools, /tools on, /tools off, /tools balanced, or /tools minimal.`,
|
|
179
218
|
display: true,
|
|
180
219
|
});
|
|
181
220
|
},
|
|
@@ -16,7 +16,7 @@ interface MinimalModelRegistry {
|
|
|
16
16
|
getAll(): MinimalModel[];
|
|
17
17
|
getAvailable(): MinimalModel[];
|
|
18
18
|
}
|
|
19
|
-
type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
|
|
19
|
+
type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'adaptive';
|
|
20
20
|
interface MinimalSettingsManager {
|
|
21
21
|
getDefaultProvider(): string | undefined;
|
|
22
22
|
getDefaultModel(): string | undefined;
|
package/package.json
CHANGED
|
@@ -179,8 +179,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
179
179
|
/**
|
|
180
180
|
* Thinking/reasoning level for models that support it.
|
|
181
181
|
* Note: "xhigh" is only supported by OpenAI gpt-5.1-codex-max, gpt-5.2, gpt-5.2-codex, gpt-5.3, and gpt-5.3-codex models.
|
|
182
|
+
* Note: "adaptive" is only supported by Claude Opus 4.6 and Sonnet 4.6 — Claude dynamically decides when and how much to think.
|
|
182
183
|
*/
|
|
183
|
-
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
184
|
+
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive";
|
|
184
185
|
/**
|
|
185
186
|
* Extensible interface for custom app messages.
|
|
186
187
|
* Apps can extend via declaration merging:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qB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B,CAAC;IAAC,OAAO,EAAE,YAAY,CAAC;IAAC,qBAAqB,EAAE,qBAAqB,CAAA;CAAE,GAC/F;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,OAAO,EAAE,YAAY,CAAA;CAAE,GAE9C;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAA;CAAE,GACjF;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,GAAG,CAAC;IAAC,aAAa,EAAE,GAAG,CAAA;CAAE,GACtG;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,GAAG,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@gsd/pi-ai\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\n/** Stream function - can return sync or Promise for async config lookup */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * Final tool results are still emitted in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n *\n * Omitted fields keep the original executed tool result values.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/**\n * Configuration for the agent loop.\n */\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after each tool execution to check for user interruptions.\n\t * If messages are returned, remaining tool calls are skipped and\n\t * these messages are added to the context before the next LLM call.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before final tool events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\n\t/**\n\t * When true, tool calls in assistant messages are rendered in the TUI\n\t * but NOT executed locally. Used for providers that handle tool execution\n\t * internally (e.g., Claude Code CLI via Agent SDK).\n\t *\n\t * The agent loop emits tool_execution_start/end events for TUI rendering\n\t * but skips tool.execute() and does not add tool results to context.\n\t */\n\texternalToolExecution?: boolean;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" is only supported by OpenAI gpt-5.1-codex-max, gpt-5.2, gpt-5.2-codex, gpt-5.3, and gpt-5.3-codex models.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Agent state containing all configuration and conversation data.\n */\nexport interface AgentState {\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: AgentTool<any>[];\n\tmessages: AgentMessage[]; // Can include attachments + custom message types\n\tisStreaming: boolean;\n\tstreamMessage: AgentMessage | null;\n\tpendingToolCalls: Set<string>;\n\terror?: string;\n\t/**\n\t * The model currently being used for inference. Set at _runLoop() start,\n\t * cleared when the loop ends. When present, UI should display this instead\n\t * of `model` to avoid showing a stale value after a mid-turn model switch.\n\t */\n\tactiveInferenceModel?: Model<any>;\n}\n\nexport interface AgentToolResult<T> {\n\t// Content blocks supporting text and images\n\tcontent: (TextContent | ImageContent)[];\n\t// Details to be displayed in a UI or logged\n\tdetails: T;\n}\n\n// Callback for streaming tool execution updates\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: AgentMessage[];\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n * These events provide fine-grained lifecycle information for messages, turns, and tool executions.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean };\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@gsd/pi-ai\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\n/** Stream function - can return sync or Promise for async config lookup */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * Final tool results are still emitted in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n *\n * Omitted fields keep the original executed tool result values.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\n/**\n * Configuration for the agent loop.\n */\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after each tool execution to check for user interruptions.\n\t * If messages are returned, remaining tool calls are skipped and\n\t * these messages are added to the context before the next LLM call.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before final tool events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\n\t/**\n\t * When true, tool calls in assistant messages are rendered in the TUI\n\t * but NOT executed locally. Used for providers that handle tool execution\n\t * internally (e.g., Claude Code CLI via Agent SDK).\n\t *\n\t * The agent loop emits tool_execution_start/end events for TUI rendering\n\t * but skips tool.execute() and does not add tool results to context.\n\t */\n\texternalToolExecution?: boolean;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" is only supported by OpenAI gpt-5.1-codex-max, gpt-5.2, gpt-5.2-codex, gpt-5.3, and gpt-5.3-codex models.\n * Note: \"adaptive\" is only supported by Claude Opus 4.6 and Sonnet 4.6 — Claude dynamically decides when and how much to think.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"adaptive\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Agent state containing all configuration and conversation data.\n */\nexport interface AgentState {\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: AgentTool<any>[];\n\tmessages: AgentMessage[]; // Can include attachments + custom message types\n\tisStreaming: boolean;\n\tstreamMessage: AgentMessage | null;\n\tpendingToolCalls: Set<string>;\n\terror?: string;\n\t/**\n\t * The model currently being used for inference. Set at _runLoop() start,\n\t * cleared when the loop ends. When present, UI should display this instead\n\t * of `model` to avoid showing a stale value after a mid-turn model switch.\n\t */\n\tactiveInferenceModel?: Model<any>;\n}\n\nexport interface AgentToolResult<T> {\n\t// Content blocks supporting text and images\n\tcontent: (TextContent | ImageContent)[];\n\t// Details to be displayed in a UI or logged\n\tdetails: T;\n}\n\n// Callback for streaming tool execution updates\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: AgentMessage[];\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n * These events provide fine-grained lifecycle information for messages, turns, and tool executions.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean };\n"]}
|
|
@@ -208,8 +208,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
208
208
|
/**
|
|
209
209
|
* Thinking/reasoning level for models that support it.
|
|
210
210
|
* Note: "xhigh" is only supported by OpenAI gpt-5.1-codex-max, gpt-5.2, gpt-5.2-codex, gpt-5.3, and gpt-5.3-codex models.
|
|
211
|
+
* Note: "adaptive" is only supported by Claude Opus 4.6 and Sonnet 4.6 — Claude dynamically decides when and how much to think.
|
|
211
212
|
*/
|
|
212
|
-
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
213
|
+
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "adaptive";
|
|
213
214
|
|
|
214
215
|
/**
|
|
215
216
|
* Extensible interface for custom app messages.
|
|
@@ -291,6 +291,9 @@ function supportsAdaptiveThinking(modelId) {
|
|
|
291
291
|
}
|
|
292
292
|
function mapThinkingLevelToEffort(level, modelId) {
|
|
293
293
|
switch (level) {
|
|
294
|
+
case "adaptive":
|
|
295
|
+
// No effort override — let Claude decide based on request complexity
|
|
296
|
+
return undefined;
|
|
294
297
|
case "minimal":
|
|
295
298
|
case "low":
|
|
296
299
|
return "low";
|
|
@@ -541,21 +544,25 @@ function buildAdditionalModelRequestFields(model, options) {
|
|
|
541
544
|
return undefined;
|
|
542
545
|
}
|
|
543
546
|
if (model.id.includes("anthropic.claude") || model.id.includes("anthropic/claude")) {
|
|
547
|
+
const adaptiveEffort = supportsAdaptiveThinking(model.id)
|
|
548
|
+
? mapThinkingLevelToEffort(options.reasoning, model.id)
|
|
549
|
+
: undefined;
|
|
544
550
|
const result = supportsAdaptiveThinking(model.id)
|
|
545
551
|
? {
|
|
546
552
|
thinking: { type: "adaptive" },
|
|
547
|
-
output_config: { effort:
|
|
553
|
+
...(adaptiveEffort != null ? { output_config: { effort: adaptiveEffort } } : {}),
|
|
548
554
|
}
|
|
549
555
|
: (() => {
|
|
550
556
|
const defaultBudgets = {
|
|
557
|
+
adaptive: 16384, // Fallback for old models that don't support adaptive
|
|
551
558
|
minimal: 1024,
|
|
552
559
|
low: 2048,
|
|
553
560
|
medium: 8192,
|
|
554
561
|
high: 16384,
|
|
555
562
|
xhigh: 16384, // Claude doesn't support xhigh, clamp to high
|
|
556
563
|
};
|
|
557
|
-
// Custom budgets override defaults (xhigh not in ThinkingBudgets, use high)
|
|
558
|
-
const level = options.reasoning === "xhigh" ? "high" : options.reasoning;
|
|
564
|
+
// Custom budgets override defaults (xhigh/adaptive not in ThinkingBudgets, use high)
|
|
565
|
+
const level = options.reasoning === "xhigh" || options.reasoning === "adaptive" ? "high" : options.reasoning;
|
|
559
566
|
const budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];
|
|
560
567
|
return {
|
|
561
568
|
thinking: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"amazon-bedrock.js","sourceRoot":"","sources":["../../src/providers/amazon-bedrock.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,oBAAoB,EAEpB,UAAU,IAAI,iBAAiB,EAE/B,cAAc,EACd,QAAQ,EAKR,gBAAgB,EAChB,qBAAqB,EAErB,WAAW,EAKX,gBAAgB,GAChB,MAAM,iCAAiC,CAAC;AAEzC,O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,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAC9C,KAAK,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import {\n\tBedrockRuntimeClient,\n\ttype BedrockRuntimeClientConfig,\n\tStopReason as BedrockStopReason,\n\ttype Tool as BedrockTool,\n\tCachePointType,\n\tCacheTTL,\n\ttype ContentBlock,\n\ttype ContentBlockDeltaEvent,\n\ttype ContentBlockStartEvent,\n\ttype ContentBlockStopEvent,\n\tConversationRole,\n\tConverseStreamCommand,\n\ttype ConverseStreamMetadataEvent,\n\tImageFormat,\n\ttype Message,\n\ttype SystemContentBlock,\n\ttype ToolChoice,\n\ttype ToolConfiguration,\n\tToolResultStatus,\n} from \"@aws-sdk/client-bedrock-runtime\";\n\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampReasoning } from \"./simple-options.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\nexport interface BedrockOptions extends StreamOptions {\n\tregion?: string;\n\tprofile?: string;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/* See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html for supported models. */\n\treasoning?: ThinkingLevel;\n\t/* Custom token budgets per thinking level. Overrides default budgets. */\n\tthinkingBudgets?: ThinkingBudgets;\n\t/* Only supported by Claude 4.x models, see https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html#claude-messages-extended-thinking-tool-use-interleaved */\n\tinterleavedThinking?: boolean;\n}\n\ntype Block = (TextContent | ThinkingContent | ToolCall) & { index?: number; partialJson?: string };\n\nexport const streamBedrock: StreamFunction<\"bedrock-converse-stream\", BedrockOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions: BedrockOptions = {},\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"bedrock-converse-stream\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tconst blocks = output.content as Block[];\n\n\t\tconst config: BedrockRuntimeClientConfig = {\n\t\t\tprofile: options.profile,\n\t\t};\n\n\t\t// in Node.js/Bun environment only\n\t\tif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\t\t\t// Region resolution: explicit option > env vars > SDK default chain.\n\t\t\t// When AWS_PROFILE is set, we leave region undefined so the SDK can\n\t\t\t// resovle it from aws profile configs. Otherwise fall back to us-east-1.\n\t\t\tconst explicitRegion = options.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION;\n\t\t\tif (explicitRegion) {\n\t\t\t\tconfig.region = explicitRegion;\n\t\t\t} else if (!process.env.AWS_PROFILE) {\n\t\t\t\tconfig.region = \"us-east-1\";\n\t\t\t}\n\n\t\t\t// Support proxies that don't need authentication\n\t\t\tif (process.env.AWS_BEDROCK_SKIP_AUTH === \"1\") {\n\t\t\t\tconfig.credentials = {\n\t\t\t\t\taccessKeyId: \"dummy-access-key\",\n\t\t\t\t\tsecretAccessKey: \"dummy-secret-key\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tprocess.env.HTTP_PROXY ||\n\t\t\t\tprocess.env.HTTPS_PROXY ||\n\t\t\t\tprocess.env.NO_PROXY ||\n\t\t\t\tprocess.env.http_proxy ||\n\t\t\t\tprocess.env.https_proxy ||\n\t\t\t\tprocess.env.no_proxy\n\t\t\t) {\n\t\t\t\tconst nodeHttpHandler = await import(\"@smithy/node-http-handler\");\n\t\t\t\tconst proxyAgent = await import(\"proxy-agent\");\n\n\t\t\t\tconst agent = new proxyAgent.ProxyAgent();\n\n\t\t\t\t// Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based\n\t\t\t\t// on `http2` module and has no support for http agent.\n\t\t\t\t// Use NodeHttpHandler to support http agent.\n\t\t\t\tconfig.requestHandler = new nodeHttpHandler.NodeHttpHandler({\n\t\t\t\t\thttpAgent: agent,\n\t\t\t\t\thttpsAgent: agent,\n\t\t\t\t});\n\t\t\t} else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === \"1\") {\n\t\t\t\t// Some custom endpoints require HTTP/1.1 instead of HTTP/2\n\t\t\t\tconst nodeHttpHandler = await import(\"@smithy/node-http-handler\");\n\t\t\t\tconfig.requestHandler = new nodeHttpHandler.NodeHttpHandler();\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-Node environment (browser): fall back to us-east-1 since\n\t\t\t// there's no config file resolution available.\n\t\t\tconfig.region = options.region || \"us-east-1\";\n\t\t}\n\n\t\ttry {\n\t\t\tconst client = new BedrockRuntimeClient(config);\n\n\t\t\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\t\t\tlet commandInput = {\n\t\t\t\tmodelId: model.id,\n\t\t\t\tmessages: convertMessages(context, model, cacheRetention),\n\t\t\t\tsystem: buildSystemPrompt(context.systemPrompt, model, cacheRetention),\n\t\t\t\tinferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature },\n\t\t\t\ttoolConfig: convertToolConfig(context.tools, options.toolChoice),\n\t\t\t\tadditionalModelRequestFields: buildAdditionalModelRequestFields(model, options),\n\t\t\t};\n\t\t\tconst nextCommandInput = await options?.onPayload?.(commandInput, model);\n\t\t\tif (nextCommandInput !== undefined) {\n\t\t\t\tcommandInput = nextCommandInput as typeof commandInput;\n\t\t\t}\n\t\t\tconst command = new ConverseStreamCommand(commandInput);\n\n\t\t\tconst response = await client.send(command, { abortSignal: options.signal });\n\n\t\t\tfor await (const item of response.stream!) {\n\t\t\t\tif (item.messageStart) {\n\t\t\t\t\tif (item.messageStart.role !== ConversationRole.ASSISTANT) {\n\t\t\t\t\t\tthrow new Error(\"Unexpected assistant message start but got user message start instead\");\n\t\t\t\t\t}\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t} else if (item.contentBlockStart) {\n\t\t\t\t\thandleContentBlockStart(item.contentBlockStart, blocks, output, stream);\n\t\t\t\t} else if (item.contentBlockDelta) {\n\t\t\t\t\thandleContentBlockDelta(item.contentBlockDelta, blocks, output, stream);\n\t\t\t\t} else if (item.contentBlockStop) {\n\t\t\t\t\thandleContentBlockStop(item.contentBlockStop, blocks, output, stream);\n\t\t\t\t} else if (item.messageStop) {\n\t\t\t\t\toutput.stopReason = mapStopReason(item.messageStop.stopReason);\n\t\t\t\t} else if (item.metadata) {\n\t\t\t\t\thandleMetadata(item.metadata, model, output);\n\t\t\t\t} else if (item.internalServerException) {\n\t\t\t\t\tthrow new Error(`Internal server error: ${item.internalServerException.message}`);\n\t\t\t\t} else if (item.modelStreamErrorException) {\n\t\t\t\t\tthrow new Error(`Model stream error: ${item.modelStreamErrorException.message}`);\n\t\t\t\t} else if (item.validationException) {\n\t\t\t\t\tthrow new Error(`Validation error: ${item.validationException.message}`);\n\t\t\t\t} else if (item.throttlingException) {\n\t\t\t\t\tthrow new Error(`Throttling error: ${item.throttlingException.message}`);\n\t\t\t\t} else if (item.serviceUnavailableException) {\n\t\t\t\t\tthrow new Error(`Service unavailable: ${item.serviceUnavailableException.message}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"error\" || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as Block).index;\n\t\t\t\tdelete (block as Block).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleBedrock: StreamFunction<\"bedrock-converse-stream\", SimpleStreamOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst base = buildBaseOptions(model, options, undefined);\n\tif (!options?.reasoning) {\n\t\treturn streamBedrock(model, context, { ...base, reasoning: undefined } satisfies BedrockOptions);\n\t}\n\n\tif (model.id.includes(\"anthropic.claude\") || model.id.includes(\"anthropic/claude\")) {\n\t\tif (supportsAdaptiveThinking(model.id)) {\n\t\t\treturn streamBedrock(model, context, {\n\t\t\t\t...base,\n\t\t\t\treasoning: options.reasoning,\n\t\t\t\tthinkingBudgets: options.thinkingBudgets,\n\t\t\t} satisfies BedrockOptions);\n\t\t}\n\n\t\tconst adjusted = adjustMaxTokensForThinking(\n\t\t\tbase.maxTokens || 0,\n\t\t\tmodel.maxTokens,\n\t\t\toptions.reasoning,\n\t\t\toptions.thinkingBudgets,\n\t\t);\n\n\t\treturn streamBedrock(model, context, {\n\t\t\t...base,\n\t\t\tmaxTokens: adjusted.maxTokens,\n\t\t\treasoning: options.reasoning,\n\t\t\tthinkingBudgets: {\n\t\t\t\t...(options.thinkingBudgets || {}),\n\t\t\t\t[clampReasoning(options.reasoning)!]: adjusted.thinkingBudget,\n\t\t\t},\n\t\t} satisfies BedrockOptions);\n\t}\n\n\treturn streamBedrock(model, context, {\n\t\t...base,\n\t\treasoning: options.reasoning,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t} satisfies BedrockOptions);\n};\n\nfunction handleContentBlockStart(\n\tevent: ContentBlockStartEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = event.contentBlockIndex!;\n\tconst start = event.start;\n\n\tif (start?.toolUse) {\n\t\tconst block: Block = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: start.toolUse.toolUseId || \"\",\n\t\t\tname: start.toolUse.name || \"\",\n\t\t\targuments: {},\n\t\t\tpartialJson: \"\",\n\t\t\tindex,\n\t\t};\n\t\toutput.content.push(block);\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: blocks.length - 1, partial: output });\n\t}\n}\n\nfunction handleContentBlockDelta(\n\tevent: ContentBlockDeltaEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst contentBlockIndex = event.contentBlockIndex!;\n\tconst delta = event.delta;\n\tlet index = blocks.findIndex((b) => b.index === contentBlockIndex);\n\tlet block = blocks[index];\n\n\tif (delta?.text !== undefined) {\n\t\t// If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks\n\t\tif (!block) {\n\t\t\tconst newBlock: Block = { type: \"text\", text: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tindex = blocks.length - 1;\n\t\t\tblock = blocks[index];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: output });\n\t\t}\n\t\tif (block.type === \"text\") {\n\t\t\tblock.text += delta.text;\n\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: delta.text, partial: output });\n\t\t}\n\t} else if (delta?.toolUse && block?.type === \"toolCall\") {\n\t\tblock.partialJson = (block.partialJson || \"\") + (delta.toolUse.input || \"\");\n\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: delta.toolUse.input || \"\", partial: output });\n\t} else if (delta?.reasoningContent) {\n\t\tlet thinkingBlock = block;\n\t\tlet thinkingIndex = index;\n\n\t\tif (!thinkingBlock) {\n\t\t\tconst newBlock: Block = { type: \"thinking\", thinking: \"\", thinkingSignature: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tthinkingIndex = blocks.length - 1;\n\t\t\tthinkingBlock = blocks[thinkingIndex];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: thinkingIndex, partial: output });\n\t\t}\n\n\t\tif (thinkingBlock?.type === \"thinking\") {\n\t\t\tif (delta.reasoningContent.text) {\n\t\t\t\tthinkingBlock.thinking += delta.reasoningContent.text;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: thinkingIndex,\n\t\t\t\t\tdelta: delta.reasoningContent.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (delta.reasoningContent.signature) {\n\t\t\t\tthinkingBlock.thinkingSignature =\n\t\t\t\t\t(thinkingBlock.thinkingSignature || \"\") + delta.reasoningContent.signature;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction handleMetadata(\n\tevent: ConverseStreamMetadataEvent,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toutput: AssistantMessage,\n): void {\n\tif (event.usage) {\n\t\toutput.usage.input = event.usage.inputTokens || 0;\n\t\toutput.usage.output = event.usage.outputTokens || 0;\n\t\toutput.usage.cacheRead = event.usage.cacheReadInputTokens || 0;\n\t\toutput.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0;\n\t\toutput.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output;\n\t\tcalculateCost(model, output.usage);\n\t}\n}\n\nfunction handleContentBlockStop(\n\tevent: ContentBlockStopEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = blocks.findIndex((b) => b.index === event.contentBlockIndex);\n\tconst block = blocks[index];\n\tif (!block) return;\n\tdelete (block as Block).index;\n\n\tswitch (block.type) {\n\t\tcase \"text\":\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: output });\n\t\t\tbreak;\n\t\tcase \"thinking\":\n\t\t\tstream.push({ type: \"thinking_end\", contentIndex: index, content: block.thinking, partial: output });\n\t\t\tbreak;\n\t\tcase \"toolCall\":\n\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\tdelete (block as Block).partialJson;\n\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: output });\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Check if the model supports adaptive thinking (Opus 4.6 and Sonnet 4.6).\n */\nfunction supportsAdaptiveThinking(modelId: string): boolean {\n\treturn (\n\t\tmodelId.includes(\"opus-4-6\") ||\n\t\tmodelId.includes(\"opus-4.6\") ||\n\t\tmodelId.includes(\"sonnet-4-6\") ||\n\t\tmodelId.includes(\"sonnet-4.6\")\n\t);\n}\n\nfunction mapThinkingLevelToEffort(\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n\tmodelId: string,\n): \"low\" | \"medium\" | \"high\" | \"max\" {\n\tswitch (level) {\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\t\treturn \"low\";\n\t\tcase \"medium\":\n\t\t\treturn \"medium\";\n\t\tcase \"high\":\n\t\t\treturn \"high\";\n\t\tcase \"xhigh\":\n\t\t\treturn modelId.includes(\"opus-4-6\") || modelId.includes(\"opus-4.6\") ? \"max\" : \"high\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models\n */\nfunction supportsPromptCaching(model: Model<\"bedrock-converse-stream\">): boolean {\n\tif (model.cost.cacheRead || model.cost.cacheWrite) {\n\t\treturn true;\n\t}\n\n\tconst id = model.id.toLowerCase();\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (id.includes(\"claude\") && (id.includes(\"-4-\") || id.includes(\"-4.\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (id.includes(\"claude-3-7-sonnet\")) return true;\n\t// Claude 3.5 Haiku\n\tif (id.includes(\"claude-3-5-haiku\")) return true;\n\treturn false;\n}\n\n/**\n * Check if the model supports thinking signatures in reasoningContent.\n * Only Anthropic Claude models support the signature field.\n * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with:\n * \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n */\nfunction supportsThinkingSignature(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn id.includes(\"anthropic.claude\") || id.includes(\"anthropic/claude\");\n}\n\nfunction buildSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): SystemContentBlock[] | undefined {\n\tif (!systemPrompt) return undefined;\n\n\tconst blocks: SystemContentBlock[] = [{ text: sanitizeSurrogates(systemPrompt) }];\n\n\t// Add cache point for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model)) {\n\t\tblocks.push({\n\t\t\tcachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}) },\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nfunction normalizeToolCallId(id: string): string {\n\tconst sanitized = id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n}\n\nfunction convertMessages(\n\tcontext: Context,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): Message[] {\n\tconst result: Message[] = [];\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst m = transformedMessages[i];\n\n\t\tswitch (m.role) {\n\t\t\tcase \"user\":\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent:\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ text: sanitizeSurrogates(m.content) }]\n\t\t\t\t\t\t\t: m.content.map((c) => {\n\t\t\t\t\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t\t\t\t\treturn { text: sanitizeSurrogates(c.text) };\n\t\t\t\t\t\t\t\t\t\tcase \"image\":\n\t\t\t\t\t\t\t\t\t\t\treturn { image: createImageBlock(c.mimeType, c.data) };\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Unknown user content type\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\": {\n\t\t\t\t// Skip assistant messages with empty content (e.g., from aborted requests)\n\t\t\t\t// Bedrock rejects messages with empty content arrays\n\t\t\t\tif (m.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentBlocks: ContentBlock[] = [];\n\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t// Skip empty text blocks\n\t\t\t\t\t\t\tif (c.text.trim().length === 0) continue;\n\t\t\t\t\t\t\tcontentBlocks.push({ text: sanitizeSurrogates(c.text) });\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"toolCall\":\n\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\ttoolUse: { toolUseId: c.id, name: c.name, input: c.arguments },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"thinking\":\n\t\t\t\t\t\t\t// Skip empty thinking blocks\n\t\t\t\t\t\t\tif (c.thinking.trim().length === 0) continue;\n\t\t\t\t\t\t\t// Only Anthropic models support the signature field in reasoningText.\n\t\t\t\t\t\t\t// For other models, we omit the signature to avoid errors like:\n\t\t\t\t\t\t\t// \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n\t\t\t\t\t\t\tif (supportsThinkingSignature(model)) {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: sanitizeSurrogates(c.thinking), signature: c.thinkingSignature },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: sanitizeSurrogates(c.thinking) },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tthrow new Error(\"Unknown assistant content type\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Skip if all content blocks were filtered out\n\t\t\t\tif (contentBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.ASSISTANT,\n\t\t\t\t\tcontent: contentBlocks,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Collect all consecutive toolResult messages into a single user message\n\t\t\t\t// Bedrock requires all tool results to be in one message\n\t\t\t\tconst toolResults: ContentBlock.ToolResultMember[] = [];\n\n\t\t\t\t// Add current tool result with all content blocks combined\n\t\t\t\ttoolResults.push({\n\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\ttoolUseId: m.toolCallId,\n\t\t\t\t\t\tcontent: m.content.map((c) =>\n\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t? { image: createImageBlock(c.mimeType, c.data) }\n\t\t\t\t\t\t\t\t: { text: sanitizeSurrogates(c.text) },\n\t\t\t\t\t\t),\n\t\t\t\t\t\tstatus: m.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// Look ahead for consecutive toolResult messages\n\t\t\t\tlet j = i + 1;\n\t\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\t\ttoolResults.push({\n\t\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\t\ttoolUseId: nextMsg.toolCallId,\n\t\t\t\t\t\t\tcontent: nextMsg.content.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t\t? { image: createImageBlock(c.mimeType, c.data) }\n\t\t\t\t\t\t\t\t\t: { text: sanitizeSurrogates(c.text) },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tstatus: nextMsg.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\t// Skip the messages we've already processed\n\t\t\t\ti = j - 1;\n\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent: toolResults,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\"Unknown message role\");\n\t\t}\n\t}\n\n\t// Add cache point to the last user message for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model) && result.length > 0) {\n\t\tconst lastMessage = result[result.length - 1];\n\t\tif (lastMessage.role === ConversationRole.USER && lastMessage.content) {\n\t\t\t(lastMessage.content as ContentBlock[]).push({\n\t\t\t\tcachePoint: {\n\t\t\t\t\ttype: CachePointType.DEFAULT,\n\t\t\t\t\t...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction convertToolConfig(\n\ttools: Tool[] | undefined,\n\ttoolChoice: BedrockOptions[\"toolChoice\"],\n): ToolConfiguration | undefined {\n\tif (!tools?.length || toolChoice === \"none\") return undefined;\n\n\tconst bedrockTools: BedrockTool[] = tools.map((tool) => ({\n\t\ttoolSpec: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: { json: tool.parameters },\n\t\t},\n\t}));\n\n\tlet bedrockToolChoice: ToolChoice | undefined;\n\tswitch (toolChoice) {\n\t\tcase \"auto\":\n\t\t\tbedrockToolChoice = { auto: {} };\n\t\t\tbreak;\n\t\tcase \"any\":\n\t\t\tbedrockToolChoice = { any: {} };\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (toolChoice?.type === \"tool\") {\n\t\t\t\tbedrockToolChoice = { tool: { name: toolChoice.name } };\n\t\t\t}\n\t}\n\n\treturn { tools: bedrockTools, toolChoice: bedrockToolChoice };\n}\n\nfunction mapStopReason(reason: string | undefined): StopReason {\n\tswitch (reason) {\n\t\tcase BedrockStopReason.END_TURN:\n\t\tcase BedrockStopReason.STOP_SEQUENCE:\n\t\t\treturn \"stop\";\n\t\tcase BedrockStopReason.MAX_TOKENS:\n\t\tcase BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:\n\t\t\treturn \"length\";\n\t\tcase BedrockStopReason.TOOL_USE:\n\t\t\treturn \"toolUse\";\n\t\tdefault:\n\t\t\treturn \"error\";\n\t}\n}\n\nfunction buildAdditionalModelRequestFields(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toptions: BedrockOptions,\n): Record<string, any> | undefined {\n\tif (!options.reasoning || !model.reasoning) {\n\t\treturn undefined;\n\t}\n\n\tif (model.id.includes(\"anthropic.claude\") || model.id.includes(\"anthropic/claude\")) {\n\t\tconst result: Record<string, any> = supportsAdaptiveThinking(model.id)\n\t\t\t? {\n\t\t\t\t\tthinking: { type: \"adaptive\" },\n\t\t\t\t\toutput_config: { effort: mapThinkingLevelToEffort(options.reasoning, model.id) },\n\t\t\t\t}\n\t\t\t: (() => {\n\t\t\t\t\tconst defaultBudgets: Record<ThinkingLevel, number> = {\n\t\t\t\t\t\tminimal: 1024,\n\t\t\t\t\t\tlow: 2048,\n\t\t\t\t\t\tmedium: 8192,\n\t\t\t\t\t\thigh: 16384,\n\t\t\t\t\t\txhigh: 16384, // Claude doesn't support xhigh, clamp to high\n\t\t\t\t\t};\n\n\t\t\t\t\t// Custom budgets override defaults (xhigh not in ThinkingBudgets, use high)\n\t\t\t\t\tconst level = options.reasoning === \"xhigh\" ? \"high\" : options.reasoning;\n\t\t\t\t\tconst budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tthinking: {\n\t\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\t\tbudget_tokens: budget,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t})();\n\n\t\tif (!supportsAdaptiveThinking(model.id) && (options.interleavedThinking ?? true)) {\n\t\t\tresult.anthropic_beta = [\"interleaved-thinking-2025-05-14\"];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\treturn undefined;\n}\n\nfunction createImageBlock(mimeType: string, data: string) {\n\tlet format: ImageFormat;\n\tswitch (mimeType) {\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\tformat = ImageFormat.JPEG;\n\t\t\tbreak;\n\t\tcase \"image/png\":\n\t\t\tformat = ImageFormat.PNG;\n\t\t\tbreak;\n\t\tcase \"image/gif\":\n\t\t\tformat = ImageFormat.GIF;\n\t\t\tbreak;\n\t\tcase \"image/webp\":\n\t\t\tformat = ImageFormat.WEBP;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown image type: ${mimeType}`);\n\t}\n\n\tconst binaryString = atob(data);\n\tconst bytes = new Uint8Array(binaryString.length);\n\tfor (let i = 0; i < binaryString.length; i++) {\n\t\tbytes[i] = binaryString.charCodeAt(i);\n\t}\n\n\treturn { source: { bytes }, format };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"amazon-bedrock.js","sourceRoot":"","sources":["../../src/providers/amazon-bedrock.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,oBAAoB,EAEpB,UAAU,IAAI,iBAAiB,EAE/B,cAAc,EACd,QAAQ,EAKR,gBAAgB,EAChB,qBAAqB,EAErB,WAAW,EAKX,gBAAgB,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAmB7C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,KAAK,YAAY;YAChB,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC;YAC1B,MAAM;QACP;YACC,MAAM,IAAI,KAAK,CAAC,uBAAuB,QAAQ,EAAE,CAAC,CAAC;IACrD,CAAC;IAED,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;IAChC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IAClD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAC9C,KAAK,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import {\n\tBedrockRuntimeClient,\n\ttype BedrockRuntimeClientConfig,\n\tStopReason as BedrockStopReason,\n\ttype Tool as BedrockTool,\n\tCachePointType,\n\tCacheTTL,\n\ttype ContentBlock,\n\ttype ContentBlockDeltaEvent,\n\ttype ContentBlockStartEvent,\n\ttype ContentBlockStopEvent,\n\tConversationRole,\n\tConverseStreamCommand,\n\ttype ConverseStreamMetadataEvent,\n\tImageFormat,\n\ttype Message,\n\ttype SystemContentBlock,\n\ttype ToolChoice,\n\ttype ToolConfiguration,\n\tToolResultStatus,\n} from \"@aws-sdk/client-bedrock-runtime\";\n\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampReasoning } from \"./simple-options.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\nexport interface BedrockOptions extends StreamOptions {\n\tregion?: string;\n\tprofile?: string;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/* See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html for supported models. */\n\treasoning?: ThinkingLevel;\n\t/* Custom token budgets per thinking level. Overrides default budgets. */\n\tthinkingBudgets?: ThinkingBudgets;\n\t/* Only supported by Claude 4.x models, see https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html#claude-messages-extended-thinking-tool-use-interleaved */\n\tinterleavedThinking?: boolean;\n}\n\ntype Block = (TextContent | ThinkingContent | ToolCall) & { index?: number; partialJson?: string };\n\nexport const streamBedrock: StreamFunction<\"bedrock-converse-stream\", BedrockOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions: BedrockOptions = {},\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"bedrock-converse-stream\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tconst blocks = output.content as Block[];\n\n\t\tconst config: BedrockRuntimeClientConfig = {\n\t\t\tprofile: options.profile,\n\t\t};\n\n\t\t// in Node.js/Bun environment only\n\t\tif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\t\t\t// Region resolution: explicit option > env vars > SDK default chain.\n\t\t\t// When AWS_PROFILE is set, we leave region undefined so the SDK can\n\t\t\t// resovle it from aws profile configs. Otherwise fall back to us-east-1.\n\t\t\tconst explicitRegion = options.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION;\n\t\t\tif (explicitRegion) {\n\t\t\t\tconfig.region = explicitRegion;\n\t\t\t} else if (!process.env.AWS_PROFILE) {\n\t\t\t\tconfig.region = \"us-east-1\";\n\t\t\t}\n\n\t\t\t// Support proxies that don't need authentication\n\t\t\tif (process.env.AWS_BEDROCK_SKIP_AUTH === \"1\") {\n\t\t\t\tconfig.credentials = {\n\t\t\t\t\taccessKeyId: \"dummy-access-key\",\n\t\t\t\t\tsecretAccessKey: \"dummy-secret-key\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tprocess.env.HTTP_PROXY ||\n\t\t\t\tprocess.env.HTTPS_PROXY ||\n\t\t\t\tprocess.env.NO_PROXY ||\n\t\t\t\tprocess.env.http_proxy ||\n\t\t\t\tprocess.env.https_proxy ||\n\t\t\t\tprocess.env.no_proxy\n\t\t\t) {\n\t\t\t\tconst nodeHttpHandler = await import(\"@smithy/node-http-handler\");\n\t\t\t\tconst proxyAgent = await import(\"proxy-agent\");\n\n\t\t\t\tconst agent = new proxyAgent.ProxyAgent();\n\n\t\t\t\t// Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based\n\t\t\t\t// on `http2` module and has no support for http agent.\n\t\t\t\t// Use NodeHttpHandler to support http agent.\n\t\t\t\tconfig.requestHandler = new nodeHttpHandler.NodeHttpHandler({\n\t\t\t\t\thttpAgent: agent,\n\t\t\t\t\thttpsAgent: agent,\n\t\t\t\t});\n\t\t\t} else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === \"1\") {\n\t\t\t\t// Some custom endpoints require HTTP/1.1 instead of HTTP/2\n\t\t\t\tconst nodeHttpHandler = await import(\"@smithy/node-http-handler\");\n\t\t\t\tconfig.requestHandler = new nodeHttpHandler.NodeHttpHandler();\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-Node environment (browser): fall back to us-east-1 since\n\t\t\t// there's no config file resolution available.\n\t\t\tconfig.region = options.region || \"us-east-1\";\n\t\t}\n\n\t\ttry {\n\t\t\tconst client = new BedrockRuntimeClient(config);\n\n\t\t\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\t\t\tlet commandInput = {\n\t\t\t\tmodelId: model.id,\n\t\t\t\tmessages: convertMessages(context, model, cacheRetention),\n\t\t\t\tsystem: buildSystemPrompt(context.systemPrompt, model, cacheRetention),\n\t\t\t\tinferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature },\n\t\t\t\ttoolConfig: convertToolConfig(context.tools, options.toolChoice),\n\t\t\t\tadditionalModelRequestFields: buildAdditionalModelRequestFields(model, options),\n\t\t\t};\n\t\t\tconst nextCommandInput = await options?.onPayload?.(commandInput, model);\n\t\t\tif (nextCommandInput !== undefined) {\n\t\t\t\tcommandInput = nextCommandInput as typeof commandInput;\n\t\t\t}\n\t\t\tconst command = new ConverseStreamCommand(commandInput);\n\n\t\t\tconst response = await client.send(command, { abortSignal: options.signal });\n\n\t\t\tfor await (const item of response.stream!) {\n\t\t\t\tif (item.messageStart) {\n\t\t\t\t\tif (item.messageStart.role !== ConversationRole.ASSISTANT) {\n\t\t\t\t\t\tthrow new Error(\"Unexpected assistant message start but got user message start instead\");\n\t\t\t\t\t}\n\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t} else if (item.contentBlockStart) {\n\t\t\t\t\thandleContentBlockStart(item.contentBlockStart, blocks, output, stream);\n\t\t\t\t} else if (item.contentBlockDelta) {\n\t\t\t\t\thandleContentBlockDelta(item.contentBlockDelta, blocks, output, stream);\n\t\t\t\t} else if (item.contentBlockStop) {\n\t\t\t\t\thandleContentBlockStop(item.contentBlockStop, blocks, output, stream);\n\t\t\t\t} else if (item.messageStop) {\n\t\t\t\t\toutput.stopReason = mapStopReason(item.messageStop.stopReason);\n\t\t\t\t} else if (item.metadata) {\n\t\t\t\t\thandleMetadata(item.metadata, model, output);\n\t\t\t\t} else if (item.internalServerException) {\n\t\t\t\t\tthrow new Error(`Internal server error: ${item.internalServerException.message}`);\n\t\t\t\t} else if (item.modelStreamErrorException) {\n\t\t\t\t\tthrow new Error(`Model stream error: ${item.modelStreamErrorException.message}`);\n\t\t\t\t} else if (item.validationException) {\n\t\t\t\t\tthrow new Error(`Validation error: ${item.validationException.message}`);\n\t\t\t\t} else if (item.throttlingException) {\n\t\t\t\t\tthrow new Error(`Throttling error: ${item.throttlingException.message}`);\n\t\t\t\t} else if (item.serviceUnavailableException) {\n\t\t\t\t\tthrow new Error(`Service unavailable: ${item.serviceUnavailableException.message}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"error\" || output.stopReason === \"aborted\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as Block).index;\n\t\t\t\tdelete (block as Block).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleBedrock: StreamFunction<\"bedrock-converse-stream\", SimpleStreamOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst base = buildBaseOptions(model, options, undefined);\n\tif (!options?.reasoning) {\n\t\treturn streamBedrock(model, context, { ...base, reasoning: undefined } satisfies BedrockOptions);\n\t}\n\n\tif (model.id.includes(\"anthropic.claude\") || model.id.includes(\"anthropic/claude\")) {\n\t\tif (supportsAdaptiveThinking(model.id)) {\n\t\t\treturn streamBedrock(model, context, {\n\t\t\t\t...base,\n\t\t\t\treasoning: options.reasoning,\n\t\t\t\tthinkingBudgets: options.thinkingBudgets,\n\t\t\t} satisfies BedrockOptions);\n\t\t}\n\n\t\tconst adjusted = adjustMaxTokensForThinking(\n\t\t\tbase.maxTokens || 0,\n\t\t\tmodel.maxTokens,\n\t\t\toptions.reasoning,\n\t\t\toptions.thinkingBudgets,\n\t\t);\n\n\t\treturn streamBedrock(model, context, {\n\t\t\t...base,\n\t\t\tmaxTokens: adjusted.maxTokens,\n\t\t\treasoning: options.reasoning,\n\t\t\tthinkingBudgets: {\n\t\t\t\t...(options.thinkingBudgets || {}),\n\t\t\t\t[clampReasoning(options.reasoning)!]: adjusted.thinkingBudget,\n\t\t\t},\n\t\t} satisfies BedrockOptions);\n\t}\n\n\treturn streamBedrock(model, context, {\n\t\t...base,\n\t\treasoning: options.reasoning,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t} satisfies BedrockOptions);\n};\n\nfunction handleContentBlockStart(\n\tevent: ContentBlockStartEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = event.contentBlockIndex!;\n\tconst start = event.start;\n\n\tif (start?.toolUse) {\n\t\tconst block: Block = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: start.toolUse.toolUseId || \"\",\n\t\t\tname: start.toolUse.name || \"\",\n\t\t\targuments: {},\n\t\t\tpartialJson: \"\",\n\t\t\tindex,\n\t\t};\n\t\toutput.content.push(block);\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: blocks.length - 1, partial: output });\n\t}\n}\n\nfunction handleContentBlockDelta(\n\tevent: ContentBlockDeltaEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst contentBlockIndex = event.contentBlockIndex!;\n\tconst delta = event.delta;\n\tlet index = blocks.findIndex((b) => b.index === contentBlockIndex);\n\tlet block = blocks[index];\n\n\tif (delta?.text !== undefined) {\n\t\t// If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks\n\t\tif (!block) {\n\t\t\tconst newBlock: Block = { type: \"text\", text: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tindex = blocks.length - 1;\n\t\t\tblock = blocks[index];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: output });\n\t\t}\n\t\tif (block.type === \"text\") {\n\t\t\tblock.text += delta.text;\n\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: delta.text, partial: output });\n\t\t}\n\t} else if (delta?.toolUse && block?.type === \"toolCall\") {\n\t\tblock.partialJson = (block.partialJson || \"\") + (delta.toolUse.input || \"\");\n\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: delta.toolUse.input || \"\", partial: output });\n\t} else if (delta?.reasoningContent) {\n\t\tlet thinkingBlock = block;\n\t\tlet thinkingIndex = index;\n\n\t\tif (!thinkingBlock) {\n\t\t\tconst newBlock: Block = { type: \"thinking\", thinking: \"\", thinkingSignature: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tthinkingIndex = blocks.length - 1;\n\t\t\tthinkingBlock = blocks[thinkingIndex];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: thinkingIndex, partial: output });\n\t\t}\n\n\t\tif (thinkingBlock?.type === \"thinking\") {\n\t\t\tif (delta.reasoningContent.text) {\n\t\t\t\tthinkingBlock.thinking += delta.reasoningContent.text;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: thinkingIndex,\n\t\t\t\t\tdelta: delta.reasoningContent.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (delta.reasoningContent.signature) {\n\t\t\t\tthinkingBlock.thinkingSignature =\n\t\t\t\t\t(thinkingBlock.thinkingSignature || \"\") + delta.reasoningContent.signature;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction handleMetadata(\n\tevent: ConverseStreamMetadataEvent,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toutput: AssistantMessage,\n): void {\n\tif (event.usage) {\n\t\toutput.usage.input = event.usage.inputTokens || 0;\n\t\toutput.usage.output = event.usage.outputTokens || 0;\n\t\toutput.usage.cacheRead = event.usage.cacheReadInputTokens || 0;\n\t\toutput.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0;\n\t\toutput.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output;\n\t\tcalculateCost(model, output.usage);\n\t}\n}\n\nfunction handleContentBlockStop(\n\tevent: ContentBlockStopEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = blocks.findIndex((b) => b.index === event.contentBlockIndex);\n\tconst block = blocks[index];\n\tif (!block) return;\n\tdelete (block as Block).index;\n\n\tswitch (block.type) {\n\t\tcase \"text\":\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: output });\n\t\t\tbreak;\n\t\tcase \"thinking\":\n\t\t\tstream.push({ type: \"thinking_end\", contentIndex: index, content: block.thinking, partial: output });\n\t\t\tbreak;\n\t\tcase \"toolCall\":\n\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\tdelete (block as Block).partialJson;\n\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: output });\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Check if the model supports adaptive thinking (Opus 4.6 and Sonnet 4.6).\n */\nfunction supportsAdaptiveThinking(modelId: string): boolean {\n\treturn (\n\t\tmodelId.includes(\"opus-4-6\") ||\n\t\tmodelId.includes(\"opus-4.6\") ||\n\t\tmodelId.includes(\"sonnet-4-6\") ||\n\t\tmodelId.includes(\"sonnet-4.6\")\n\t);\n}\n\nfunction mapThinkingLevelToEffort(\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n\tmodelId: string,\n): \"low\" | \"medium\" | \"high\" | \"max\" | undefined {\n\tswitch (level) {\n\t\tcase \"adaptive\":\n\t\t\t// No effort override — let Claude decide based on request complexity\n\t\t\treturn undefined;\n\t\tcase \"minimal\":\n\t\tcase \"low\":\n\t\t\treturn \"low\";\n\t\tcase \"medium\":\n\t\t\treturn \"medium\";\n\t\tcase \"high\":\n\t\t\treturn \"high\";\n\t\tcase \"xhigh\":\n\t\t\treturn modelId.includes(\"opus-4-6\") || modelId.includes(\"opus-4.6\") ? \"max\" : \"high\";\n\t\tdefault:\n\t\t\treturn \"high\";\n\t}\n}\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses PI_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.PI_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models\n */\nfunction supportsPromptCaching(model: Model<\"bedrock-converse-stream\">): boolean {\n\tif (model.cost.cacheRead || model.cost.cacheWrite) {\n\t\treturn true;\n\t}\n\n\tconst id = model.id.toLowerCase();\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (id.includes(\"claude\") && (id.includes(\"-4-\") || id.includes(\"-4.\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (id.includes(\"claude-3-7-sonnet\")) return true;\n\t// Claude 3.5 Haiku\n\tif (id.includes(\"claude-3-5-haiku\")) return true;\n\treturn false;\n}\n\n/**\n * Check if the model supports thinking signatures in reasoningContent.\n * Only Anthropic Claude models support the signature field.\n * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with:\n * \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n */\nfunction supportsThinkingSignature(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst id = model.id.toLowerCase();\n\treturn id.includes(\"anthropic.claude\") || id.includes(\"anthropic/claude\");\n}\n\nfunction buildSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): SystemContentBlock[] | undefined {\n\tif (!systemPrompt) return undefined;\n\n\tconst blocks: SystemContentBlock[] = [{ text: sanitizeSurrogates(systemPrompt) }];\n\n\t// Add cache point for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model)) {\n\t\tblocks.push({\n\t\t\tcachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}) },\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nfunction normalizeToolCallId(id: string): string {\n\tconst sanitized = id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n}\n\nfunction convertMessages(\n\tcontext: Context,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): Message[] {\n\tconst result: Message[] = [];\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst m = transformedMessages[i];\n\n\t\tswitch (m.role) {\n\t\t\tcase \"user\":\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent:\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ text: sanitizeSurrogates(m.content) }]\n\t\t\t\t\t\t\t: m.content.map((c) => {\n\t\t\t\t\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t\t\t\t\treturn { text: sanitizeSurrogates(c.text) };\n\t\t\t\t\t\t\t\t\t\tcase \"image\":\n\t\t\t\t\t\t\t\t\t\t\treturn { image: createImageBlock(c.mimeType, c.data) };\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Unknown user content type\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\": {\n\t\t\t\t// Skip assistant messages with empty content (e.g., from aborted requests)\n\t\t\t\t// Bedrock rejects messages with empty content arrays\n\t\t\t\tif (m.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentBlocks: ContentBlock[] = [];\n\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\t// Skip empty text blocks\n\t\t\t\t\t\t\tif (c.text.trim().length === 0) continue;\n\t\t\t\t\t\t\tcontentBlocks.push({ text: sanitizeSurrogates(c.text) });\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"toolCall\":\n\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\ttoolUse: { toolUseId: c.id, name: c.name, input: c.arguments },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"thinking\":\n\t\t\t\t\t\t\t// Skip empty thinking blocks\n\t\t\t\t\t\t\tif (c.thinking.trim().length === 0) continue;\n\t\t\t\t\t\t\t// Only Anthropic models support the signature field in reasoningText.\n\t\t\t\t\t\t\t// For other models, we omit the signature to avoid errors like:\n\t\t\t\t\t\t\t// \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n\t\t\t\t\t\t\tif (supportsThinkingSignature(model)) {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: sanitizeSurrogates(c.thinking), signature: c.thinkingSignature },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: sanitizeSurrogates(c.thinking) },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tthrow new Error(\"Unknown assistant content type\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Skip if all content blocks were filtered out\n\t\t\t\tif (contentBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.ASSISTANT,\n\t\t\t\t\tcontent: contentBlocks,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Collect all consecutive toolResult messages into a single user message\n\t\t\t\t// Bedrock requires all tool results to be in one message\n\t\t\t\tconst toolResults: ContentBlock.ToolResultMember[] = [];\n\n\t\t\t\t// Add current tool result with all content blocks combined\n\t\t\t\ttoolResults.push({\n\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\ttoolUseId: m.toolCallId,\n\t\t\t\t\t\tcontent: m.content.map((c) =>\n\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t? { image: createImageBlock(c.mimeType, c.data) }\n\t\t\t\t\t\t\t\t: { text: sanitizeSurrogates(c.text) },\n\t\t\t\t\t\t),\n\t\t\t\t\t\tstatus: m.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// Look ahead for consecutive toolResult messages\n\t\t\t\tlet j = i + 1;\n\t\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\t\ttoolResults.push({\n\t\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\t\ttoolUseId: nextMsg.toolCallId,\n\t\t\t\t\t\t\tcontent: nextMsg.content.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\"\n\t\t\t\t\t\t\t\t\t? { image: createImageBlock(c.mimeType, c.data) }\n\t\t\t\t\t\t\t\t\t: { text: sanitizeSurrogates(c.text) },\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tstatus: nextMsg.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\t// Skip the messages we've already processed\n\t\t\t\ti = j - 1;\n\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent: toolResults,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\"Unknown message role\");\n\t\t}\n\t}\n\n\t// Add cache point to the last user message for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model) && result.length > 0) {\n\t\tconst lastMessage = result[result.length - 1];\n\t\tif (lastMessage.role === ConversationRole.USER && lastMessage.content) {\n\t\t\t(lastMessage.content as ContentBlock[]).push({\n\t\t\t\tcachePoint: {\n\t\t\t\t\ttype: CachePointType.DEFAULT,\n\t\t\t\t\t...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction convertToolConfig(\n\ttools: Tool[] | undefined,\n\ttoolChoice: BedrockOptions[\"toolChoice\"],\n): ToolConfiguration | undefined {\n\tif (!tools?.length || toolChoice === \"none\") return undefined;\n\n\tconst bedrockTools: BedrockTool[] = tools.map((tool) => ({\n\t\ttoolSpec: {\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: { json: tool.parameters },\n\t\t},\n\t}));\n\n\tlet bedrockToolChoice: ToolChoice | undefined;\n\tswitch (toolChoice) {\n\t\tcase \"auto\":\n\t\t\tbedrockToolChoice = { auto: {} };\n\t\t\tbreak;\n\t\tcase \"any\":\n\t\t\tbedrockToolChoice = { any: {} };\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (toolChoice?.type === \"tool\") {\n\t\t\t\tbedrockToolChoice = { tool: { name: toolChoice.name } };\n\t\t\t}\n\t}\n\n\treturn { tools: bedrockTools, toolChoice: bedrockToolChoice };\n}\n\nfunction mapStopReason(reason: string | undefined): StopReason {\n\tswitch (reason) {\n\t\tcase BedrockStopReason.END_TURN:\n\t\tcase BedrockStopReason.STOP_SEQUENCE:\n\t\t\treturn \"stop\";\n\t\tcase BedrockStopReason.MAX_TOKENS:\n\t\tcase BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:\n\t\t\treturn \"length\";\n\t\tcase BedrockStopReason.TOOL_USE:\n\t\t\treturn \"toolUse\";\n\t\tdefault:\n\t\t\treturn \"error\";\n\t}\n}\n\nfunction buildAdditionalModelRequestFields(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toptions: BedrockOptions,\n): Record<string, any> | undefined {\n\tif (!options.reasoning || !model.reasoning) {\n\t\treturn undefined;\n\t}\n\n\tif (model.id.includes(\"anthropic.claude\") || model.id.includes(\"anthropic/claude\")) {\n\t\tconst adaptiveEffort = supportsAdaptiveThinking(model.id)\n\t\t\t? mapThinkingLevelToEffort(options.reasoning, model.id)\n\t\t\t: undefined;\n\t\tconst result: Record<string, any> = supportsAdaptiveThinking(model.id)\n\t\t\t? {\n\t\t\t\t\tthinking: { type: \"adaptive\" },\n\t\t\t\t\t...(adaptiveEffort != null ? { output_config: { effort: adaptiveEffort } } : {}),\n\t\t\t\t}\n\t\t\t: (() => {\n\t\t\t\t\tconst defaultBudgets: Record<ThinkingLevel, number> = {\n\t\t\t\t\t\tadaptive: 16384, // Fallback for old models that don't support adaptive\n\t\t\t\t\t\tminimal: 1024,\n\t\t\t\t\t\tlow: 2048,\n\t\t\t\t\t\tmedium: 8192,\n\t\t\t\t\t\thigh: 16384,\n\t\t\t\t\t\txhigh: 16384, // Claude doesn't support xhigh, clamp to high\n\t\t\t\t\t};\n\n\t\t\t\t\t// Custom budgets override defaults (xhigh/adaptive not in ThinkingBudgets, use high)\n\t\t\t\t\tconst level = options.reasoning === \"xhigh\" || options.reasoning === \"adaptive\" ? \"high\" : options.reasoning;\n\t\t\t\t\tconst budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tthinking: {\n\t\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\t\tbudget_tokens: budget,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t})();\n\n\t\tif (!supportsAdaptiveThinking(model.id) && (options.interleavedThinking ?? true)) {\n\t\t\tresult.anthropic_beta = [\"interleaved-thinking-2025-05-14\"];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\treturn undefined;\n}\n\nfunction createImageBlock(mimeType: string, data: string) {\n\tlet format: ImageFormat;\n\tswitch (mimeType) {\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\tformat = ImageFormat.JPEG;\n\t\t\tbreak;\n\t\tcase \"image/png\":\n\t\t\tformat = ImageFormat.PNG;\n\t\t\tbreak;\n\t\tcase \"image/gif\":\n\t\t\tformat = ImageFormat.GIF;\n\t\t\tbreak;\n\t\tcase \"image/webp\":\n\t\t\tformat = ImageFormat.WEBP;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown image type: ${mimeType}`);\n\t}\n\n\tconst binaryString = atob(data);\n\tconst bytes = new Uint8Array(binaryString.length);\n\tfor (let i = 0; i < binaryString.length; i++) {\n\t\tbytes[i] = binaryString.charCodeAt(i);\n\t}\n\n\treturn { source: { bytes }, format };\n}\n"]}
|