All files / src/provider tool-call-aggregator.ts

76.59% Statements 72/94
60% Branches 51/85
70% Functions 7/10
76.59% Lines 72/94

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 2338x   8x                             8x                   8x                     79x 79x   79x 79x     79x 79x 79x         79x 79x                       32x       9x                           18x       59x 59x 61x 61x       61x 61x 46x   61x 61x 50x 48x 2x     2x   2x       2x                     61x 61x   61x   61x 1x           60x 60x 60x           47x 37x 37x       3x 3x 3x 3x   34x 34x 34x 34x 34x 34x                   2x 3x 2x             73x 11x     11x 11x 11x           11x 1x 1x                 1x 1x 1x   1x 10x 10x 10x           11x 11x                                    
import { randomUUID } from "node:crypto";
import * as vscode from "vscode";
import {
  getToolSchemaMap,
  extractChatRequestContext,
  getCompletedToolCallKeys,
  buildToolCallCanonicalKey,
  isDuplicateSuppressionEnabled,
  isToolCallInput,
  hasRequiredToolArguments,
  parseToolArguments,
  parseToolArgumentsStrict,
  repairToolArguments,
  ChatRequestContext,
  ToolSchema,
  SkippedToolCallReason,
} from "../tools/parser";
import { debugLog } from "../shared/logging";
import { NimToolCall } from "../types";
 
export interface ToolCallStreamAggregatorOptions {
  options: vscode.ProvideLanguageModelChatResponseOptions;
  messages: readonly vscode.LanguageModelChatMessage[];
  onEmitToolCall: (id: string, name: string, args: Record<string, unknown>) => void;
  onSkipToolCall: (name: string, required: string[], reason?: SkippedToolCallReason) => void;
}
 
export class ToolCallStreamAggregator {
  private toolSchemas: Map<string, ToolSchema>;
  private requestContext: ChatRequestContext | undefined;
  private emittedTextToolCallKeys: Set<string>;
  private onEmitToolCall: (id: string, name: string, args: Record<string, unknown>) => void;
  private onSkipToolCall: (
    name: string,
    required: string[],
    reason?: SkippedToolCallReason,
  ) => void;
 
  private toolCallBuffers = new Map<number, { id?: string; name?: string; args: string }>();
  private completedToolCallIndices = new Set<number>();
 
  private sawToolCall = false;
  private emittedToolCall = false;
 
  constructor(options: ToolCallStreamAggregatorOptions) {
    this.toolSchemas = getToolSchemaMap(options.options);
    this.requestContext = extractChatRequestContext(options.messages);
    this.emittedTextToolCallKeys = getCompletedToolCallKeys(
      options.messages,
      this.requestContext,
      this.toolSchemas,
    );
    this.onEmitToolCall = options.onEmitToolCall;
    this.onSkipToolCall = options.onSkipToolCall;
  }
 
  public getSawToolCall(): boolean {
    return this.sawToolCall;
  }
 
  public getEmittedToolCall(): boolean {
    return this.emittedToolCall;
  }
 
  public getToolSchemas(): Map<string, ToolSchema> {
    return this.toolSchemas;
  }
 
  public getRequestContext(): ChatRequestContext | undefined {
    return this.requestContext;
  }
 
  public recordExtractedParameters(params: Record<string, unknown>): void {
    Iif (!this.requestContext) {
      this.requestContext = {};
    }
    this.requestContext.extractedParameters = {
      ...(this.requestContext.extractedParameters ?? {}),
      ...params,
    };
  }
 
  public getEmittedTextToolCallKeys(): Set<string> {
    return this.emittedTextToolCallKeys;
  }
 
