-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathsrc_diff.txt
More file actions
626 lines (607 loc) · 22.7 KB
/
src_diff.txt
File metadata and controls
626 lines (607 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
diff --git a/README.md b/README.md
index 93f712f..c2f4892 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@
<a href="https://github.com/suhaibbinyounis/github-copilot-api-vscode/actions/workflows/ci.yml">
<img src="https://img.shields.io/github/actions/workflow/status/suhaibbinyounis/github-copilot-api-vscode/ci.yml?branch=main&style=flat-square&logo=github&label=Build" alt="CI Status">
</a>
- <img src="media/coverage.svg" alt="Coverage">
+ <img src="https://img.shields.io/badge/Coverage-89.38%25-dfb317?style=flat-square" alt="Coverage">
<img src="https://img.shields.io/github/repo-size/suhaibbinyounis/github-copilot-api-vscode?style=flat-square&logo=github&color=blue" alt="Repo Size">
<img src="https://img.shields.io/badge/TypeScript-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript">
</p>
diff --git a/src/CopilotApiGateway.ts b/src/CopilotApiGateway.ts
index eae0894..81e6d47 100644
--- a/src/CopilotApiGateway.ts
+++ b/src/CopilotApiGateway.ts
@@ -12,13 +12,19 @@ import { AuditService, AuditEntry } from './services/AuditService';
import type { McpService } from './McpService';
import type { RawData, WebSocket, WebSocketServer } from 'ws';
import {
+ applyStructuredAnthropicToolPairLimit,
+ flattenAnthropicMessageForTextHistory,
+ flattenAnthropicToolResultContent,
getAnthropicToolUseId,
+ getAnthropicToolHistoryDebugInfo,
getStructuredAnthropicToolPairIndexes,
- normalizeAnthropicContent
+ normalizeAnthropicContent,
+ type AnthropicToolResultContent
} from './anthropicToolPairs';
const COPILOT_CHAT_EXTENSION_ID = 'GitHub.copilot-chat';
const COPILOT_CHAT_SEARCH_QUERY = '@id:GitHub.copilot-chat';
+const MAX_STRUCTURED_ANTHROPIC_TOOL_PAIRS = 8;
export class ApiError extends Error {
constructor(
@@ -117,7 +123,7 @@ interface ExtensionBuildInfo {
export type AnthropicContentBlock =
| { type: 'text'; text: string }
| { type: 'tool_use'; id: string; name: string; input: any }
- | { type: 'tool_result'; tool_use_id: string; content: string | { type: 'text'; text: string }[] };
+ | { type: 'tool_result'; tool_use_id: string; content: AnthropicToolResultContent };
export interface AnthropicMessageRequest {
model: string;
@@ -2081,19 +2087,21 @@ export class CopilotApiGateway implements vscode.Disposable {
// Anthropic Messages API
if (req.method === 'POST' && url.pathname === '/v1/messages') {
const body = await this.readJsonBody(req) as AnthropicMessageRequest;
+ const anthropicDebug = this.buildAnthropicDebugPayload(body, requestId);
// Model validation
if (body?.model && !this.resolveModel(body.model)) {
throw new ApiError(400, `Model '${body.model}' is not supported.`, 'invalid_request_error', 'model_not_found');
}
if (body?.stream === true) {
- await this.processStreamingAnthropicMessages(body, req, res, requestId, requestStart);
+ await this.processStreamingAnthropicMessages(body, req, res, requestId, requestStart, anthropicDebug);
} else {
try {
const response = await this.processAnthropicMessages(body);
this.logRequest(requestId, req.method, url.pathname, 200, Date.now() - requestStart, {
requestPayload: body,
responsePayload: response,
+ debugPayload: anthropicDebug,
tokensIn: response?.usage?.input_tokens,
tokensOut: response?.usage?.output_tokens,
model: body?.model,
@@ -2103,6 +2111,21 @@ export class CopilotApiGateway implements vscode.Disposable {
this.sendJson(res, 200, response);
} catch (error: any) {
const apiError = error instanceof ApiError ? error : new ApiError(500, error.message || 'Internal Server Error', 'api_error');
+ this.logRequest(requestId, req.method, url.pathname, apiError.status, Date.now() - requestStart, {
+ requestPayload: body,
+ responsePayload: {
+ type: 'error',
+ error: {
+ type: apiError.code || 'api_error',
+ message: apiError.message
+ }
+ },
+ debugPayload: anthropicDebug,
+ error: apiError.message,
+ model: body?.model,
+ requestHeaders: req.headers,
+ responseHeaders: res.getHeaders()
+ });
this.sendJson(res, apiError.status, {
type: 'error',
error: {
@@ -2432,7 +2455,14 @@ export class CopilotApiGateway implements vscode.Disposable {
}
}
- private async processStreamingAnthropicMessages(payload: AnthropicMessageRequest, req: IncomingMessage, res: ServerResponse, logRequestId?: string, logRequestStart?: number): Promise<void> {
+ private async processStreamingAnthropicMessages(
+ payload: AnthropicMessageRequest,
+ req: IncomingMessage,
+ res: ServerResponse,
+ logRequestId?: string,
+ logRequestStart?: number,
+ debugPayload?: unknown
+ ): Promise<void> {
const messages: vscode.LanguageModelChatMessage[] = [];
const systemText = typeof payload.system === 'string'
@@ -2613,6 +2643,7 @@ export class CopilotApiGateway implements vscode.Disposable {
this.logRequest(logRequestId, 'POST', '/v1/messages', 200, Date.now() - (logRequestStart || 0), {
requestPayload: payload,
responsePayload: { id: messageId, type: 'message', content: [{ type: 'text', text: totalContent }] },
+ debugPayload,
tokensIn: inputTokens,
tokensOut: outputTokens,
model: resolvedModel
@@ -2623,6 +2654,23 @@ export class CopilotApiGateway implements vscode.Disposable {
if (cts.token.isCancellationRequested) { return; }
console.error('Anthropic streaming error:', error);
const apiError = error instanceof ApiError ? error : new ApiError(500, error.message || 'Internal Server Error', 'server_error');
+ if (logRequestId) {
+ this.logRequest(logRequestId, 'POST', '/v1/messages', apiError.status, Date.now() - (logRequestStart || 0), {
+ requestPayload: payload,
+ responsePayload: {
+ type: 'error',
+ error: {
+ type: apiError.code || 'api_error',
+ message: apiError.message
+ }
+ },
+ debugPayload,
+ error: apiError.message,
+ model: payload?.model,
+ requestHeaders: req.headers,
+ responseHeaders: res.getHeaders()
+ });
+ }
res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: apiError.code || 'api_error', message: apiError.message } })}\n\n`);
res.end();
} finally {
@@ -4398,7 +4446,10 @@ export class CopilotApiGateway implements vscode.Disposable {
anthropicMessages: AnthropicMessageRequest['messages']
): vscode.LanguageModelChatMessage[] {
const result: vscode.LanguageModelChatMessage[] = [];
- const structuredToolPairs = getStructuredAnthropicToolPairIndexes(anthropicMessages);
+ const structuredToolPairs = applyStructuredAnthropicToolPairLimit(
+ getStructuredAnthropicToolPairIndexes(anthropicMessages),
+ MAX_STRUCTURED_ANTHROPIC_TOOL_PAIRS
+ );
for (let messageIndex = 0; messageIndex < anthropicMessages.length; messageIndex++) {
const msg = anthropicMessages[messageIndex];
@@ -4409,7 +4460,7 @@ export class CopilotApiGateway implements vscode.Disposable {
// Only preserve tool results as structured parts when the preceding tool call is complete.
const toolResultBlocks = contentArr.filter(p => p.type === 'tool_result') as Array<{
type: 'tool_result'; tool_use_id: string;
- content: string | { type: 'text'; text: string }[];
+ content: AnthropicToolResultContent;
}>;
if (toolResultBlocks.length > 0 && structuredToolPairs.userIndexes.has(messageIndex)) {
@@ -4417,12 +4468,8 @@ export class CopilotApiGateway implements vscode.Disposable {
const parts: (vscode.LanguageModelToolResultPart | vscode.LanguageModelTextPart)[] = [];
for (const blk of contentArr) {
if (blk.type === 'tool_result') {
- const tr = blk as { type: 'tool_result'; tool_use_id: string; content: string | { type: 'text'; text: string }[] };
- const resultText = typeof tr.content === 'string'
- ? tr.content
- : Array.isArray(tr.content)
- ? tr.content.map((c: { type: string; text?: string }) => c.text || '').join('\n')
- : '';
+ const tr = blk as { type: 'tool_result'; tool_use_id: string; content: AnthropicToolResultContent };
+ const resultText = flattenAnthropicToolResultContent(tr.content);
parts.push(new vscode.LanguageModelToolResultPart(
tr.tool_use_id,
[new vscode.LanguageModelTextPart(this.redactPromptString(resultText))]
@@ -4436,7 +4483,7 @@ export class CopilotApiGateway implements vscode.Disposable {
result.push(vscode.LanguageModelChatMessage.User(parts));
} else {
// Plain user text
- const text = this.flattenMessageContent(msg.content);
+ const text = flattenAnthropicMessageForTextHistory(msg);
result.push(vscode.LanguageModelChatMessage.User(this.redactPromptString(text)));
}
} else {
@@ -4468,7 +4515,7 @@ export class CopilotApiGateway implements vscode.Disposable {
result.push(vscode.LanguageModelChatMessage.Assistant(parts));
} else {
// Plain assistant text
- const text = this.flattenMessageContent(msg.content);
+ const text = flattenAnthropicMessageForTextHistory(msg);
result.push(vscode.LanguageModelChatMessage.Assistant(this.redactPromptString(text)));
}
}
@@ -4477,6 +4524,28 @@ export class CopilotApiGateway implements vscode.Disposable {
return result;
}
+ private buildAnthropicDebugPayload(
+ body: AnthropicMessageRequest,
+ requestId: string
+ ): Record<string, unknown> {
+ const historyDebug = getAnthropicToolHistoryDebugInfo(
+ body?.messages || [],
+ MAX_STRUCTURED_ANTHROPIC_TOOL_PAIRS
+ );
+ return {
+ requestId,
+ model: body?.model,
+ stream: body?.stream === true,
+ maxStructuredToolPairs: MAX_STRUCTURED_ANTHROPIC_TOOL_PAIRS,
+ messageCount: historyDebug.messageCount,
+ structuredAssistantIndexes: historyDebug.structuredAssistantIndexes,
+ structuredUserIndexes: historyDebug.structuredUserIndexes,
+ leadingOrphanToolResultIds: historyDebug.leadingOrphanToolResultIds,
+ orphanToolResultIds: historyDebug.orphanToolResultIds,
+ messages: historyDebug.messages
+ };
+ }
+
private extractTextFromPart(part: unknown): string | undefined {
if (!part || typeof part !== 'object') {
return typeof part === 'string' ? part : undefined;
@@ -5902,6 +5971,7 @@ export class CopilotApiGateway implements vscode.Disposable {
extra?: {
requestPayload?: unknown;
responsePayload?: unknown;
+ debugPayload?: unknown;
tokensIn?: number;
tokensOut?: number;
model?: string;
@@ -5938,6 +6008,7 @@ export class CopilotApiGateway implements vscode.Disposable {
ip: extra?.ip || this.requestIpMap.get(requestId),
requestBody: extra?.requestPayload,
responseBody: extra?.responsePayload,
+ debug: extra?.debugPayload,
requestHeaders: extra?.requestHeaders,
responseHeaders: extra?.responseHeaders
};
@@ -5968,6 +6039,13 @@ export class CopilotApiGateway implements vscode.Disposable {
if (extra?.error) {
this.output.appendLine(` Error: ${extra.error}`);
}
+ if (extra?.debugPayload) {
+ try {
+ this.output.appendLine(` Debug: ${JSON.stringify(extra.debugPayload)}`);
+ } catch {
+ this.output.appendLine(' Debug: [unserializable]');
+ }
+ }
}
}
diff --git a/src/anthropicToolPairs.ts b/src/anthropicToolPairs.ts
index 439fcf5..f35e5a1 100644
--- a/src/anthropicToolPairs.ts
+++ b/src/anthropicToolPairs.ts
@@ -1,7 +1,13 @@
+export type AnthropicToolResultContentPart =
+ | { type: 'text'; text: string }
+ | { type: 'image'; source?: unknown };
+
+export type AnthropicToolResultContent = string | AnthropicToolResultContentPart[];
+
export type AnthropicToolPairContentBlock =
| { type: 'text'; text: string }
| { type: 'tool_use'; id: string; name: string; input: any }
- | { type: 'tool_result'; tool_use_id: string; content: string | { type: 'text'; text: string }[] };
+ | { type: 'tool_result'; tool_use_id: string; content: AnthropicToolResultContent };
export interface AnthropicToolPairMessage {
role: 'user' | 'assistant';
@@ -13,6 +19,25 @@ export interface AnthropicToolPairIndexes {
userIndexes: Set<number>;
}
+export interface AnthropicToolHistoryMessageDebug {
+ index: number;
+ role: 'user' | 'assistant';
+ blockTypes: string[];
+ toolUseIds: string[];
+ toolResultIds: string[];
+ hasLeadingOrphanToolResult: boolean;
+ structuredMode: 'structured' | 'text';
+}
+
+export interface AnthropicToolHistoryDebugInfo {
+ messageCount: number;
+ structuredAssistantIndexes: number[];
+ structuredUserIndexes: number[];
+ leadingOrphanToolResultIds: string[];
+ orphanToolResultIds: string[];
+ messages: AnthropicToolHistoryMessageDebug[];
+}
+
export function getAnthropicToolUseId(
callId: string | undefined,
fallbackFactory: () => string
@@ -30,6 +55,43 @@ export function normalizeAnthropicContent(content: string | AnthropicToolPairCon
: [{ type: 'text', text: typeof content === 'string' ? content : '' }];
}
+export function flattenAnthropicToolResultContent(content: AnthropicToolResultContent): string {
+ if (typeof content === 'string') {
+ return content;
+ }
+ if (!Array.isArray(content)) {
+ return '';
+ }
+ return content.map(block => block.type === 'image' ? '[image omitted]' : (block.text || '')).join('\n');
+}
+
+export function flattenAnthropicMessageForTextHistory(message: AnthropicToolPairMessage): string {
+ if (typeof message.content === 'string') {
+ return message.content;
+ }
+
+ const content = normalizeAnthropicContent(message.content);
+ const parts: string[] = [];
+
+ for (const block of content) {
+ if (block.type === 'text') {
+ if (block.text) {
+ parts.push(block.text);
+ }
+ continue;
+ }
+
+ if (block.type === 'tool_result') {
+ const resultText = flattenAnthropicToolResultContent(block.content);
+ if (resultText) {
+ parts.push(resultText);
+ }
+ }
+ }
+
+ return parts.join('\n');
+}
+
function getToolUseIds(content: AnthropicToolPairContentBlock[]): string[] {
return content
.filter((block): block is { type: 'tool_use'; id: string; name: string; input: any } => block.type === 'tool_use')
@@ -38,7 +100,7 @@ function getToolUseIds(content: AnthropicToolPairContentBlock[]): string[] {
function getToolResultIds(content: AnthropicToolPairContentBlock[]): string[] {
return content
- .filter((block): block is { type: 'tool_result'; tool_use_id: string; content: string | { type: 'text'; text: string }[] } => block.type === 'tool_result')
+ .filter((block): block is { type: 'tool_result'; tool_use_id: string; content: AnthropicToolResultContent } => block.type === 'tool_result')
.map(block => block.tool_use_id);
}
@@ -111,3 +173,91 @@ export function getStructuredAnthropicToolPairIndexes(
return { assistantIndexes, userIndexes };
}
+
+export function applyStructuredAnthropicToolPairLimit(
+ pairs: AnthropicToolPairIndexes,
+ maxStructuredPairs: number
+): AnthropicToolPairIndexes {
+ if (!Number.isFinite(maxStructuredPairs) || maxStructuredPairs < 0) {
+ return {
+ assistantIndexes: new Set(pairs.assistantIndexes),
+ userIndexes: new Set(pairs.userIndexes)
+ };
+ }
+
+ if (maxStructuredPairs === 0) {
+ return {
+ assistantIndexes: new Set(),
+ userIndexes: new Set()
+ };
+ }
+
+ const sortedAssistantIndexes = [...pairs.assistantIndexes].sort((left, right) => left - right);
+ if (sortedAssistantIndexes.length <= maxStructuredPairs) {
+ return {
+ assistantIndexes: new Set(pairs.assistantIndexes),
+ userIndexes: new Set(pairs.userIndexes)
+ };
+ }
+
+ const keptAssistantIndexes = sortedAssistantIndexes.slice(-maxStructuredPairs);
+ return {
+ assistantIndexes: new Set(keptAssistantIndexes),
+ userIndexes: new Set(keptAssistantIndexes.map(index => index + 1))
+ };
+}
+
+export function getAnthropicToolHistoryDebugInfo(
+ messages: readonly AnthropicToolPairMessage[]
+ ,
+ maxStructuredPairs?: number
+): AnthropicToolHistoryDebugInfo {
+ const structuredPairs = maxStructuredPairs === undefined
+ ? getStructuredAnthropicToolPairIndexes(messages)
+ : applyStructuredAnthropicToolPairLimit(
+ getStructuredAnthropicToolPairIndexes(messages),
+ maxStructuredPairs
+ );
+ const messageDebug: AnthropicToolHistoryMessageDebug[] = [];
+ const orphanToolResultIds: string[] = [];
+ const leadingOrphanToolResultIds: string[] = [];
+
+ for (let index = 0; index < messages.length; index++) {
+ const message = messages[index];
+ const content = normalizeAnthropicContent(message.content);
+ const toolUseIds = getToolUseIds(content);
+ const toolResultIds = getToolResultIds(content);
+ const structuredMode = message.role === 'assistant'
+ ? (structuredPairs.assistantIndexes.has(index) ? 'structured' : 'text')
+ : (structuredPairs.userIndexes.has(index) ? 'structured' : 'text');
+ const hasLeadingOrphanToolResult = message.role === 'user'
+ && toolResultIds.length > 0
+ && !structuredPairs.userIndexes.has(index);
+
+ if (hasLeadingOrphanToolResult) {
+ orphanToolResultIds.push(...toolResultIds);
+ if (index === 0) {
+ leadingOrphanToolResultIds.push(...toolResultIds);
+ }
+ }
+
+ messageDebug.push({
+ index,
+ role: message.role,
+ blockTypes: content.map(block => block.type),
+ toolUseIds,
+ toolResultIds,
+ hasLeadingOrphanToolResult,
+ structuredMode
+ });
+ }
+
+ return {
+ messageCount: messages.length,
+ structuredAssistantIndexes: [...structuredPairs.assistantIndexes],
+ structuredUserIndexes: [...structuredPairs.userIndexes],
+ leadingOrphanToolResultIds,
+ orphanToolResultIds,
+ messages: messageDebug
+ };
+}
diff --git a/src/services/AuditService.ts b/src/services/AuditService.ts
index 1db0f99..8dc523f 100644
--- a/src/services/AuditService.ts
+++ b/src/services/AuditService.ts
@@ -19,6 +19,7 @@ export interface AuditEntry {
responseHeaders?: Record<string, unknown>;
requestBody?: unknown;
responseBody?: unknown;
+ debug?: unknown;
}
export interface DailyStats {
diff --git a/src/test/CopilotApiGateway.test.ts b/src/test/CopilotApiGateway.test.ts
index 74794d8..5621a12 100644
--- a/src/test/CopilotApiGateway.test.ts
+++ b/src/test/CopilotApiGateway.test.ts
@@ -2,7 +2,10 @@
import * as assert from 'assert';
import {
+ applyStructuredAnthropicToolPairLimit,
+ flattenAnthropicMessageForTextHistory,
getAnthropicToolUseId,
+ getAnthropicToolHistoryDebugInfo,
getStructuredAnthropicToolPairIndexes,
type AnthropicToolPairMessage
} from '../anthropicToolPairs.js';
@@ -79,4 +82,155 @@ suite('CopilotApiGateway Anthropic tool message handling', () => {
assert.equal(toolUseId, 'toolu_fallback');
});
+
+ test('reports leading orphan tool_result blocks in debug info', () => {
+ const debugInfo = getAnthropicToolHistoryDebugInfo([
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_orphan', content: 'done' },
+ ],
+ },
+ ]);
+
+ assert.deepEqual(debugInfo.leadingOrphanToolResultIds, ['toolu_orphan']);
+ assert.deepEqual(debugInfo.orphanToolResultIds, ['toolu_orphan']);
+ assert.equal(debugInfo.messages[0].structuredMode, 'text');
+ assert.equal(debugInfo.messages[0].hasLeadingOrphanToolResult, true);
+ });
+
+ test('reports structured tool pairs in debug info', () => {
+ const debugInfo = getAnthropicToolHistoryDebugInfo([
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool_use', id: 'toolu_1', name: 'read_file', input: { path: 'README.md' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_1', content: 'contents' },
+ ],
+ },
+ ]);
+
+ assert.deepEqual(debugInfo.structuredAssistantIndexes, [0]);
+ assert.deepEqual(debugInfo.structuredUserIndexes, [1]);
+ assert.deepEqual(debugInfo.leadingOrphanToolResultIds, []);
+ assert.equal(debugInfo.messages[0].structuredMode, 'structured');
+ assert.equal(debugInfo.messages[1].structuredMode, 'structured');
+ });
+
+ test('limits structured tool pairs to the most recent pairs', () => {
+ const pairs = getStructuredAnthropicToolPairIndexes([
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool_use', id: 'toolu_old', name: 'read_file', input: { path: 'old.txt' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_old', content: 'old' },
+ ],
+ },
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool_use', id: 'toolu_new', name: 'read_file', input: { path: 'new.txt' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_new', content: 'new' },
+ ],
+ },
+ ]);
+
+ const limited = applyStructuredAnthropicToolPairLimit(pairs, 1);
+
+ assert.equal(limited.assistantIndexes.has(0), false);
+ assert.equal(limited.userIndexes.has(1), false);
+ assert.equal(limited.assistantIndexes.has(2), true);
+ assert.equal(limited.userIndexes.has(3), true);
+ });
+
+ test('drops all structured tool pairs when the limit is zero', () => {
+ const pairs = getStructuredAnthropicToolPairIndexes([
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool_use', id: 'toolu_old', name: 'read_file', input: { path: 'old.txt' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_old', content: 'old' },
+ ],
+ },
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool_use', id: 'toolu_new', name: 'read_file', input: { path: 'new.txt' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_new', content: 'new' },
+ ],
+ },
+ ]);
+
+ const limited = applyStructuredAnthropicToolPairLimit(pairs, 0);
+
+ assert.deepEqual([...limited.assistantIndexes], []);
+ assert.deepEqual([...limited.userIndexes], []);
+ });
+
+ test('downgrades assistant tool_use history without pseudo tool call syntax', () => {
+ const flattened = flattenAnthropicMessageForTextHistory({
+ role: 'assistant',
+ content: [
+ { type: 'text', text: 'I will inspect the file.' },
+ { type: 'tool_use', id: 'toolu_1', name: 'Read', input: { file_path: '/tmp/demo' } },
+ ],
+ });
+
+ assert.equal(flattened, 'I will inspect the file.');
+ assert.equal(flattened.includes('[Tool call:'), false);
+ });
+
+ test('keeps tool result text when downgrading user tool history', () => {
+ const flattened = flattenAnthropicMessageForTextHistory({
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'toolu_1', content: 'line 1\nline 2' },
+ ],
+ });
+
+ assert.equal(flattened, 'line 1\nline 2');
+ });
+
+ test('preserves image placeholders when downgrading user tool history', () => {
+ const flattened = flattenAnthropicMessageForTextHistory({
+ role: 'user',
+ content: [
+ {
+ type: 'tool_result',
+ tool_use_id: 'toolu_1',
+ content: [
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'abc' } },
+ { type: 'text', text: 'OCR result' },
+ ],
+ },
+ ],
+ });
+
+ assert.equal(flattened, '[image omitted]\nOCR result');
+ });
});