@vellumai/assistant 0.10.10-dev.202607210310.d95be07 → 0.10.10-dev.202607210700.85f5e82
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/package.json +1 -1
- package/src/__tests__/provider-error-scenarios.test.ts +78 -0
- package/src/providers/anthropic/__tests__/stream-content-shadow.test.ts +272 -0
- package/src/providers/anthropic/client.ts +36 -1
- package/src/providers/anthropic/stream-content-shadow.ts +224 -0
- package/src/providers/retry.ts +66 -5
- package/src/providers/unparseable-tool-args.ts +9 -0
package/package.json
CHANGED
|
@@ -721,6 +721,84 @@ describe("RetryProvider — streaming corruption retries", () => {
|
|
|
721
721
|
expect(inner.calls).toBe(DEFAULT_MAX_RETRIES + 1);
|
|
722
722
|
});
|
|
723
723
|
|
|
724
|
+
/** Provider that fails N times then succeeds, recording each call's messages. */
|
|
725
|
+
function makeCapturingFlaky(
|
|
726
|
+
failCount: number,
|
|
727
|
+
error: Error,
|
|
728
|
+
): Provider & { calls: number; seen: Message[][] } {
|
|
729
|
+
const p = {
|
|
730
|
+
name: "capturing",
|
|
731
|
+
calls: 0,
|
|
732
|
+
seen: [] as Message[][],
|
|
733
|
+
async sendMessage(messages: Message[]): Promise<ProviderResponse> {
|
|
734
|
+
p.calls++;
|
|
735
|
+
p.seen.push(messages);
|
|
736
|
+
if (p.calls <= failCount) {
|
|
737
|
+
throw error;
|
|
738
|
+
}
|
|
739
|
+
return successResponse();
|
|
740
|
+
},
|
|
741
|
+
};
|
|
742
|
+
return p;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
const PARSE_ERROR = new ProviderError(
|
|
746
|
+
"Anthropic request failed: Unable to parse tool parameter JSON from " +
|
|
747
|
+
"model. Please retry your request or adjust your prompt. Error: " +
|
|
748
|
+
"SyntaxError: JSON Parse error: Expected ']'. JSON: {\"content\": [Jul",
|
|
749
|
+
"anthropic",
|
|
750
|
+
);
|
|
751
|
+
|
|
752
|
+
test("tool-JSON parse retries append a corrective note to the latest user message", async () => {
|
|
753
|
+
const inner = makeCapturingFlaky(1, PARSE_ERROR);
|
|
754
|
+
const provider = new RetryProvider(inner);
|
|
755
|
+
|
|
756
|
+
await provider.sendMessage(MESSAGES);
|
|
757
|
+
|
|
758
|
+
expect(inner.calls).toBe(2);
|
|
759
|
+
// First attempt sends the caller's messages untouched.
|
|
760
|
+
expect(inner.seen[0]).toBe(MESSAGES);
|
|
761
|
+
// Retry appends exactly one trailing text block to the last user message.
|
|
762
|
+
const retried = inner.seen[1]!;
|
|
763
|
+
const lastMessage = retried[retried.length - 1]!;
|
|
764
|
+
expect(lastMessage.role).toBe("user");
|
|
765
|
+
expect(lastMessage.content).toHaveLength(2);
|
|
766
|
+
const hint = lastMessage.content[1] as { type: string; text: string };
|
|
767
|
+
expect(hint.type).toBe("text");
|
|
768
|
+
expect(hint.text).toContain("strict JSON");
|
|
769
|
+
// The caller's array is never mutated.
|
|
770
|
+
expect(MESSAGES[MESSAGES.length - 1]!.content).toHaveLength(1);
|
|
771
|
+
});
|
|
772
|
+
|
|
773
|
+
test("the corrective note is applied once across repeated parse failures", async () => {
|
|
774
|
+
const inner = makeCapturingFlaky(3, PARSE_ERROR);
|
|
775
|
+
const provider = new RetryProvider(inner);
|
|
776
|
+
|
|
777
|
+
await provider.sendMessage(MESSAGES);
|
|
778
|
+
|
|
779
|
+
expect(inner.calls).toBe(4);
|
|
780
|
+
for (const attempt of inner.seen.slice(1)) {
|
|
781
|
+
const lastMessage = attempt[attempt.length - 1]!;
|
|
782
|
+
expect(lastMessage.content).toHaveLength(2);
|
|
783
|
+
}
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
test("other stream-corruption retries resend the messages untouched", async () => {
|
|
787
|
+
const inner = makeCapturingFlaky(
|
|
788
|
+
1,
|
|
789
|
+
new ProviderError(
|
|
790
|
+
"Anthropic request failed: request ended without sending any chunks",
|
|
791
|
+
"anthropic",
|
|
792
|
+
),
|
|
793
|
+
);
|
|
794
|
+
const provider = new RetryProvider(inner);
|
|
795
|
+
|
|
796
|
+
await provider.sendMessage(MESSAGES);
|
|
797
|
+
|
|
798
|
+
expect(inner.calls).toBe(2);
|
|
799
|
+
expect(inner.seen[1]).toBe(MESSAGES);
|
|
800
|
+
});
|
|
801
|
+
|
|
724
802
|
test("does not retry non-stream ProviderError without status code", async () => {
|
|
725
803
|
const inner = makeFailing(
|
|
726
804
|
new ProviderError("model not found", "anthropic"),
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
|
|
3
|
+
import { StreamContentShadow } from "../stream-content-shadow.js";
|
|
4
|
+
|
|
5
|
+
// Mirrors the SDK accumulator's message format, including the trailing
|
|
6
|
+
// `. JSON: <buf>` suffix carrying the exact buffer it choked on.
|
|
7
|
+
const PARSE_ERROR = new Error(
|
|
8
|
+
"Unable to parse tool parameter JSON from model. Please retry your request " +
|
|
9
|
+
"or adjust your prompt. Error: SyntaxError: JSON Parse error: " +
|
|
10
|
+
"Expected ']'. JSON: {\"content\": [Jul 18 5:15 AM CT] ENTRY TITLE —",
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
function blockStart(index: number, contentBlock: Record<string, unknown>) {
|
|
14
|
+
return { type: "content_block_start", index, content_block: contentBlock };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function blockDelta(index: number, delta: Record<string, unknown>) {
|
|
18
|
+
return { type: "content_block_delta", index, delta };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function blockStop(index: number) {
|
|
22
|
+
return { type: "content_block_stop", index };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function textBlockEvents(index: number, text: string) {
|
|
26
|
+
return [
|
|
27
|
+
blockStart(index, { type: "text", text: "" }),
|
|
28
|
+
blockDelta(index, { type: "text_delta", text }),
|
|
29
|
+
blockStop(index),
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe("StreamContentShadow.salvage", () => {
|
|
34
|
+
test("wraps the in-flight tool call and keeps completed blocks", () => {
|
|
35
|
+
const shadow = new StreamContentShadow();
|
|
36
|
+
for (const event of textBlockEvents(0, "let me save that")) {
|
|
37
|
+
shadow.handleEvent(event);
|
|
38
|
+
}
|
|
39
|
+
shadow.handleEvent(
|
|
40
|
+
blockStart(1, {
|
|
41
|
+
type: "tool_use",
|
|
42
|
+
id: "tu_1",
|
|
43
|
+
name: "remember",
|
|
44
|
+
input: {},
|
|
45
|
+
}),
|
|
46
|
+
);
|
|
47
|
+
shadow.handleEvent(
|
|
48
|
+
blockDelta(1, { type: "input_json_delta", partial_json: '{"content": ' }),
|
|
49
|
+
);
|
|
50
|
+
// The poison delta itself is never observed — the SDK suppresses events
|
|
51
|
+
// after its internal accumulator errors.
|
|
52
|
+
|
|
53
|
+
const salvaged = shadow.salvage(PARSE_ERROR);
|
|
54
|
+
|
|
55
|
+
expect(salvaged).toBeDefined();
|
|
56
|
+
expect(salvaged!.toolName).toBe("remember");
|
|
57
|
+
expect(salvaged!.message.stop_reason).toBe("tool_use");
|
|
58
|
+
expect(salvaged!.message.content).toEqual([
|
|
59
|
+
{ type: "text", text: "let me save that" },
|
|
60
|
+
{
|
|
61
|
+
type: "tool_use",
|
|
62
|
+
id: "tu_1",
|
|
63
|
+
name: "remember",
|
|
64
|
+
// Raw args come from the error's `. JSON:` suffix — the full buffer,
|
|
65
|
+
// including the final chunk the shadow never saw.
|
|
66
|
+
input: { _raw: '{"content": [Jul 18 5:15 AM CT] ENTRY TITLE —' },
|
|
67
|
+
},
|
|
68
|
+
]);
|
|
69
|
+
expect(salvaged!.rawArgsLength).toBeGreaterThan(0);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("falls back to the shadow-accumulated buffer when the error carries no JSON suffix", () => {
|
|
73
|
+
const shadow = new StreamContentShadow();
|
|
74
|
+
shadow.handleEvent(
|
|
75
|
+
blockStart(0, {
|
|
76
|
+
type: "tool_use",
|
|
77
|
+
id: "tu_1",
|
|
78
|
+
name: "remember",
|
|
79
|
+
input: {},
|
|
80
|
+
}),
|
|
81
|
+
);
|
|
82
|
+
shadow.handleEvent(
|
|
83
|
+
blockDelta(0, {
|
|
84
|
+
type: "input_json_delta",
|
|
85
|
+
partial_json: '{"content": [Jul',
|
|
86
|
+
}),
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
const salvaged = shadow.salvage(
|
|
90
|
+
new Error("Unable to parse tool parameter JSON from model."),
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
expect(salvaged).toBeDefined();
|
|
94
|
+
expect(salvaged!.message.content).toEqual([
|
|
95
|
+
{
|
|
96
|
+
type: "tool_use",
|
|
97
|
+
id: "tu_1",
|
|
98
|
+
name: "remember",
|
|
99
|
+
input: { _raw: '{"content": [Jul' },
|
|
100
|
+
},
|
|
101
|
+
]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("returns undefined for unrelated errors", () => {
|
|
105
|
+
const shadow = new StreamContentShadow();
|
|
106
|
+
shadow.handleEvent(
|
|
107
|
+
blockStart(0, {
|
|
108
|
+
type: "tool_use",
|
|
109
|
+
id: "tu_1",
|
|
110
|
+
name: "remember",
|
|
111
|
+
input: {},
|
|
112
|
+
}),
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
expect(
|
|
116
|
+
shadow.salvage(new Error("Anthropic API error: Request was aborted.")),
|
|
117
|
+
).toBeUndefined();
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("returns undefined when no tool_use block is in flight", () => {
|
|
121
|
+
const shadow = new StreamContentShadow();
|
|
122
|
+
for (const event of textBlockEvents(0, "just text")) {
|
|
123
|
+
shadow.handleEvent(event);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
expect(shadow.salvage(PARSE_ERROR)).toBeUndefined();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("returns undefined when the in-flight block is not a tool_use", () => {
|
|
130
|
+
const shadow = new StreamContentShadow();
|
|
131
|
+
shadow.handleEvent(blockStart(0, { type: "text", text: "" }));
|
|
132
|
+
shadow.handleEvent(
|
|
133
|
+
blockDelta(0, { type: "text_delta", text: "streaming…" }),
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
expect(shadow.salvage(PARSE_ERROR)).toBeUndefined();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("parses completed tool calls strictly and preserves multi-block order", () => {
|
|
140
|
+
const shadow = new StreamContentShadow();
|
|
141
|
+
shadow.handleEvent(
|
|
142
|
+
blockStart(0, {
|
|
143
|
+
type: "tool_use",
|
|
144
|
+
id: "tu_1",
|
|
145
|
+
name: "recall",
|
|
146
|
+
input: {},
|
|
147
|
+
}),
|
|
148
|
+
);
|
|
149
|
+
shadow.handleEvent(
|
|
150
|
+
blockDelta(0, { type: "input_json_delta", partial_json: '{"query": ' }),
|
|
151
|
+
);
|
|
152
|
+
shadow.handleEvent(
|
|
153
|
+
blockDelta(0, { type: "input_json_delta", partial_json: '"alice"}' }),
|
|
154
|
+
);
|
|
155
|
+
shadow.handleEvent(blockStop(0));
|
|
156
|
+
shadow.handleEvent(
|
|
157
|
+
blockStart(1, {
|
|
158
|
+
type: "tool_use",
|
|
159
|
+
id: "tu_2",
|
|
160
|
+
name: "remember",
|
|
161
|
+
input: {},
|
|
162
|
+
}),
|
|
163
|
+
);
|
|
164
|
+
shadow.handleEvent(
|
|
165
|
+
blockDelta(1, {
|
|
166
|
+
type: "input_json_delta",
|
|
167
|
+
partial_json: '{"content": [Jul',
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
const salvaged = shadow.salvage(
|
|
172
|
+
new Error("Unable to parse tool parameter JSON from model."),
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
expect(salvaged).toBeDefined();
|
|
176
|
+
expect(salvaged!.message.content).toEqual([
|
|
177
|
+
{
|
|
178
|
+
type: "tool_use",
|
|
179
|
+
id: "tu_1",
|
|
180
|
+
name: "recall",
|
|
181
|
+
input: { query: "alice" },
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
type: "tool_use",
|
|
185
|
+
id: "tu_2",
|
|
186
|
+
name: "remember",
|
|
187
|
+
input: { _raw: '{"content": [Jul' },
|
|
188
|
+
},
|
|
189
|
+
]);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test("wraps a completed tool call whose buffer only satisfied the lenient partial parser", () => {
|
|
193
|
+
const shadow = new StreamContentShadow();
|
|
194
|
+
// `{"content": "abc` parses partially (unterminated string) so the SDK
|
|
195
|
+
// accumulator survives the block — but it is not strict JSON.
|
|
196
|
+
shadow.handleEvent(
|
|
197
|
+
blockStart(0, {
|
|
198
|
+
type: "tool_use",
|
|
199
|
+
id: "tu_1",
|
|
200
|
+
name: "remember",
|
|
201
|
+
input: {},
|
|
202
|
+
}),
|
|
203
|
+
);
|
|
204
|
+
shadow.handleEvent(
|
|
205
|
+
blockDelta(0, {
|
|
206
|
+
type: "input_json_delta",
|
|
207
|
+
partial_json: '{"content": "abc',
|
|
208
|
+
}),
|
|
209
|
+
);
|
|
210
|
+
shadow.handleEvent(blockStop(0));
|
|
211
|
+
shadow.handleEvent(
|
|
212
|
+
blockStart(1, {
|
|
213
|
+
type: "tool_use",
|
|
214
|
+
id: "tu_2",
|
|
215
|
+
name: "remember",
|
|
216
|
+
input: {},
|
|
217
|
+
}),
|
|
218
|
+
);
|
|
219
|
+
shadow.handleEvent(
|
|
220
|
+
blockDelta(1, { type: "input_json_delta", partial_json: "{" }),
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
const salvaged = shadow.salvage(
|
|
224
|
+
new Error("Unable to parse tool parameter JSON from model."),
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
expect(salvaged).toBeDefined();
|
|
228
|
+
expect(salvaged!.message.content[0]).toEqual({
|
|
229
|
+
type: "tool_use",
|
|
230
|
+
id: "tu_1",
|
|
231
|
+
name: "remember",
|
|
232
|
+
input: { _raw: '{"content": "abc' },
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
test("accumulates thinking blocks with signatures", () => {
|
|
237
|
+
const shadow = new StreamContentShadow();
|
|
238
|
+
shadow.handleEvent(blockStart(0, { type: "thinking", thinking: "" }));
|
|
239
|
+
shadow.handleEvent(
|
|
240
|
+
blockDelta(0, { type: "thinking_delta", thinking: "hmm, " }),
|
|
241
|
+
);
|
|
242
|
+
shadow.handleEvent(
|
|
243
|
+
blockDelta(0, { type: "thinking_delta", thinking: "let me save this" }),
|
|
244
|
+
);
|
|
245
|
+
shadow.handleEvent(
|
|
246
|
+
blockDelta(0, { type: "signature_delta", signature: "sig_abc" }),
|
|
247
|
+
);
|
|
248
|
+
shadow.handleEvent(blockStop(0));
|
|
249
|
+
shadow.handleEvent(
|
|
250
|
+
blockStart(1, {
|
|
251
|
+
type: "tool_use",
|
|
252
|
+
id: "tu_1",
|
|
253
|
+
name: "remember",
|
|
254
|
+
input: {},
|
|
255
|
+
}),
|
|
256
|
+
);
|
|
257
|
+
shadow.handleEvent(
|
|
258
|
+
blockDelta(1, { type: "input_json_delta", partial_json: "{" }),
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
const salvaged = shadow.salvage(
|
|
262
|
+
new Error("Unable to parse tool parameter JSON from model."),
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
expect(salvaged).toBeDefined();
|
|
266
|
+
expect(salvaged!.message.content[0]).toEqual({
|
|
267
|
+
type: "thinking",
|
|
268
|
+
thinking: "hmm, let me save this",
|
|
269
|
+
signature: "sig_abc",
|
|
270
|
+
});
|
|
271
|
+
});
|
|
272
|
+
});
|
|
@@ -30,6 +30,10 @@ import {
|
|
|
30
30
|
ContextOverflowError,
|
|
31
31
|
extractOverflowTokensFromMessage,
|
|
32
32
|
} from "../types.js";
|
|
33
|
+
import {
|
|
34
|
+
type ShadowStreamEvent,
|
|
35
|
+
StreamContentShadow,
|
|
36
|
+
} from "./stream-content-shadow.js";
|
|
33
37
|
|
|
34
38
|
const log = getLogger("anthropic-client");
|
|
35
39
|
|
|
@@ -1314,6 +1318,11 @@ export class AnthropicProvider implements Provider {
|
|
|
1314
1318
|
requestOptions,
|
|
1315
1319
|
) as unknown as UnifiedStream);
|
|
1316
1320
|
|
|
1321
|
+
// Shadow the streamed content blocks so a mid-stream SDK accumulator
|
|
1322
|
+
// failure on malformed tool-argument JSON can be salvaged instead of
|
|
1323
|
+
// discarding the whole response (see StreamContentShadow).
|
|
1324
|
+
const contentShadow = new StreamContentShadow();
|
|
1325
|
+
|
|
1317
1326
|
// Buffer streaming text until it's clear the accumulated text isn't
|
|
1318
1327
|
// going to form a placeholder sentinel. Sentinels are injected into
|
|
1319
1328
|
// outbound requests for role alternation and are sometimes echoed by
|
|
@@ -1357,6 +1366,7 @@ export class AnthropicProvider implements Provider {
|
|
|
1357
1366
|
>();
|
|
1358
1367
|
|
|
1359
1368
|
stream.on("streamEvent", (event) => {
|
|
1369
|
+
contentShadow.handleEvent(event as ShadowStreamEvent);
|
|
1360
1370
|
// Reset the text sentinel buffer at each content-block boundary.
|
|
1361
1371
|
// A new block starts fresh; at the end of a block, flush any
|
|
1362
1372
|
// buffered text that is NOT a complete sentinel, and drop it if
|
|
@@ -1512,7 +1522,32 @@ export class AnthropicProvider implements Provider {
|
|
|
1512
1522
|
}
|
|
1513
1523
|
});
|
|
1514
1524
|
|
|
1515
|
-
|
|
1525
|
+
try {
|
|
1526
|
+
response = await stream.finalMessage();
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
// The SDK rejects finalMessage() the moment a tool_use block's
|
|
1529
|
+
// argument JSON stops parsing, discarding everything it streamed.
|
|
1530
|
+
// Salvage the observed prefix instead: completed blocks plus the
|
|
1531
|
+
// malformed call wrapped under `_raw`, which the tool layer bounces
|
|
1532
|
+
// back to the model as an error tool_result so it can self-correct
|
|
1533
|
+
// in the next iteration. Any other rejection rethrows untouched.
|
|
1534
|
+
const salvaged = contentShadow.salvage(error);
|
|
1535
|
+
if (salvaged === undefined) {
|
|
1536
|
+
throw error;
|
|
1537
|
+
}
|
|
1538
|
+
log.warn(
|
|
1539
|
+
{
|
|
1540
|
+
model: params.model,
|
|
1541
|
+
toolName: salvaged.toolName,
|
|
1542
|
+
rawArgsLength: salvaged.rawArgsLength,
|
|
1543
|
+
},
|
|
1544
|
+
"Salvaged stream with unparseable tool-call arguments; returning _raw-wrapped tool call",
|
|
1545
|
+
);
|
|
1546
|
+
response = {
|
|
1547
|
+
...salvaged.message,
|
|
1548
|
+
model: params.model,
|
|
1549
|
+
} as unknown as Anthropic.Message;
|
|
1550
|
+
}
|
|
1516
1551
|
} finally {
|
|
1517
1552
|
cleanupTimeout();
|
|
1518
1553
|
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import {
|
|
2
|
+
UNPARSEABLE_TOOL_ARGS_SDK_MESSAGE,
|
|
3
|
+
wrapUnparseableToolArgs,
|
|
4
|
+
} from "../unparseable-tool-args.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The accumulator error embeds the exact buffer it choked on as a trailing
|
|
8
|
+
* `. JSON: <buf>` suffix — including the final delta chunk, which the shadow
|
|
9
|
+
* never observes (the SDK suppresses event emission the moment it errors).
|
|
10
|
+
*/
|
|
11
|
+
const ERROR_JSON_BUF_SUFFIX = /\. JSON: ([\s\S]+)$/;
|
|
12
|
+
|
|
13
|
+
/** Raw content block in the Anthropic wire shape. */
|
|
14
|
+
type ShadowBlock = Record<string, unknown>;
|
|
15
|
+
|
|
16
|
+
/** Structural subset of the SDK's stream events consumed by the shadow. */
|
|
17
|
+
export interface ShadowStreamEvent {
|
|
18
|
+
type: string;
|
|
19
|
+
index?: number;
|
|
20
|
+
content_block?: unknown;
|
|
21
|
+
delta?: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface SalvagedStream {
|
|
25
|
+
/**
|
|
26
|
+
* Response in the Anthropic `Message` shape, minus `model` (the caller
|
|
27
|
+
* stamps the request model). Usage is zeroed: the SDK discards the
|
|
28
|
+
* `message_delta` usage totals when it errors, so the salvaged turn
|
|
29
|
+
* under-reports rather than guesses.
|
|
30
|
+
*/
|
|
31
|
+
message: {
|
|
32
|
+
content: ShadowBlock[];
|
|
33
|
+
stop_reason: "tool_use";
|
|
34
|
+
usage: { input_tokens: number; output_tokens: number };
|
|
35
|
+
};
|
|
36
|
+
toolName: string;
|
|
37
|
+
rawArgsLength: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Shadow accumulator for a streamed Anthropic message, maintained from raw
|
|
42
|
+
* `streamEvent`s independently of the SDK's internal snapshot.
|
|
43
|
+
*
|
|
44
|
+
* The SDK's `MessageStream` re-parses a `tool_use` block's accumulated
|
|
45
|
+
* argument JSON on every `input_json_delta` and fails the entire stream the
|
|
46
|
+
* moment the buffer stops parsing: `finalMessage()` rejects with
|
|
47
|
+
* `Unable to parse tool parameter JSON…` and every later event is suppressed
|
|
48
|
+
* while the wire stream silently drains. That discards the whole response —
|
|
49
|
+
* even though the protocol has a well-defined degrade for exactly this case:
|
|
50
|
+
* return the malformed call with its raw argument text wrapped under the
|
|
51
|
+
* `_raw` marker so the tool layer rejects it back to the model as an error
|
|
52
|
+
* tool_result and the model self-corrects (see
|
|
53
|
+
* `providers/unparseable-tool-args.ts`; the OpenAI-format providers apply the
|
|
54
|
+
* same contract at parse time).
|
|
55
|
+
*
|
|
56
|
+
* `salvage()` rebuilds that degraded message from what streamed before the
|
|
57
|
+
* poison delta: completed blocks verbatim, plus the in-flight tool call with
|
|
58
|
+
* its arguments wrapped. Whatever the model emitted after the failure is
|
|
59
|
+
* unobservable and is dropped — strictly better than dropping the turn.
|
|
60
|
+
*/
|
|
61
|
+
export class StreamContentShadow {
|
|
62
|
+
private readonly blocks = new Map<number, ShadowBlock>();
|
|
63
|
+
private readonly jsonBufs = new Map<number, string>();
|
|
64
|
+
private readonly completed = new Set<number>();
|
|
65
|
+
private inFlightIndex: number | undefined;
|
|
66
|
+
|
|
67
|
+
handleEvent(event: ShadowStreamEvent): void {
|
|
68
|
+
switch (event.type) {
|
|
69
|
+
case "content_block_start": {
|
|
70
|
+
if (typeof event.index !== "number") {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const block = structuredClone(event.content_block);
|
|
74
|
+
if (block === null || typeof block !== "object") {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
this.blocks.set(event.index, block as ShadowBlock);
|
|
78
|
+
this.inFlightIndex = event.index;
|
|
79
|
+
if (this.tracksToolInput(block as ShadowBlock)) {
|
|
80
|
+
this.jsonBufs.set(event.index, "");
|
|
81
|
+
}
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
case "content_block_delta": {
|
|
85
|
+
if (typeof event.index !== "number") {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const block = this.blocks.get(event.index);
|
|
89
|
+
const delta = event.delta as Record<string, unknown> | undefined;
|
|
90
|
+
if (block === undefined || delta === undefined) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
switch (delta.type) {
|
|
94
|
+
case "text_delta":
|
|
95
|
+
block.text = `${typeof block.text === "string" ? block.text : ""}${String(delta.text ?? "")}`;
|
|
96
|
+
return;
|
|
97
|
+
case "thinking_delta":
|
|
98
|
+
block.thinking = `${typeof block.thinking === "string" ? block.thinking : ""}${String(delta.thinking ?? "")}`;
|
|
99
|
+
return;
|
|
100
|
+
case "signature_delta":
|
|
101
|
+
block.signature = delta.signature;
|
|
102
|
+
return;
|
|
103
|
+
case "input_json_delta": {
|
|
104
|
+
const buf = this.jsonBufs.get(event.index);
|
|
105
|
+
if (buf !== undefined) {
|
|
106
|
+
this.jsonBufs.set(
|
|
107
|
+
event.index,
|
|
108
|
+
buf + String(delta.partial_json ?? ""),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
case "citations_delta": {
|
|
114
|
+
const citations = Array.isArray(block.citations)
|
|
115
|
+
? block.citations
|
|
116
|
+
: [];
|
|
117
|
+
citations.push(delta.citation);
|
|
118
|
+
block.citations = citations;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
default:
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
case "content_block_stop": {
|
|
126
|
+
if (typeof event.index !== "number") {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const block = this.blocks.get(event.index);
|
|
130
|
+
if (block !== undefined) {
|
|
131
|
+
const buf = this.jsonBufs.get(event.index);
|
|
132
|
+
if (buf !== undefined && buf.length > 0) {
|
|
133
|
+
block.input = this.parseFinalToolInput(buf);
|
|
134
|
+
}
|
|
135
|
+
this.completed.add(event.index);
|
|
136
|
+
}
|
|
137
|
+
if (this.inFlightIndex === event.index) {
|
|
138
|
+
this.inFlightIndex = undefined;
|
|
139
|
+
}
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
default:
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Rebuild the response for an `Unable to parse tool parameter JSON`
|
|
149
|
+
* rejection. Returns `undefined` — caller rethrows — when the error is a
|
|
150
|
+
* different failure or the shadow lacks an in-flight `tool_use` block to
|
|
151
|
+
* pin the failure on (without it the salvaged message would carry no trace
|
|
152
|
+
* of what went wrong).
|
|
153
|
+
*/
|
|
154
|
+
salvage(error: unknown): SalvagedStream | undefined {
|
|
155
|
+
const messageText =
|
|
156
|
+
error instanceof Error ? error.message : String(error ?? "");
|
|
157
|
+
if (!messageText.includes(UNPARSEABLE_TOOL_ARGS_SDK_MESSAGE)) {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
if (this.inFlightIndex === undefined) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
const inFlight = this.blocks.get(this.inFlightIndex);
|
|
164
|
+
if (
|
|
165
|
+
inFlight === undefined ||
|
|
166
|
+
inFlight.type !== "tool_use" ||
|
|
167
|
+
typeof inFlight.name !== "string"
|
|
168
|
+
) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const raw =
|
|
173
|
+
ERROR_JSON_BUF_SUFFIX.exec(messageText)?.[1] ??
|
|
174
|
+
this.jsonBufs.get(this.inFlightIndex) ??
|
|
175
|
+
"";
|
|
176
|
+
|
|
177
|
+
const content: ShadowBlock[] = [];
|
|
178
|
+
for (const index of [...this.blocks.keys()].sort((a, b) => a - b)) {
|
|
179
|
+
if (index === this.inFlightIndex) {
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
if (this.completed.has(index)) {
|
|
183
|
+
content.push(this.blocks.get(index)!);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
content.push({ ...inFlight, input: wrapUnparseableToolArgs(raw) });
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
message: {
|
|
190
|
+
content,
|
|
191
|
+
stop_reason: "tool_use",
|
|
192
|
+
usage: { input_tokens: 0, output_tokens: 0 },
|
|
193
|
+
},
|
|
194
|
+
toolName: inFlight.name,
|
|
195
|
+
rawArgsLength: raw.length,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private tracksToolInput(block: ShadowBlock): boolean {
|
|
200
|
+
return block.type === "tool_use" || block.type === "server_tool_use";
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Strict-parse a completed block's accumulated argument JSON. Tool inputs
|
|
205
|
+
* must be plain objects; anything else (including JSON that only satisfied
|
|
206
|
+
* the SDK's lenient partial parser mid-stream) is wrapped under `_raw` so
|
|
207
|
+
* the tool layer rejects it instead of executing with garbage.
|
|
208
|
+
*/
|
|
209
|
+
private parseFinalToolInput(buf: string): Record<string, unknown> {
|
|
210
|
+
try {
|
|
211
|
+
const parsed: unknown = JSON.parse(buf);
|
|
212
|
+
if (
|
|
213
|
+
parsed !== null &&
|
|
214
|
+
typeof parsed === "object" &&
|
|
215
|
+
!Array.isArray(parsed)
|
|
216
|
+
) {
|
|
217
|
+
return parsed as Record<string, unknown>;
|
|
218
|
+
}
|
|
219
|
+
} catch {
|
|
220
|
+
// fall through to wrap
|
|
221
|
+
}
|
|
222
|
+
return wrapUnparseableToolArgs(buf);
|
|
223
|
+
}
|
|
224
|
+
}
|
package/src/providers/retry.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
type ProviderResponse,
|
|
31
31
|
type SendMessageOptions,
|
|
32
32
|
} from "./types.js";
|
|
33
|
+
import { UNPARSEABLE_TOOL_ARGS_SDK_MESSAGE } from "./unparseable-tool-args.js";
|
|
33
34
|
|
|
34
35
|
const log = getLogger("retry");
|
|
35
36
|
|
|
@@ -125,12 +126,63 @@ const RETRYABLE_STREAM_PATTERNS = [
|
|
|
125
126
|
"request ended without sending any chunks",
|
|
126
127
|
"stream has ended, this shouldn't happen",
|
|
127
128
|
// The SDK's stream accumulator throws this when the model emits tool-call
|
|
128
|
-
// arguments that don't parse as JSON (e.g.
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
|
|
129
|
+
// arguments that don't parse as JSON (e.g. an unquoted string value). The
|
|
130
|
+
// Anthropic client salvages most of these into a `_raw`-wrapped tool call
|
|
131
|
+
// before they surface (see anthropic/stream-content-shadow.ts); ones that
|
|
132
|
+
// still reach here retry with a corrective note
|
|
133
|
+
// (`withUnparseableToolArgsHint`) because the malformation can be
|
|
134
|
+
// conditioned on the request context — a byte-identical resend can
|
|
135
|
+
// reproduce it indefinitely.
|
|
136
|
+
UNPARSEABLE_TOOL_ARGS_SDK_MESSAGE,
|
|
132
137
|
];
|
|
133
138
|
|
|
139
|
+
/**
|
|
140
|
+
* One-shot note appended to the retried request after a tool-argument JSON
|
|
141
|
+
* parse failure. Appended as a trailing text block on the latest user
|
|
142
|
+
* message: the request tail sits after every prompt-cache anchor, so the
|
|
143
|
+
* hint costs no cache reuse (a system-prompt edit would invalidate the whole
|
|
144
|
+
* cached prefix).
|
|
145
|
+
*/
|
|
146
|
+
const UNPARSEABLE_TOOL_ARGS_RETRY_HINT =
|
|
147
|
+
"[assistant runtime] The previous attempt at this response was discarded: " +
|
|
148
|
+
"a tool call's arguments were not valid JSON (typically an unquoted string " +
|
|
149
|
+
"value). Respond again, emitting tool-call arguments as strict JSON — " +
|
|
150
|
+
"every string value double-quoted, including values that begin with '[' " +
|
|
151
|
+
"or '{'.";
|
|
152
|
+
|
|
153
|
+
function isUnparseableToolArgsError(error: unknown): boolean {
|
|
154
|
+
if (!(error instanceof ProviderError)) {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
if (error.statusCode !== undefined) {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
return error.message.includes(UNPARSEABLE_TOOL_ARGS_SDK_MESSAGE);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Copy of `messages` with the corrective note appended to the latest user
|
|
165
|
+
* message. When the request doesn't end on a user message (assistant
|
|
166
|
+
* prefill), returns `messages` unchanged — appending anything there would
|
|
167
|
+
* change prefill semantics.
|
|
168
|
+
*/
|
|
169
|
+
function withUnparseableToolArgsHint(messages: Message[]): Message[] {
|
|
170
|
+
const last = messages[messages.length - 1];
|
|
171
|
+
if (last === undefined || last.role !== "user") {
|
|
172
|
+
return messages;
|
|
173
|
+
}
|
|
174
|
+
return [
|
|
175
|
+
...messages.slice(0, -1),
|
|
176
|
+
{
|
|
177
|
+
...last,
|
|
178
|
+
content: [
|
|
179
|
+
...last.content,
|
|
180
|
+
{ type: "text", text: UNPARSEABLE_TOOL_ARGS_RETRY_HINT },
|
|
181
|
+
],
|
|
182
|
+
},
|
|
183
|
+
];
|
|
184
|
+
}
|
|
185
|
+
|
|
134
186
|
/**
|
|
135
187
|
* Patterns that indicate a transient provider error even when no HTTP status
|
|
136
188
|
* code is available (e.g. overloaded errors delivered as SSE events mid-stream
|
|
@@ -753,6 +805,7 @@ export class RetryProvider implements Provider {
|
|
|
753
805
|
): Promise<ProviderResponse> {
|
|
754
806
|
let lastError: unknown;
|
|
755
807
|
let didRetry = false;
|
|
808
|
+
let messagesForAttempt = messages;
|
|
756
809
|
|
|
757
810
|
const normalizedOptions = normalizeSendMessageOptions(this.name, options, {
|
|
758
811
|
forwardUsageAttributionHeaders:
|
|
@@ -762,7 +815,7 @@ export class RetryProvider implements Provider {
|
|
|
762
815
|
for (let attempt = 0; attempt <= DEFAULT_MAX_RETRIES; attempt++) {
|
|
763
816
|
try {
|
|
764
817
|
const result = await this.inner.sendMessage(
|
|
765
|
-
|
|
818
|
+
messagesForAttempt,
|
|
766
819
|
normalizedOptions,
|
|
767
820
|
);
|
|
768
821
|
return result;
|
|
@@ -770,6 +823,13 @@ export class RetryProvider implements Provider {
|
|
|
770
823
|
lastError = error;
|
|
771
824
|
|
|
772
825
|
if (attempt < DEFAULT_MAX_RETRIES && isRetryableError(error)) {
|
|
826
|
+
// Malformed tool-argument JSON is conditioned on the request, so
|
|
827
|
+
// resend with the corrective note. Built from the original
|
|
828
|
+
// `messages` each time — the note appears exactly once no matter
|
|
829
|
+
// how many attempts fail this way.
|
|
830
|
+
if (isUnparseableToolArgsError(error)) {
|
|
831
|
+
messagesForAttempt = withUnparseableToolArgsHint(messages);
|
|
832
|
+
}
|
|
773
833
|
// Prefer server-provided Retry-After; fall back to exponential backoff.
|
|
774
834
|
const retryAfter =
|
|
775
835
|
error instanceof ProviderError ? error.retryAfterMs : undefined;
|
|
@@ -799,6 +859,7 @@ export class RetryProvider implements Provider {
|
|
|
799
859
|
delay,
|
|
800
860
|
retryAfterHeader: retryAfter !== undefined,
|
|
801
861
|
errorType,
|
|
862
|
+
correctiveHint: messagesForAttempt !== messages,
|
|
802
863
|
provider: this.name,
|
|
803
864
|
message: error instanceof Error ? error.message : String(error),
|
|
804
865
|
},
|
|
@@ -14,6 +14,15 @@
|
|
|
14
14
|
*/
|
|
15
15
|
const UNPARSEABLE_TOOL_ARGS_KEY = "_raw";
|
|
16
16
|
|
|
17
|
+
/**
|
|
18
|
+
* Message emitted by the Anthropic SDK's stream accumulator when a tool_use
|
|
19
|
+
* block's argument JSON stops parsing mid-stream. Shared by the salvage path
|
|
20
|
+
* (`anthropic/stream-content-shadow.ts`) and the retry classifier
|
|
21
|
+
* (`retry.ts`), which both key off this exact text.
|
|
22
|
+
*/
|
|
23
|
+
export const UNPARSEABLE_TOOL_ARGS_SDK_MESSAGE =
|
|
24
|
+
"Unable to parse tool parameter JSON";
|
|
25
|
+
|
|
17
26
|
/** Wrap raw, unparseable tool-call argument text in the marker shape. */
|
|
18
27
|
export function wrapUnparseableToolArgs(raw: string): Record<string, unknown> {
|
|
19
28
|
return { [UNPARSEABLE_TOOL_ARGS_KEY]: raw };
|