Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 | 11x 11x 11x 11x 14x 14x 14x 2x 2x 79x 79x 11x 13x 11x 118x 11x 55x 11x 48x 1x 47x 47x 3x 44x 162x 162x 107x 55x 93x 107x 11x 79x 79x 72x 72x 6x 66x 66x 66x 66x 60x 60x 79x 79x 12x 12x 12x 6x 79x 79x 12x 12x 12x 6x 6x 6x 79x 11x 91x 91x 89x 89x 137x 89x 89x 89x 159x 20x 159x 10x 89x 91x 254x 168x 86x 86x 164x 164x 164x 164x 4x 164x 164x 2x 164x 164x 1x 164x 86x 164x 163x 1x 1x 247x 85x 162x 162x 2x 160x 4x 4x 156x 11x 1x 1x 1x 1x 1x 247x 247x 156x 156x 1x 1x 1x 155x 247x 6x 241x 2x 6x 239x 174x 174x 174x 374x 241x 174x 12x 4x 118x 1x 117x 71x 24x 11x 5x 1x 3x 5x 5x 11x 86x 86x 86x 137x 137x 23x 63x 121x 3x 60x 11x 81x 11x 2x 1x 1x 1x 1x 11x 64x 4x 60x 32x 2x 58x 58x 18x 18x 40x 40x 28x 12x 11x 1343x 1343x 11348x 4x 1339x 11x 79x 79x 1343x 1343x 4x 79x 11x 13x 13x 13x 11x 75x 75x 11x 17x 17x 17x 1x 1x 16x 2661x 2661x 12x 12x 11x 190x 190x 190x 2470x 190x 190x 189x 1x 1x 1x 3x 3x 3x 11x 11x 1x 11x 7x 7x 11x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 11x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 155x 377x 155x 189x 189x 90x 99x 99x 1x 1x 98x 155x 188x 188x 188x 141x 141x 141x 188x 1141x 188x 188x 188x 79x 79x 75x 4x 4x 79x 109x 109x 109x 24x 24x 85x 7x 7x 7x 7x 7x 78x 13x 13x 2x 2x 11x 1x 1x 1x 10x 10x 9x 10x 10x 65x 16x 16x 5x 5x 11x 11x 11x 11x 11x 11x 4x 4x 7x 7x 49x 49x 49x 16x 16x 33x 33x 33x 33x 33x 33x 19x 155x 11x 155x 155x 155x 155x 15x 15x 15x 12x 12x 3x 3x 140x 140x 140x 2x 2x 2x 2x 138x 138x 1x 137x 137x 137x 137x 137x 137x 137x 11x 79x 79x 79x 79x 79x 82x 82x 82x 82x 16x 66x 66x 66x 66x 6x 66x 3x 66x 4x 4x 4x 4x 4x 66x 79x 11x 84x 9x 75x 167x 167x 103x 64x 64x 62x 2x 1x 1x 1x 11x 85x 85x 85x 85x 1x 84x 84x 19x 84x 16x 84x 1x 1x 1x 84x 84x 588x 63x 393x 2x 2x 84x 84x 84x 1x 1x 84x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 84x 84x 3x 1x 1x 3x 3x 84x 84x 84x 75x 9x 7x 5x 7x 3x 7x 3x 2x 1x 1x 1x 9x 1x 1x 1x 9x 11x 58x | import * as vscode from "vscode";
import { LanguageModelChatMessage, ProvideLanguageModelChatResponseOptions } from "vscode";
import { jsonrepair } from "jsonrepair";
import { ConfigManager } from "../shared/config";
import {
extractStandaloneXmlParameters as scanStandaloneXmlParameters,
findXmlConstructStart,
indexOfUnquoted,
isTokenInStringOrRegexLiteral,
scanXmlToolConstruct,
} from "./xml-tool-scanner";
function safeJsonParse(text: string): Record<string, unknown> {
Iif (!text) return {};
try {
return parseToolArgumentsStrict(text);
} catch {
// Repair is deliberately attempted only after strict JSON parsing fails.
}
try {
return parseJsonObject(JSON.parse(jsonrepair(text)));
} catch {
throw new Error("Failed to parse JSON");
}
}
function parseJsonObject(value: unknown): Record<string, unknown> {
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
throw new Error("Tool arguments must be a JSON object");
}
export function parseToolArguments(text: string): Record<string, unknown> {
return safeJsonParse(text);
}
export function parseToolArgumentsStrict(text: string): Record<string, unknown> {
return parseJsonObject(JSON.parse(text));
}
export type ToolSchemaType = "string" | "number" | "integer" | "boolean" | "object" | "array";
export interface ToolPropertySchema {
type?: ToolSchemaType;
enum?: unknown[];
required?: string[];
properties?: Record<string, ToolPropertySchema>;
items?: ToolPropertySchema;
}
export interface ToolSchema {
required?: string[];
enumValues?: Record<string, string[]>;
properties?: Record<string, ToolPropertySchema>;
}
export type SkippedToolCallReason = "invalid" | "duplicate" | "missing_payload";
export interface SkippedToolCall {
name: string;
required: string[];
reason?: SkippedToolCallReason;
}
export interface ParsedTextToolCall {
name: string;
args: unknown;
}
export interface ParsedTextSegmentText {
type: "text";
text: string;
}
export interface ParsedTextSegmentToolCall {
type: "toolCall";
toolCall: ParsedTextToolCall;
}
export interface ParsedTextSegmentInvalidToolCall {
type: "invalidToolCall";
name: string;
}
export type ParsedTextSegment =
| ParsedTextSegmentText
| ParsedTextSegmentToolCall
| ParsedTextSegmentInvalidToolCall;
export interface ParsedTextToolCallResult {
segments: ParsedTextSegment[];
incompleteText: string;
extractedParams?: Record<string, unknown>;
}
export interface ChatRequestContext {
filePath?: string;
startLine?: number;
endLine?: number;
cwd?: string;
extractedParameters?: Record<string, unknown>;
}
export function buildToolCallCanonicalKey(name: string, args: unknown): string {
return `${name}:${JSON.stringify(sortObjectKeys(args))}`;
}
export function isDuplicateSuppressionEnabled(toolName: string): boolean {
if (!ConfigManager.getToolsConfig().suppressDuplicateReads) {
return false;
}
const normalized = toolName.toLowerCase();
if (
normalized.includes("terminal") ||
normalized.includes("command") ||
normalized.includes("exec") ||
normalized.includes("write") ||
normalized.includes("edit") ||
normalized.includes("create") ||
normalized.includes("delete") ||
normalized.includes("patch") ||
normalized.includes("replace") ||
normalized.includes("apply") ||
normalized.includes("grep") ||
normalized.includes("search") ||
normalized.includes("find")
) {
return false;
}
return true;
}
function sortObjectKeys(value: unknown): unknown {
Iif (Array.isArray(value)) {
return value.map(sortObjectKeys);
}
if (typeof value !== "object" || value === null) {
return value;
}
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, child]) => [key, sortObjectKeys(child)]),
);
}
export function getCompletedToolCallKeys(
messages: readonly LanguageModelChatMessage[],
requestContext: ChatRequestContext | undefined,
toolSchemas: ReadonlyMap<string, ToolSchema>,
): Set<string> {
let startIndex = 0;
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (message.role !== vscode.LanguageModelChatMessageRole.User) {
continue;
}
const hasNonToolResultContent = message.content.some((part) => {
const toolResultPart = part as { callId?: unknown; content?: unknown[] };
return !(typeof toolResultPart.callId === "string" && Array.isArray(toolResultPart.content));
});
if (hasNonToolResultContent) {
startIndex = i + 1;
break;
}
}
const completedCallIds = new Set<string>();
for (const message of messages.slice(startIndex)) {
for (const part of message.content) {
const toolResultPart = part as { callId?: unknown; content?: unknown[] };
if (typeof toolResultPart.callId === "string" && Array.isArray(toolResultPart.content)) {
completedCallIds.add(toolResultPart.callId);
}
}
}
const keys = new Set<string>();
for (const message of messages.slice(startIndex)) {
for (const part of message.content) {
const toolCallPart = part as { callId?: unknown; name?: unknown; input?: unknown };
if (
typeof toolCallPart.callId !== "string" ||
!completedCallIds.has(toolCallPart.callId) ||
typeof toolCallPart.name !== "string"
) {
continue;
}
const repairedArgs = repairToolArguments(
toolCallPart.name,
toolCallPart.input ?? {},
requestContext,
toolSchemas.get(toolCallPart.name),
);
keys.add(buildToolCallCanonicalKey(toolCallPart.name, repairedArgs));
}
}
return keys;
}
export function getToolSchemaMap(
options: ProvideLanguageModelChatResponseOptions,
): Map<string, ToolSchema> {
const map = new Map<string, ToolSchema>();
for (const tool of options.tools ?? []) {
const inputSchema = tool.inputSchema as
| { required?: unknown; properties?: unknown }
| undefined;
const required = Array.isArray(inputSchema?.required)
? inputSchema.required.filter(
(value): value is string => typeof value === "string" && value.length > 0,
)
: undefined;
const properties = normalizeProperties(inputSchema?.properties);
const enumValues: Record<string, string[]> = {};
for (const [name, propertySchema] of Object.entries(properties)) {
const allowed = propertySchema.enum?.filter(
(item): item is string => typeof item === "string",
);
if (allowed && allowed.length > 0) {
enumValues[name] = allowed;
}
}
map.set(tool.name, {
required,
enumValues,
properties,
});
}
return map;
}
function normalizeProperties(value: unknown): Record<string, ToolPropertySchema> {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return {};
}
const properties: Record<string, ToolPropertySchema> = {};
for (const [name, rawSchema] of Object.entries(value)) {
Iif (typeof rawSchema !== "object" || rawSchema === null || Array.isArray(rawSchema)) {
continue;
}
const schema = rawSchema as {
type?: unknown;
enum?: unknown;
required?: unknown;
properties?: unknown;
items?: unknown;
};
const type =
schema.type === "string" ||
schema.type === "number" ||
schema.type === "integer" ||
schema.type === "boolean" ||
schema.type === "object" ||
schema.type === "array"
? schema.type
: undefined;
const property: ToolPropertySchema = {
...(type ? { type } : {}),
...(Array.isArray(schema.enum) ? { enum: schema.enum } : {}),
...(Array.isArray(schema.required)
? {
required: schema.required.filter(
(item): item is string => typeof item === "string" && item.length > 0,
),
}
: {}),
};
const nestedProperties = normalizeProperties(schema.properties);
if (Object.keys(nestedProperties).length > 0) {
property.properties = nestedProperties;
}
const nestedItems = normalizePropertySchema(schema.items);
if (nestedItems) {
property.items = nestedItems;
}
properties[name] = property;
}
return properties;
}
function normalizePropertySchema(value: unknown): ToolPropertySchema | undefined {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return undefined;
}
const normalized = normalizeProperties({ value });
return normalized.value;
}
function normalizeScalar(value: unknown, schema: ToolPropertySchema): unknown {
if (typeof value !== "string") {
return value;
}
const trimmed = value.trim();
if (schema.type === "boolean") {
if (["true", "yes", "1"].includes(trimmed.toLowerCase())) return true;
Iif (["false", "no", "0"].includes(trimmed.toLowerCase())) return false;
}
if (schema.type === "number" || schema.type === "integer") {
const numberValue = Number(trimmed);
if (trimmed.length > 0 && Number.isFinite(numberValue)) return numberValue;
}
return value;
}
export function tryParseJsonValue(text: string): unknown {
Iif (!text) return text;
try {
return JSON.parse(text);
} catch {
// Attempt jsonrepair if strict parse fails
}
try {
return JSON.parse(jsonrepair(text));
} catch {
return text;
}
}
function normalizeValue(value: unknown, schema: ToolPropertySchema): unknown {
let normalized = normalizeScalar(value, schema);
if (typeof normalized === "string") {
const trimmed = normalized.trim();
if (
schema.type === "array" ||
(!schema.type && trimmed.startsWith("[") && trimmed.endsWith("]"))
) {
const parsed = tryParseJsonValue(trimmed);
if (Array.isArray(parsed)) {
normalized = parsed;
}
} else Iif (
schema.type === "object" ||
(!schema.type && trimmed.startsWith("{") && trimmed.endsWith("}"))
) {
const parsed = tryParseJsonValue(trimmed);
Iif (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
normalized = parsed;
}
}
}
if (
schema.type === "object" &&
typeof normalized === "object" &&
normalized !== null &&
!Array.isArray(normalized)
) {
return normalizeArguments(normalized as Record<string, unknown>, {
properties: schema.properties,
});
}
if (schema.type === "array" && Array.isArray(normalized)) {
return schema.items
? normalized.map((item) => normalizeValue(item, schema.items!))
: normalized;
}
return normalized;
}
function normalizeArguments(
args: Record<string, unknown>,
schema: ToolSchema,
): Record<string, unknown> {
const properties = schema.properties ?? {};
const normalized: Record<string, unknown> = { ...args };
for (const [name, propertySchema] of Object.entries(properties)) {
if (name in normalized) {
normalized[name] = normalizeValue(normalized[name], propertySchema);
}
}
return normalized;
}
function valuesEqual(left: unknown, right: unknown): boolean {
if (Object.is(left, right)) return true;
return typeof left === "object" && left !== null && typeof right === "object" && right !== null
? JSON.stringify(left) === JSON.stringify(right)
: false;
}
function isSchemaValueValid(value: unknown, schema: ToolPropertySchema): boolean {
if (schema.enum && !schema.enum.some((allowed) => valuesEqual(value, allowed))) {
return false;
}
switch (schema.type) {
case "string":
return typeof value === "string";
case "number":
return typeof value === "number" && Number.isFinite(value);
case "integer":
return typeof value === "number" && Number.isInteger(value);
case "boolean":
return typeof value === "boolean";
case "array":
return (
Array.isArray(value) &&
(!schema.items || value.every((item) => isSchemaValueValid(item, schema.items!)))
);
case "object":
Iif (typeof value !== "object" || value === null || Array.isArray(value)) return false;
return validateToolArguments(value, {
required: schema.required,
properties: schema.properties,
});
default:
return true;
}
}
export function validateToolArguments(args: unknown, schema: ToolSchema | undefined): boolean {
Iif (!schema || typeof args !== "object" || args === null || Array.isArray(args)) {
return false;
}
const record = args as Record<string, unknown>;
for (const key of schema.required ?? []) {
const value = record[key];
if (
value === undefined ||
value === null ||
(typeof value === "string" && value.trim() === "")
) {
return false;
}
}
for (const [name, propertySchema] of Object.entries(schema.properties ?? {})) {
if (name in record && !isSchemaValueValid(record[name], propertySchema)) {
return false;
}
}
return true;
}
export function hasRequiredToolArguments(args: unknown, schema: ToolSchema | undefined): boolean {
return validateToolArguments(args, schema);
}
export function buildInvalidToolCallFallback(
skippedToolCalls: readonly SkippedToolCall[],
): string | undefined {
if (skippedToolCalls.some((toolCall) => toolCall.reason === "missing_payload")) {
return "The model indicated a tool call but the stream did not include tool arguments. Retry the request.";
}
if (
skippedToolCalls.length > 0 &&
skippedToolCalls.every((toolCall) => toolCall.reason === "duplicate")
) {
return `Tool call \`${skippedToolCalls[0].name}\` was not repeated because it already completed with the same arguments. Call it again only with different arguments.`;
}
const skippedWithRequiredArgs = skippedToolCalls.find((toolCall) => toolCall.required.length > 0);
Iif (skippedWithRequiredArgs) {
const requiredArgs = skippedWithRequiredArgs.required.map((arg) => `\`${arg}\``).join(", ");
return `Tool call \`${skippedWithRequiredArgs.name}\` was rejected: missing ${requiredArgs}. Retry with all required fields filled.`;
}
const firstSkippedToolCall = skippedToolCalls[0];
Iif (!firstSkippedToolCall) {
return undefined;
}
return `Tool call \`${firstSkippedToolCall.name}\` had invalid arguments. Retry with a valid JSON object.`;
}
export function buildInvalidToolCallRetryMessage(
skippedToolCalls: readonly SkippedToolCall[],
): string | undefined {
if (skippedToolCalls.some((toolCall) => toolCall.reason === "missing_payload")) {
return [
"Your previous response finished with tool_calls but no tool function arguments were received.",
"Retry NOW with a native tool call that includes the function name and a complete JSON arguments object.",
"Do not emit an empty tool_calls array.",
"Do not ask the user to retry. Do not explain the error.",
].join(" ");
}
if (
skippedToolCalls.length > 0 &&
skippedToolCalls.every((toolCall) => toolCall.reason === "duplicate")
) {
return [
`Your previous tool call "${skippedToolCalls[0].name}" was identical to one that already completed.`,
"Retry NOW with different arguments (for read_file, pass a new startLine/endLine for the unread range).",
"Do not ask the user to retry. Do not explain the error.",
].join(" ");
}
const skippedWithRequiredArgs = skippedToolCalls.find((toolCall) => toolCall.required.length > 0);
if (skippedWithRequiredArgs) {
const requiredList = skippedWithRequiredArgs.required.join(", ");
return [
`Your previous tool call "${skippedWithRequiredArgs.name}" was rejected because it was missing required arguments: ${requiredList}.`,
`Retry NOW. Provide a valid JSON object containing ALL of: ${requiredList}.`,
"Do not call any tool with an empty object or missing fields.",
"Do not ask the user to retry. Do not explain the error.",
].join(" ");
}
const firstSkippedToolCall = skippedToolCalls[0];
if (!firstSkippedToolCall) {
return undefined;
}
return [
`Your previous tool call "${firstSkippedToolCall.name}" was rejected due to invalid or incomplete arguments.`,
"Retry NOW with a complete, valid JSON object.",
"Do not emit malformed JSON or empty arguments.",
"Do not ask the user to retry. Do not explain what went wrong.",
].join(" ");
}
export function findTrailingTokenPrefixStart(text: string, token: string): number {
const maxPrefixLength = Math.min(text.length, token.length - 1);
for (let prefixLength = maxPrefixLength; prefixLength > 0; prefixLength -= 1) {
if (text.endsWith(token.slice(0, prefixLength))) {
return text.length - prefixLength;
}
}
return -1;
}
export function findTrailingTokenPrefixStartAny(text: string, tokens: readonly string[]): number {
let bestMatch = -1;
for (const token of tokens) {
const matchIndex = findTrailingTokenPrefixStart(text, token);
if (matchIndex !== -1 && (bestMatch === -1 || matchIndex < bestMatch)) {
bestMatch = matchIndex;
}
}
return bestMatch;
}
export function unwrapJsonCodeFence(text: string): string {
const trimmed = text.trim();
const fencedMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
return fencedMatch ? fencedMatch[1].trim() : trimmed;
}
export function isValidToolIdentifier(name: string): boolean {
const trimmed = name.trim();
return trimmed.length > 0 && trimmed.length <= 64 && /^[a-zA-Z0-9_.-]+$/.test(trimmed);
}
export function parseEmbeddedToolParameterValue(rawValue: string): unknown {
const trimmed = rawValue.trim();
Iif (!trimmed) return "";
if (
/^[\\[{\"]/.test(trimmed) ||
/^(?:true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)$/.test(trimmed)
) {
try {
return JSON.parse(trimmed);
} catch {
try {
return JSON.parse(jsonrepair(trimmed));
} catch {
return trimmed;
}
}
}
return trimmed;
}
function stripPatternOutsideLiterals(text: string, pattern: RegExp, contextPrefix = ""): string {
const global = new RegExp(
pattern.source,
pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`,
);
return text.replace(global, (match, ...rest) => {
const offset = rest[rest.length - 2] as number;
return isTokenInStringOrRegexLiteral(contextPrefix + text, contextPrefix.length + offset)
? match
: "";
});
}
export function stripKnownControlText(text: string, contextPrefix = ""): string {
const controlPatterns = [
/<|DSML|[^\s<]*/g,
/<\|DSML\|>[^\s<]*/g,
/<\|python_tag\|>/g,
/<\|start_header_id\|>.*?<\|end_header_id\|>/g,
/<\|eot_id\|>/g,
/<\|eom_id\|>/g,
/<\|im_start\|>[^\n]*/g,
/<\|im_end\|>/g,
/<\|observation\|>/g,
/<\|assistant\|>/g,
/\[gMASK\]/g,
/<sop>/g,
/<eop>/g,
];
let sanitized = text;
for (const pattern of controlPatterns) {
sanitized = stripPatternOutsideLiterals(sanitized, pattern, contextPrefix);
}
const orphanClose = /<\/(?:tool_calls|tool_call|function|parameter|tool_parameter|invoke)>/gi;
if (!sanitized.includes("```")) {
return stripPatternOutsideLiterals(sanitized, orphanClose, contextPrefix);
}
const parts = sanitized.split(/(```[\s\S]*?```)/g);
let walked = contextPrefix;
return parts
.map((part) => {
const next = part.startsWith("```")
? part
: stripPatternOutsideLiterals(part, orphanClose, walked);
walked += part;
return next;
})
.join("");
}
export function parseXmlParameters(content: string): Record<string, unknown> {
const trimmed = content.trim();
Iif (trimmed.startsWith("{") && trimmed.endsWith("}")) {
try {
const parsed = safeJsonParse(trimmed);
Iif (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
return parsed;
}
} catch {
// Fall through to the tag-stack scan of parameter tags.
}
}
const scanned = scanXmlToolConstruct(
`<tool_call name="_">${content}</tool_call>`,
parseEmbeddedToolParameterValue,
() => true,
);
Iif (scanned.status === "complete" && scanned.toolCall) {
return scanned.toolCall.args;
}
return {};
}
export function extractStandaloneXmlParameters(text: string): {
cleanText: string;
extractedParams: Record<string, unknown>;
} {
return scanStandaloneXmlParameters(text, parseEmbeddedToolParameterValue);
}
export function findControlTextTerminatorIndex(text: string): number {
const terminatorMatch = text.match(/[\s<]/);
return terminatorMatch?.index ?? -1;
}
export function parseDeepSeekTextEmbeddedToolCallContent(
content: string,
): { name: string; argsText: string } | undefined {
const separatorToken = "<|tool▁sep|>";
const separatorIndex = content.indexOf(separatorToken);
Iif (separatorIndex === -1) {
return undefined;
}
const afterSeparator = content.slice(separatorIndex + separatorToken.length).trim();
Iif (!afterSeparator) {
return undefined;
}
const newlineIndex = afterSeparator.indexOf("\n");
const name =
newlineIndex === -1 ? afterSeparator.trim() : afterSeparator.slice(0, newlineIndex).trim();
const argsText =
newlineIndex === -1 ? "" : unwrapJsonCodeFence(afterSeparator.slice(newlineIndex).trim());
Iif (!name || !isValidToolIdentifier(name)) {
return undefined;
}
return {
name,
argsText,
};
}
export function parseTextEmbeddedToolCalls(text: string): ParsedTextToolCallResult {
const beginToken = "<|tool_call_begin|>";
const argBeginToken = "<|tool_call_argument_begin|>";
const endToken = "<|tool_call_end|>";
const deepSeekCallsBeginToken = "<|tool▁calls▁begin|>";
const deepSeekCallBeginToken = "<|tool▁call▁begin|>";
const deepSeekCallEndToken = "<|tool▁call▁end|>";
const deepSeekCallsEndToken = "<|tool▁calls▁end|>";
const unicodeDsmlToken = "<|DSML|";
const asciiDsmlToken = "<|DSML|>";
const partialTokens = [
beginToken,
deepSeekCallsBeginToken,
deepSeekCallBeginToken,
deepSeekCallsEndToken,
unicodeDsmlToken,
asciiDsmlToken,
"<tool_calls>",
"<tool_call",
"<function=",
"<invoke ",
"<parameter=",
"<parameter name=",
"<tool_parameter",
"<|python_tag|>",
"<|start_header_id|>",
"<|im_start|>",
"[gMASK]",
] as const;
const extractedParams: Record<string, unknown> = {};
const segments: ParsedTextSegment[] = [];
let remaining = text;
let incompleteText = "";
const textContextPrefix = (): string =>
segments.map((segment) => (segment.type === "text" ? segment.text : "")).join("");
const appendText = (value: string): void => {
const sanitizedValue = stripKnownControlText(value, textContextPrefix());
if (!sanitizedValue) {
return;
}
const lastSegment = segments.at(-1);
if (lastSegment?.type === "text") {
lastSegment.text += sanitizedValue;
return;
}
segments.push({ type: "text", text: sanitizedValue });
};
while (remaining.length > 0) {
const accumulatedSoFar = textContextPrefix();
const xmlStartIndex = findXmlConstructStart(remaining, accumulatedSoFar);
const isInsideCodeFence = (offset: number): boolean => {
const textUpToOffset = accumulatedSoFar + remaining.slice(0, offset);
const matches = textUpToOffset.match(/```/g);
return matches !== null && matches.length % 2 === 1;
};
const tokenMatches = [
{
kind: "openai" as const,
token: beginToken,
index: indexOfUnquoted(remaining, beginToken, 0, accumulatedSoFar),
},
{
kind: "strip" as const,
token: deepSeekCallsBeginToken,
index: indexOfUnquoted(remaining, deepSeekCallsBeginToken, 0, accumulatedSoFar),
},
{
kind: "deepseek" as const,
token: deepSeekCallBeginToken,
index: indexOfUnquoted(remaining, deepSeekCallBeginToken, 0, accumulatedSoFar),
},
{
kind: "strip" as const,
token: deepSeekCallsEndToken,
index: indexOfUnquoted(remaining, deepSeekCallsEndToken, 0, accumulatedSoFar),
},
{
kind: "control" as const,
token: unicodeDsmlToken,
index: indexOfUnquoted(remaining, unicodeDsmlToken, 0, accumulatedSoFar),
},
{
kind: "control" as const,
token: asciiDsmlToken,
index: indexOfUnquoted(remaining, asciiDsmlToken, 0, accumulatedSoFar),
},
...(xmlStartIndex !== -1
? [{ kind: "xml" as const, token: remaining[xmlStartIndex], index: xmlStartIndex }]
: []),
].filter((match) => match.index !== -1 && !isInsideCodeFence(match.index));
tokenMatches.sort((left, right) => left.index - right.index);
const nextTokenMatch = tokenMatches[0];
if (!nextTokenMatch) {
const partialBeginIndex = findTrailingTokenPrefixStartAny(remaining, partialTokens);
if (
partialBeginIndex === -1 ||
isTokenInStringOrRegexLiteral(
accumulatedSoFar + remaining,
accumulatedSoFar.length + partialBeginIndex,
)
) {
appendText(remaining);
} else {
appendText(remaining.slice(0, partialBeginIndex));
incompleteText = remaining.slice(partialBeginIndex);
}
break;
}
appendText(remaining.slice(0, nextTokenMatch.index));
remaining = remaining.slice(nextTokenMatch.index);
if (nextTokenMatch.kind === "strip") {
remaining = remaining.slice(nextTokenMatch.token.length);
continue;
}
if (nextTokenMatch.kind === "control") {
remaining = remaining.slice(nextTokenMatch.token.length);
const terminatorIndex = findControlTextTerminatorIndex(remaining);
if (terminatorIndex === -1) {
incompleteText = nextTokenMatch.token + remaining;
break;
}
remaining = remaining.slice(terminatorIndex);
continue;
}
if (nextTokenMatch.kind === "xml") {
const scanned = scanXmlToolConstruct(
remaining,
parseEmbeddedToolParameterValue,
isValidToolIdentifier,
);
if (scanned.status === "incomplete") {
incompleteText = remaining;
break;
}
if (scanned.status === "not-a-tag") {
appendText(remaining.slice(0, scanned.skip));
remaining = remaining.slice(scanned.skip);
continue;
}
Iif (scanned.extractedParams) {
Object.assign(extractedParams, scanned.extractedParams);
}
if (scanned.toolCall) {
segments.push({
type: "toolCall",
toolCall: scanned.toolCall,
});
}
remaining = remaining.slice(scanned.consumed);
continue;
}
if (nextTokenMatch.kind === "deepseek") {
const endIndex = remaining.indexOf(deepSeekCallEndToken);
if (endIndex === -1) {
incompleteText = remaining;
break;
}
const callText = remaining.slice(nextTokenMatch.token.length, endIndex);
remaining = remaining.slice(endIndex + deepSeekCallEndToken.length);
const parsedToolCallContent = parseDeepSeekTextEmbeddedToolCallContent(callText);
if (parsedToolCallContent) {
try {
const parsedArgs = parsedToolCallContent.argsText
? parseToolArgumentsStrict(parsedToolCallContent.argsText)
: {};
segments.push({
type: "toolCall",
toolCall: { name: parsedToolCallContent.name, args: parsedArgs },
});
continue;
} catch {
segments.push({ type: "invalidToolCall", name: parsedToolCallContent.name });
continue;
}
}
appendText(`${nextTokenMatch.token}${callText}${deepSeekCallEndToken}`);
continue;
}
// OpenAI format
const argBeginIndex = remaining.indexOf(argBeginToken);
const endIndex = remaining.indexOf(endToken);
if (argBeginIndex === -1 || endIndex === -1 || argBeginIndex > endIndex) {
incompleteText = remaining;
break;
}
const name = remaining.slice(beginToken.length, argBeginIndex).trim();
const argsText = remaining.slice(argBeginIndex + argBeginToken.length, endIndex).trim();
remaining = remaining.slice(endIndex + endToken.length);
Iif (!name || !isValidToolIdentifier(name)) {
continue;
}
try {
segments.push({
type: "toolCall",
toolCall: { name, args: parseToolArgumentsStrict(argsText) },
});
} catch {
segments.push({ type: "invalidToolCall", name });
}
}
return { segments, incompleteText, extractedParams };
}
export function getIncompleteTextToolCallName(text: string): string | undefined {
const openaiBeginToken = "<|tool_call_begin|>";
const openaiArgumentToken = "<|tool_call_argument_begin|>";
const openaiBeginIndex = text.indexOf(openaiBeginToken);
if (openaiBeginIndex !== -1) {
const callText = text.slice(openaiBeginIndex + openaiBeginToken.length);
const argumentIndex = callText.indexOf(openaiArgumentToken);
if (argumentIndex !== -1) {
const name = callText.slice(0, argumentIndex).trim();
return isValidToolIdentifier(name) ? name : undefined;
}
const name = callText.split(/[\s<|]/u, 1)[0]?.trim();
return name && isValidToolIdentifier(name) ? name : undefined;
}
const deepSeekBeginToken = "<|tool▁call▁begin|>";
const deepSeekBeginIndex = text.indexOf(deepSeekBeginToken);
if (deepSeekBeginIndex !== -1) {
const callText = text.slice(deepSeekBeginIndex + deepSeekBeginToken.length);
const parsed = parseDeepSeekTextEmbeddedToolCallContent(callText);
const name = parsed?.name?.trim();
return name && isValidToolIdentifier(name) ? name : undefined;
}
const xmlHermesMatch = text.match(/<tool_call>\s*<function=([a-zA-Z0-9_.-]+)/i);
if (xmlHermesMatch) {
return isValidToolIdentifier(xmlHermesMatch[1]) ? xmlHermesMatch[1].trim() : undefined;
}
const xmlStandardMatch = text.match(/<tool_call\s+name="([a-zA-Z0-9_.-]+)"/i);
Iif (xmlStandardMatch) {
return isValidToolIdentifier(xmlStandardMatch[1]) ? xmlStandardMatch[1].trim() : undefined;
}
const xmlInvokeMatch = text.match(/<invoke\s+name="([a-zA-Z0-9_.-]+)"/i);
Iif (xmlInvokeMatch) {
return isValidToolIdentifier(xmlInvokeMatch[1]) ? xmlInvokeMatch[1].trim() : undefined;
}
const xmlFunctionMatch = text.match(/<function=([a-zA-Z0-9_.-]+)/i);
Iif (xmlFunctionMatch) {
return isValidToolIdentifier(xmlFunctionMatch[1]) ? xmlFunctionMatch[1].trim() : undefined;
}
return undefined;
}
export function extractChatRequestContext(
messages: readonly LanguageModelChatMessage[],
): ChatRequestContext | undefined {
const filePattern = /The user's current file is\s+([^\n]+?)\.(?:\s|$)/;
const selectionPattern = /The current selection is from line\s+(\d+)\s+to line\s+(\d+)/;
const cwdPattern = /(?:^|\n)Cwd:\s+([^\n]+)/;
const context: ChatRequestContext = {};
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
for (const part of message.content) {
const text =
part instanceof vscode.LanguageModelTextPart
? part.value
: typeof part === "object" &&
part !== null &&
"value" in part &&
typeof (part as { value?: unknown }).value === "string"
? (part as { value: string }).value
: undefined;
if (!text) {
continue;
}
const fileMatch = text.match(filePattern);
const selectionMatch = text.match(selectionPattern);
const cwdMatch = text.match(cwdPattern);
if (fileMatch && !context.filePath) {
context.filePath = fileMatch[1].trim();
}
if (cwdMatch && !context.cwd) {
context.cwd = cwdMatch[1].trim();
}
if (selectionMatch && context.startLine === undefined && context.endLine === undefined) {
const startLine = Number(selectionMatch[1]);
const endLine = Number(selectionMatch[2]);
if (Number.isFinite(startLine) && Number.isFinite(endLine)) {
context.startLine = startLine;
context.endLine = endLine;
}
}
Iif (
context.filePath &&
context.cwd &&
context.startLine !== undefined &&
context.endLine !== undefined
) {
break;
}
}
}
return context.filePath ||
context.cwd ||
context.startLine !== undefined ||
context.endLine !== undefined
? context
: undefined;
}
const AUXILIARY_BOOLEAN_FIELDS = new Set(["isregexp", "isregex", "casesensitive", "recursive"]);
function fillMissingAuxiliaryBooleans(
repaired: Record<string, unknown>,
schema: ToolSchema | undefined,
): void {
if (!schema?.required) {
return;
}
for (const key of schema.required) {
const current = repaired[key];
if (current !== undefined && current !== null) {
continue;
}
const property = schema.properties?.[key];
if (property?.type !== "boolean") {
continue;
}
if (!AUXILIARY_BOOLEAN_FIELDS.has(key.toLowerCase())) {
continue;
}
const enumValues = property.enum?.filter((item): item is boolean => typeof item === "boolean");
repaired[key] = enumValues && enumValues.length > 0 ? enumValues[0] : false;
}
}
export function repairToolArguments(
toolName: string,
args: unknown,
requestContext: ChatRequestContext | undefined,
schema?: ToolSchema,
): Record<string, unknown> {
let parsedArgs: Record<string, unknown>;
Iif (typeof args === "string") {
try {
parsedArgs = safeJsonParse(args);
} catch {
parsedArgs = {};
}
} else if (typeof args === "object" && args !== null && !Array.isArray(args)) {
parsedArgs = { ...(args as Record<string, unknown>) };
} else E{
parsedArgs = {};
}
if (!ConfigManager.getToolsConfig().autoRepairArguments) {
return parsedArgs;
}
const required = new Set(schema?.required ?? []);
const needsStringField = (value: unknown, field: string): boolean =>
required.has(field) && (typeof value !== "string" || value.trim().length === 0);
const needsNumberField = (value: unknown, field: string): boolean =>
required.has(field) && typeof value !== "number";
// 1. Merge extracted parameters from XML stream buffer if present
if (requestContext?.extractedParameters) {
for (const [key, value] of Object.entries(requestContext.extractedParameters)) {
if (!(key in parsedArgs) || parsedArgs[key] === undefined || parsedArgs[key] === "") {
parsedArgs[key] = value;
}
}
}
// 2. Resolve common property aliases when required properties are missing
const propertyAliases: Record<string, string[]> = {
filePath: [
"path",
"targetFile",
"target_file",
"file",
"filename",
"file_path",
"filepath",
"uri",
"destination",
"dest",
],
content: ["code", "text", "data", "body", "file_content", "fileContent"],
startLine: ["start", "fromLine", "from_line", "start_line"],
endLine: ["end", "toLine", "to_line", "end_line"],
path: ["directory", "dir", "folder", "cwd", "targetDirectory"],
query: ["pattern", "search_pattern", "searchPattern", "regex", "searchTerm", "search_term"],
command: ["cmd", "script", "commandLine", "command_line"],
};
for (const [canonicalKey, aliases] of Object.entries(propertyAliases)) {
if (
required.has(canonicalKey) &&
(parsedArgs[canonicalKey] === undefined || parsedArgs[canonicalKey] === "")
) {
for (const alias of aliases) {
if (parsedArgs[alias] !== undefined && parsedArgs[alias] !== "") {
parsedArgs[canonicalKey] = parsedArgs[alias];
break;
}
}
}
}
const repaired: Record<string, unknown> = normalizeArguments(parsedArgs, schema ?? {});
const argumentsSchema = schema?.properties?.arguments;
if (
typeof repaired.arguments === "string" &&
(!argumentsSchema || argumentsSchema.type === "object")
) {
try {
repaired.arguments = safeJsonParse(repaired.arguments);
} catch {
// Leave an invalid nested value for schema validation to reject.
}
}
if (
repaired.arguments &&
typeof repaired.arguments === "object" &&
!Array.isArray(repaired.arguments)
) {
const inner = repaired.arguments as Record<string, unknown>;
const outerRequiredKeys = schema?.required ?? [];
const knownPropertyNames = Object.keys(schema?.properties ?? {});
const hasRequiredInInner = outerRequiredKeys.some((k) => k in inner);
const hasKnownPropertyInInner = knownPropertyNames.some((k) => k in inner);
if (!schema?.properties?.arguments && (hasRequiredInInner || hasKnownPropertyInInner)) {
for (const [key, value] of Object.entries(inner)) {
if (!(key in repaired)) {
repaired[key] = value;
}
}
delete repaired.arguments;
}
}
const normalizedToolName = toolName.toLowerCase();
if (
normalizedToolName.includes("terminal") ||
normalizedToolName.includes("command") ||
normalizedToolName.includes("exec") ||
normalizedToolName === "run_in_terminal"
) {
if (needsStringField(repaired.goal, "goal")) {
if (typeof repaired.explanation === "string" && repaired.explanation.trim()) {
repaired.goal = repaired.explanation;
} else IEif (typeof repaired.command === "string" && repaired.command.trim()) {
repaired.goal = `Run: ${repaired.command.slice(0, 60)}`;
}
}
Iif (needsStringField(repaired.explanation, "explanation")) {
Iif (typeof repaired.goal === "string" && repaired.goal.trim()) {
repaired.explanation = repaired.goal;
}
}
Iif (needsStringField(repaired.mode, "mode")) {
repaired.mode = schema?.enumValues?.mode?.[0] ?? "sync";
}
}
fillMissingAuxiliaryBooleans(repaired, schema);
const context = requestContext;
if (!context) {
return normalizeArguments(repaired, schema ?? {});
}
if (normalizedToolName === "read_file") {
if (needsStringField(repaired.filePath, "filePath") && context.filePath) {
repaired.filePath = context.filePath;
}
if (needsNumberField(repaired.startLine, "startLine") && context.startLine !== undefined) {
repaired.startLine = context.startLine;
}
if (needsNumberField(repaired.endLine, "endLine") && context.endLine !== undefined) {
repaired.endLine = context.endLine;
}
} else if (
normalizedToolName.includes("file") ||
normalizedToolName === "create_file" ||
normalizedToolName === "write_file" ||
normalizedToolName === "edit_file"
) {
Iif (needsStringField(repaired.filePath, "filePath") && context.filePath) {
repaired.filePath = context.filePath;
}
Iif (needsNumberField(repaired.startLine, "startLine") && context.startLine !== undefined) {
repaired.startLine = context.startLine;
}
Iif (needsNumberField(repaired.endLine, "endLine") && context.endLine !== undefined) {
repaired.endLine = context.endLine;
}
}
if (
normalizedToolName === "list_dir" ||
normalizedToolName === "grep_search" ||
normalizedToolName === "find_files" ||
normalizedToolName.includes("dir")
) {
if (needsStringField(repaired.path, "path") && context.cwd) {
repaired.path = context.cwd;
}
Iif (needsStringField(repaired.cwd, "cwd") && context.cwd) {
repaired.cwd = context.cwd;
}
}
return normalizeArguments(repaired, schema ?? {});
}
export function isToolCallInput(args: unknown): args is Record<string, unknown> {
return typeof args === "object" && args !== null && !Array.isArray(args);
}
|