  public handleToolCalls(deltas: readonly NimToolCall[]): void {
    this.sawToolCall = true;
    for (const tc of deltas) {
      const idx = (tc as { index?: number }).index ?? 0;
      Iif (this.completedToolCallIndices.has(idx)) {
        continue;
      }
 
      const buf = this.toolCallBuffers.get(idx) ?? { args: "" };
      if (tc.id && typeof tc.id === "string") {
        buf.id = tc.id;
      }
      const func = tc.function;
      if (func?.name && typeof func.name === "string") {
        if (!buf.name || buf.name === func.name) {
          buf.name = func.name;
        } else Iif (func.name.startsWith(buf.name)) {
          // Some providers repeat a cumulative prefix as the name arrives.
          buf.name = func.name;
        } else Iif (buf.name.startsWith(func.name)) {
          // Keep the longer prefix when a provider repeats an earlier fragment.
        } else if (this.hasToolNameCandidate(`${buf.name}${func.name}`)) {
          // A complete tool name can itself be a prefix of another tool name.
          // Prefer the concatenated candidate while it still matches a known
          // name or prefix (for example, `read` + `_file` => `read_file`).
          buf.name += func.name;
        } else Eif (this.toolSchemas.has(func.name)) {
          buf.name = func.name;
        } else if (this.toolSchemas.has(buf.name)) {
          // A complete known name followed by an unrelated fragment should
          // not turn into a different tool name.
        } else {
          // OpenAI-compatible streams may split function names across deltas.
          buf.name += func.name;
        }
      }
      if (typeof func?.arguments === "string") {
        buf.args += func.arguments;
      }
      this.toolCallBuffers.set(idx, buf);
 
      if (buf.args.trim().length === 0) {
        continue;
      }
 
      // Only emit early when the current buffer is strict JSON and already
      // satisfies its schema. Incomplete JSON and syntactically valid but
      // incomplete required arguments stay buffered until the stream ends.
      try {
        const schema = this.toolSchemas.get(buf.name ?? "");
        const args = repairToolArguments(
          buf.name ?? "",
          parseToolArgumentsStrict(buf.args),
          this.requestContext,
          schema,
        );
        if (buf.name && isToolCallInput(args) && hasRequiredToolArguments(args, schema)) {
          const canonicalKey = buildToolCallCanonicalKey(buf.name, args);
          if (
            isDuplicateSuppressionEnabled(buf.name) &&
            this.emittedTextToolCallKeys.has(canonicalKey)
          ) {
            this.onSkipToolCall(buf.name, [], "duplicate");
            this.completedToolCallIndices.add(idx);
            this.toolCallBuffers.delete(idx);
            continue;
          }
          const id = buf.id && buf.id.length > 0 ? buf.id : `tool_${randomUUID()}`;
          this.onEmitToolCall(id, buf.name, args);
          this.emittedToolCall = true;
          this.emittedTextToolCallKeys.add(canonicalKey);
          this.completedToolCallIndices.add(idx);
          this.toolCallBuffers.delete(idx);
        }
      } catch {
        // JSON is incomplete or fails schema validation; flushRemaining() will
        // repair and validate the complete buffer at stream end.
      }
    }
  }
 
  private hasToolNameCandidate(name: string): boolean {
    for (const knownName of this.toolSchemas.keys()) {
      if (knownName === name || knownName.startsWith(name)) {
        return true;
      }
    }
    return false;
  }
 
  public flushRemaining(): void {
    for (const [idx, buf] of Array.from(this.toolCallBuffers.entries())) {
      Iif (this.completedToolCallIndices.has(idx)) {
        continue;
      }
      try {
        const schema = this.toolSchemas.get(buf.name ?? "");
        const args = repairToolArguments(
          buf.name ?? "",
          buf.args ? parseToolArguments(buf.args) : {},
          this.requestContext,
          schema,
        );
        if (buf.name && isToolCallInput(args) && hasRequiredToolArguments(args, schema)) {
          const canonicalKey = buildToolCallCanonicalKey(buf.name, args);
          Iif (
            isDuplicateSuppressionEnabled(buf.name) &&
            this.emittedTextToolCallKeys.has(canonicalKey)
          ) {
            this.onSkipToolCall(buf.name, [], "duplicate");
            this.completedToolCallIndices.add(idx);
            this.toolCallBuffers.delete(idx);
            continue;
          }
          const id = buf.id && buf.id.length > 0 ? buf.id : `tool_${randomUUID()}`;
          this.onEmitToolCall(id, buf.name, args);
          this.emittedToolCall = true;
 
          this.emittedTextToolCallKeys.add(canonicalKey);
        } else if (buf.name || buf.id || buf.args) {
          this.onSkipToolCall(buf.name ?? "unknown_tool", schema?.required ?? []);
          debugLog("Skipped invalid tool call at stream end", {
            id: buf.id,
            name: buf.name,
            args,
          });
        }
        this.completedToolCallIndices.add(idx);
        this.toolCallBuffers.delete(idx);
      } catch {
        Iif (buf.name || buf.id || buf.args) {
          this.onSkipToolCall(
            buf.name ?? "unknown_tool",
            this.toolSchemas.get(buf.name ?? "")?.required ?? [],
          );
        }
        debugLog("Skipped truncated tool call at stream end", {
          id: buf.id,
          name: buf.name,
        });
        this.completedToolCallIndices.add(idx);
        this.toolCallBuffers.delete(idx);
      }
    }
  }
}