File size: 5,428 Bytes
db9635c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export interface ToolCall {
  name: string;
  args: Record<string, unknown>;
  rawArgs: string;
  startIndex?: number;
  endIndex?: number;
  complete: boolean;
}

export interface ParseResult {
  safeText: string;
  toolCalls: ToolCall[];
  pendingToolCall: boolean;
  errors: string[];
}

export class ToolParser {
  private buffer = "";
  private textBuffer = "";
  private lastReturnedTextLength = 0;
  private toolCalls: ToolCall[] = [];
  private errors: string[];
  private processedUpTo = 0;

  constructor() {
    this.errors = [];
  }

  reset(): void {
    this.buffer = "";
    this.textBuffer = "";
    this.lastReturnedTextLength = 0;
    this.toolCalls = [];
    this.errors = [];
    this.processedUpTo = 0;
  }

  process(text: string): ParseResult {
    this.buffer += text;

    // Use regex to find complete tool tags
    // This avoids htmlparser2 interpreting HTML inside JSON strings
    const toolRegex = /<tool\s+name="([^"]+)">([^]*?)<\/tool>/g;
    toolRegex.lastIndex = 0;

    let match;
    let lastMatchEnd = this.processedUpTo;

    while ((match = toolRegex.exec(this.buffer)) !== null) {
      // Only process new matches
      if (match.index < this.processedUpTo) continue;

      // Add text before the tool tag to textBuffer
      if (match.index > lastMatchEnd) {
        this.textBuffer += this.buffer.slice(lastMatchEnd, match.index);
      }

      const toolName = match[1];
      const rawContent = match[2];

      // Parse the JSON content
      let args: Record<string, unknown> = {};
      try {
        const trimmedContent = rawContent.trim();
        if (trimmedContent) {
          args = JSON.parse(trimmedContent);
        }
      } catch (e) {
        this.errors.push(`Failed to parse tool args for ${toolName}: ${e}`);
        args = {};
      }

      this.toolCalls.push({
        name: toolName,
        args,
        rawArgs: rawContent,
        startIndex: match.index,
        endIndex: match.index + match[0].length,
        complete: true,
      });

      lastMatchEnd = match.index + match[0].length;
      this.processedUpTo = lastMatchEnd;
    }

    // Check for incomplete tool tag at the end
    const remainingText = this.buffer.slice(this.processedUpTo);
    const incompleteToolRegex = /<tool\s+name="[^"]*"?\s*>?[^]*$/;
    const incompleteMatch = incompleteToolRegex.test(remainingText);

    if (!incompleteMatch && remainingText) {
      // No pending tool tag, add remaining text
      this.textBuffer += remainingText;
      this.processedUpTo = this.buffer.length;
    }

    // Return only new text since last call
    const newText = this.textBuffer.slice(this.lastReturnedTextLength);
    this.lastReturnedTextLength = this.textBuffer.length;

    return {
      safeText: newText,
      toolCalls: [...this.toolCalls],
      pendingToolCall: incompleteMatch,
      errors: [...this.errors],
    };
  }

  finalize(): ParseResult {
    // Process any remaining text
    const remainingText = this.buffer.slice(this.processedUpTo);
    if (remainingText && !/<tool\s/.test(remainingText)) {
      this.textBuffer += remainingText;
    }

    // Return any remaining text
    const newText = this.textBuffer.slice(this.lastReturnedTextLength);
    this.lastReturnedTextLength = this.textBuffer.length;

    return {
      safeText: newText,
      toolCalls: [...this.toolCalls],
      pendingToolCall: false,
      errors: [...this.errors],
    };
  }

  getAllText(): string {
    return this.textBuffer;
  }
}

export class StreamingToolParser {
  private parser: ToolParser;
  private lastToolCount = 0;
  private safeTextCallback?: (text: string) => void;
  private toolCallCallback?: (tool: ToolCall) => void;
  private errorCallback?: (error: string) => void;

  constructor(options?: {
    onSafeText?: (text: string) => void;
    onToolCall?: (tool: ToolCall) => void;
    onError?: (error: string) => void;
  }) {
    this.parser = new ToolParser();
    this.safeTextCallback = options?.onSafeText;
    this.toolCallCallback = options?.onToolCall;
    this.errorCallback = options?.onError;
  }

  write(chunk: string): ParseResult {
    const result = this.parser.process(chunk);

    // Handle callbacks
    if (result.safeText && this.safeTextCallback) {
      this.safeTextCallback(result.safeText);
    }

    if (result.toolCalls.length > this.lastToolCount) {
      const newTools = result.toolCalls.slice(this.lastToolCount);
      for (const tool of newTools) {
        if (tool.complete && this.toolCallCallback) {
          this.toolCallCallback(tool);
        }
      }
      this.lastToolCount = result.toolCalls.length;
    }

    if (result.errors.length > 0 && this.errorCallback) {
      for (const error of result.errors) {
        this.errorCallback(error);
      }
    }

    return result;
  }

  end(): ParseResult {
    return this.parser.finalize();
  }

  reset(): void {
    this.parser.reset();
    this.lastToolCount = 0;
  }
}

export function extractToolCalls(text: string): ToolCall[] {
  const parser = new ToolParser();
  parser.process(text);
  const result = parser.finalize();

  if (result.errors.length > 0) {
    console.warn("Tool parsing errors:", result.errors);
  }

  return result.toolCalls.filter((tc) => tc.complete);
}

export function filterToolCalls(text: string): string {
  const parser = new ToolParser();
  parser.process(text);
  parser.finalize();
  return parser.getAllText();
}