@pedrofariasx/qwenproxy 1.2.0 → 1.2.2

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.
@@ -1,252 +0,0 @@
1
- /*
2
- * Layer 1: Streaming State Machine
3
- * Incremental parser that processes token-by-token chunks
4
- * Maintains structural state without requiring complete input
5
- */
6
-
7
- import type { ParserState } from './types'
8
-
9
- export interface StreamChunkResult {
10
- buffer: string
11
- triggersExtraction: boolean
12
- inProgress: boolean
13
- }
14
-
15
- export class StreamingStateMachine {
16
- private state: ParserState = {
17
- buffer: '',
18
- insideCodeBlock: false,
19
- braceDepth: 0,
20
- bracketDepth: 0,
21
- inString: false,
22
- escapeNext: false,
23
- potentialToolStart: false,
24
- }
25
-
26
- private lastChunkEndsWithJson: boolean = false
27
-
28
- reset(): void {
29
- this.state = {
30
- buffer: '',
31
- insideCodeBlock: false,
32
- braceDepth: 0,
33
- bracketDepth: 0,
34
- inString: false,
35
- escapeNext: false,
36
- potentialToolStart: false,
37
- }
38
- this.lastChunkEndsWithJson = false
39
- }
40
-
41
- getState(): ParserState {
42
- return { ...this.state }
43
- }
44
-
45
- isInsideStructuredValue(): boolean {
46
- return this.state.braceDepth > 0 || this.state.bracketDepth > 0
47
- }
48
-
49
- push(chunk: string): StreamChunkResult {
50
- this.state.buffer += chunk
51
-
52
- for (let i = 0; i < chunk.length; i++) {
53
- const char = chunk[i]
54
- this.processChar(char)
55
- }
56
-
57
- const triggersExtraction = this.shouldAttemptExtraction()
58
- const inProgress = this.isInsideStructuredValue() || this.looksLikeReAct(chunk)
59
-
60
- return {
61
- buffer: this.state.buffer,
62
- triggersExtraction,
63
- inProgress,
64
- }
65
- }
66
-
67
- private processChar(char: string): void {
68
- const { inString, escapeNext } = this.state
69
-
70
- if (escapeNext) {
71
- this.state.escapeNext = false
72
- return
73
- }
74
-
75
- if (char === '\\' && inString) {
76
- this.state.escapeNext = true
77
- return
78
- }
79
-
80
- if (!inString) {
81
- if (char === '"') {
82
- this.state.inString = true
83
- return
84
- }
85
-
86
- if (char === '{') {
87
- this.state.braceDepth++
88
- this.state.potentialToolStart = true
89
- return
90
- }
91
-
92
- if (char === '}') {
93
- if (this.state.braceDepth > 0) this.state.braceDepth--
94
- this.updatePotentialToolStart()
95
- return
96
- }
97
-
98
- if (char === '[') {
99
- this.state.bracketDepth++
100
- return
101
- }
102
-
103
- if (char === ']') {
104
- if (this.state.bracketDepth > 0) this.state.bracketDepth--
105
- return
106
- }
107
-
108
- if (char === '`') {
109
- this.state.insideCodeBlock = !this.state.insideCodeBlock
110
- return
111
- }
112
- } else {
113
- if (char === '"') {
114
- this.state.inString = false
115
- return
116
- }
117
- }
118
- }
119
-
120
- private updatePotentialToolStart(): void {
121
- const { buffer, braceDepth } = this.state
122
- if (braceDepth > 0) return
123
-
124
- const trimmed = buffer.trimEnd()
125
- if (trimmed.length === 0) {
126
- this.state.potentialToolStart = false
127
- return
128
- }
129
-
130
- const lastBlock = this.extractLastBlock(trimmed)
131
- if (lastBlock) {
132
- this.state.potentialToolStart = true
133
- }
134
- }
135
-
136
- private extractLastBlock(text: string): string | null {
137
- let depth = 0
138
- let start = -1
139
-
140
- for (let i = text.length - 1; i >= 0; i--) {
141
- const char = text[i]
142
- if (char === '}') {
143
- if (depth === 0) start = i
144
- depth++
145
- } else if (char === '{') {
146
- depth--
147
- if (depth === 0 && start !== -1) {
148
- return text.slice(i, start + 1)
149
- }
150
- }
151
- }
152
-
153
- return null
154
- }
155
-
156
- private looksLikeReAct(chunk: string): boolean {
157
- const markers = ['Action:', 'Action Input:', 'Thought:']
158
-
159
- for (const marker of markers) {
160
- if (chunk.includes(marker)) return true
161
- }
162
-
163
- return false
164
- }
165
-
166
- private shouldAttemptExtraction(): boolean {
167
- const { braceDepth, buffer } = this.state
168
-
169
- if (braceDepth === 0 && buffer.trim().length > 0) {
170
- const trimmed = buffer.trimEnd()
171
- return trimmed.endsWith('}') || trimmed.endsWith(']')
172
- }
173
-
174
- return false
175
- }
176
-
177
- extractCompleteSpans(): string[] {
178
- const spans: string[] = []
179
- const { buffer, braceDepth } = this.state
180
-
181
- if (braceDepth !== 0) return spans
182
-
183
- const trimmed = buffer.trim()
184
- if (trimmed.length === 0) return spans
185
-
186
- // Extract JSON objects/arrays
187
- let depth = 0
188
- let start = -1
189
- let inString = false
190
- let escape = false
191
-
192
- for (let i = 0; i < trimmed.length; i++) {
193
- const char = trimmed[i]
194
-
195
- if (escape) {
196
- escape = false
197
- continue
198
- }
199
-
200
- if (char === '\\' && inString) {
201
- escape = true
202
- continue
203
- }
204
-
205
- if (char === '"' && !escape) {
206
- inString = !inString
207
- continue
208
- }
209
-
210
- if (inString) continue
211
-
212
- if (char === '{' || char === '[') {
213
- if (depth === 0) start = i
214
- depth++
215
- } else if (char === '}' || char === ']') {
216
- depth--
217
- if (depth === 0 && start !== -1) {
218
- spans.push(trimmed.slice(start, i + 1))
219
- start = -1
220
- }
221
- }
222
- }
223
-
224
- // Check for ReAct patterns
225
- const reactMatch = trimmed.match(/Action:\s*(\w+)\s*\n?Action Input:\s*(\{[\s\S]*\})/) ||
226
- trimmed.match(/Action:\s*(\w+)\s*Action Input:\s*(\{[\s\S]*\})/)
227
-
228
- if (reactMatch && !spans.includes(reactMatch[2])) {
229
- spans.push(reactMatch[2])
230
- }
231
-
232
- return spans
233
- }
234
-
235
- hasCompleteContent(): boolean {
236
- const { braceDepth, buffer } = this.state
237
-
238
- if (braceDepth !== 0) return false
239
-
240
- const trimmed = buffer.trim()
241
- return trimmed.includes('{') || trimmed.includes('[') ||
242
- /Action:\s*\w+\s*\n?Action Input:/.test(trimmed)
243
- }
244
-
245
- getBuffer(): string {
246
- return this.state.buffer
247
- }
248
-
249
- setBuffer(buffer: string): void {
250
- this.state.buffer = buffer
251
- }
252
- }
@@ -1,352 +0,0 @@
1
- /*
2
- * Layer 2: Structural AST Parser (Tolerant)
3
- * Builds partial AST from JSON-like structures without strict parsing
4
- */
5
-
6
- import type { PartialASTNode, ToolCallSource } from './types'
7
-
8
- export interface StructuralParseResult {
9
- ast: PartialASTNode | null
10
- confidence: number
11
- errors: string[]
12
- sourceHint: ToolCallSource
13
- }
14
-
15
- export class StructuralParser {
16
- private pos = 0
17
- private text = ''
18
- private errors: string[] = []
19
-
20
- parse(text: string, sourceHint: ToolCallSource = 'unknown'): StructuralParseResult {
21
- this.pos = 0
22
- this.text = text.trim()
23
- this.errors = []
24
-
25
- if (this.text.length === 0) {
26
- return { ast: null, confidence: 0, errors: ['Empty input'], sourceHint }
27
- }
28
-
29
- const nodes: PartialASTNode[] = []
30
-
31
- while (this.pos < this.text.length) {
32
- this.skipWhitespace()
33
- if (this.pos >= this.text.length) break
34
- const node = this.parseValue()
35
- if (node) nodes.push(node)
36
- }
37
-
38
- if (nodes.length === 0) {
39
- return { ast: null, confidence: 0, errors: ['No parseable content'], sourceHint }
40
- }
41
-
42
- const root: PartialASTNode = {
43
- type: 'object',
44
- raw: this.text,
45
- confidence: this.calculateConfidence(nodes),
46
- }
47
- if (nodes.length === 1 && nodes[0].type === 'object' && nodes[0].value !== undefined) {
48
- root.value = nodes[0].value
49
- root.children = nodes[0].children
50
- } else {
51
- root.children = nodes
52
- }
53
-
54
- return { ast: root, confidence: root.confidence, errors: this.errors, sourceHint }
55
- }
56
-
57
- private parseValue(): PartialASTNode | undefined {
58
- const char = this.peek()
59
- if (char === '{') return this.parseObject()
60
- if (char === '[') return this.parseArray()
61
- if (char === '"' || char === "'") return this.parseString()
62
- if (this.isNull(char)) return this.parseNull()
63
- if (this.isBoolean(char)) return this.parseBoolean()
64
- if (this.isNumberStart(char)) return this.parseNumber()
65
- if (this.isUnquotedKey(char)) return this.parseUnquotedValue()
66
- if (this.isReActAction(char)) return this.parseReActBlock()
67
- return undefined
68
- }
69
-
70
- private parseObject(): PartialASTNode {
71
- const start = this.pos
72
- this.expect('{')
73
- const children: PartialASTNode[] = []
74
-
75
- while (this.pos < this.text.length) {
76
- this.skipWhitespace()
77
- if (this.peek() === '}') { this.pos++; break }
78
-
79
- const key = this.parseKey()
80
- if (!key) { this.pos++; this.errors.push(`Expected key at position ${this.pos}`); continue }
81
-
82
- this.skipWhitespace()
83
- this.expectOptional(':')
84
- this.skipWhitespace()
85
-
86
- let value: PartialASTNode | undefined
87
- const ch = this.peek()
88
- if (ch === '"' || ch === "'") value = this.parseString()
89
- else if (ch === '{') value = this.parseObject()
90
- else if (ch === '[') value = this.parseArray()
91
- else value = this.parseScalar()
92
-
93
- if (value) {
94
- children.push({
95
- type: 'object',
96
- value: value.value,
97
- raw: this.text.slice(start, this.pos),
98
- confidence: 1,
99
- children: [key, value],
100
- })
101
- }
102
-
103
- this.skipWhitespace()
104
- if (this.expectOptional(',')) {
105
- this.skipWhitespace()
106
- if (this.peek() === '}') break
107
- }
108
- }
109
-
110
- const value: Record<string, unknown> = {}
111
- for (const child of children) {
112
- if (child.children && child.children.length >= 2) {
113
- const key = child.children[0].value
114
- const val = child.children[1].value
115
- if (key !== undefined) value[key as string] = val
116
- }
117
- }
118
-
119
- return {
120
- type: 'object',
121
- value,
122
- raw: this.text.slice(start, this.pos),
123
- confidence: this.calculateObjectConfidence(children),
124
- children,
125
- }
126
- }
127
-
128
- private parseArray(): PartialASTNode {
129
- const start = this.pos
130
- this.expect('[')
131
- const children: PartialASTNode[] = []
132
-
133
- while (this.pos < this.text.length) {
134
- this.skipWhitespace()
135
- if (this.peek() === ']') { this.pos++; break }
136
- const value = this.parseValue()
137
- if (value) children.push(value)
138
- this.skipWhitespace()
139
- this.expectOptional(',')
140
- }
141
-
142
- return {
143
- type: 'array',
144
- raw: this.text.slice(start, this.pos),
145
- confidence: children.length > 0 ? 0.9 : 0.5,
146
- children,
147
- }
148
- }
149
-
150
- private parseString(): PartialASTNode {
151
- const start = this.pos
152
- const quote = this.peek()
153
- this.expect(quote as '"' | "'")
154
- let value = ''
155
- try {
156
- value = this.readStringContent(quote)
157
- } catch {
158
- this.errors.push(`Unterminated string at position ${start}`)
159
- const content = this.text.slice(start + 1)
160
- const idx = content.split('').findIndex((c, i) => c === quote && (i === 0 || content[i - 1] !== '\\'))
161
- value = idx === -1 ? content : content.slice(0, idx)
162
- this.pos = this.text.length
163
- }
164
- return { type: 'string', value, raw: this.text.slice(start, this.pos), confidence: 0.95 }
165
- }
166
-
167
- private readStringContent(quote: string): string {
168
- let value = ''
169
- while (this.pos < this.text.length) {
170
- const char = this.text[this.pos++]
171
- if (char === '\\' && this.pos < this.text.length) {
172
- const next = this.text[this.pos++]
173
- value += this.resolveEscapeSequence(char, next)
174
- continue
175
- }
176
- if (char === quote) break
177
- value += char
178
- }
179
- return value
180
- }
181
-
182
- private resolveEscapeSequence(_backslash: string, char: string): string {
183
- const map: Record<string, string> = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', "'": "'", '\\': '\\', '0': '\0' }
184
- return map[char] ?? _backslash + char
185
- }
186
-
187
- private parseKey(): PartialASTNode | undefined {
188
- const start = this.pos
189
- if (this.peek() === '"' || this.peek() === "'") {
190
- const key = this.parseString()
191
- return { type: 'string', value: key.value, raw: key.raw, confidence: 1 }
192
- }
193
-
194
- let key = ''
195
- while (this.pos < this.text.length) {
196
- const c = this.text[this.pos]
197
- if (/[a-zA-Z0-9_\-]/.test(c)) { key += c; this.pos++ }
198
- else break
199
- }
200
-
201
- if (key.length === 0) { this.pos = start; return undefined }
202
- }
203
-
204
- private parseScalar(): PartialASTNode | undefined {
205
- const start = this.pos
206
- let value = ''
207
- while (this.pos < this.text.length) {
208
- const c = this.text[this.pos]
209
- if (c === ',' || c === '}' || c === ']' || c === '\n') break
210
- value += c
211
- this.pos++
212
- }
213
- value = value.trim()
214
-
215
- if (value === 'true') return { type: 'boolean', value: true, raw: value, confidence: 1 }
216
- if (value === 'false') return { type: 'boolean', value: false, raw: value, confidence: 1 }
217
- if (value === 'null' || value === 'undefined') return { type: 'null', value: null, raw: value, confidence: 0.9 }
218
- const num = Number(value)
219
- if (!isNaN(num) && isFinite(num)) return { type: 'number', value: num, raw: value, confidence: 0.9 }
220
- if (value.startsWith('"') && value.endsWith('"')) return { type: 'string', value: value.slice(1, -1), raw: value, confidence: 0.85 }
221
- if (value.startsWith("'") && value.endsWith("'")) return { type: 'string', value: value.slice(1, -1), raw: value, confidence: 0.8 }
222
- return { type: 'unknown', value, raw: value, confidence: 0.3 }
223
- }
224
-
225
- private parseUnquotedValue(): PartialASTNode | undefined {
226
- const start = this.pos
227
- let value = ''
228
- while (this.pos < this.text.length) {
229
- const c = this.text[this.pos]
230
- if (/[a-zA-Z0-9_\- ]/.test(c)) { value += c; this.pos++ }
231
- else break
232
- }
233
- if (value.length === 0) return undefined
234
- return { type: 'unknown', value: value.trim(), raw: value, confidence: 0.5 }
235
- }
236
-
237
- private parseNull(): PartialASTNode | undefined {
238
- if (this.text.slice(this.pos, this.pos + 4) === 'null') {
239
- this.pos += 4
240
- return { type: 'null', value: null, raw: 'null', confidence: 1 }
241
- }
242
- return undefined
243
- }
244
-
245
- private parseBoolean(): PartialASTNode | undefined {
246
- if (this.text.slice(this.pos, this.pos + 4) === 'true') {
247
- this.pos += 4
248
- return { type: 'boolean', value: true, raw: 'true', confidence: 1 }
249
- }
250
- if (this.text.slice(this.pos, this.pos + 5) === 'false') {
251
- this.pos += 5
252
- return { type: 'boolean', value: false, raw: 'false', confidence: 1 }
253
- }
254
- return undefined
255
- }
256
-
257
- private parseNumber(): PartialASTNode | undefined {
258
- const start = this.pos
259
- let value = ''
260
- while (this.pos < this.text.length) {
261
- const c = this.text[this.pos]
262
- if (/[0-9.\-eE+]/.test(c)) { value += c; this.pos++ }
263
- else break
264
- }
265
- if (value.length === 0) return undefined
266
- const num = Number(value)
267
- if (!isNaN(num) && isFinite(num)) return { type: 'number', value: num, raw: value, confidence: 0.9 }
268
- return { type: 'unknown', value, raw: value, confidence: 0.3 }
269
- }
270
-
271
- private parseReActBlock(): PartialASTNode | undefined {
272
- const start = this.pos
273
- let action = ''
274
- let input = ''
275
-
276
- const actionMatch = this.text.slice(this.pos).match(/^Action:\s*(\w+)/i)
277
- if (!actionMatch) return undefined
278
- action = actionMatch[1]
279
- this.pos += actionMatch[0].length
280
- this.skipWhitespace()
281
-
282
- const inputMatch = this.text.slice(this.pos).match(/^Action Input:\s*(\{[\s\S]*)/i)
283
- if (inputMatch) {
284
- input = inputMatch[1].trim()
285
- this.pos += inputMatch[0].length
286
- }
287
-
288
- return { type: 'object', value: { action, input }, raw: this.text.slice(start, this.pos), confidence: 0.85 }
289
- }
290
-
291
- private isReActAction(char: string): boolean {
292
- return /^Action:|^thought|^Observation|^Final Answer/i.test(this.text.slice(this.pos))
293
- }
294
- private isNull(char: string): boolean { return this.text.slice(this.pos, this.pos + 4) === 'null' }
295
- private isBoolean(char: string): boolean {
296
- return this.text.slice(this.pos, this.pos + 4) === 'true' || this.text.slice(this.pos, this.pos + 5) === 'false'
297
- }
298
- private isNumberStart(char: string): boolean { return /[0-9.\-]/.test(char) }
299
- private isUnquotedKey(char: string): boolean { return /[a-zA-Z_]/.test(char) && !this.isNull(char) && !this.isReActAction(char) }
300
-
301
- private skipWhitespace(): void {
302
- while (this.pos < this.text.length && /\s/.test(this.text[this.pos])) this.pos++
303
- }
304
- private peek(): string { return this.text[this.pos] ?? '' }
305
- private expect(char: string): boolean {
306
- if (this.peek() === char) { this.pos++; return true }
307
- this.errors.push(`Expected '${char}' at position ${this.pos}, got '${this.peek()}'`)
308
- return false
309
- }
310
- private expectOptional(char: string): boolean {
311
- if (this.peek() === char) { this.pos++; return true }
312
- return false
313
- }
314
-
315
- private calculateConfidence(nodes: PartialASTNode[]): number {
316
- if (nodes.length === 0) return 0
317
- const avg = nodes.reduce((a, n) => a + n.confidence, 0) / nodes.length
318
- return Math.max(0, Math.min(1, avg - Math.min(this.errors.length * 0.1, 0.5)))
319
- }
320
-
321
- private calculateObjectConfidence(children: PartialASTNode[]): number {
322
- if (children.length === 0) return 0.1
323
- let confidence = 0.7
324
- if (children.some(c => c.children && c.children[0]?.type === 'string')) confidence += 0.2
325
- if (this.errors.length === 0) confidence += 0.1
326
- if (children.length >= 2) confidence += 0.05
327
- return Math.min(0.99, confidence)
328
- }
329
-
330
- static extractJsonFromText(text: string): string[] {
331
- const results: string[] = []
332
- let depth = 0, start = -1, inString = false, escape = false
333
-
334
- for (let i = 0; i < text.length; i++) {
335
- const char = text[i]
336
- if (escape) { escape = false; continue }
337
- if (char === '\\' && inString) { escape = true; continue }
338
- if (char === '"' && !escape) { inString = !inString; continue }
339
- if (inString) continue
340
-
341
- if (char === '{' || char === '[') {
342
- if (depth === 0) start = i
343
- depth++
344
- } else if (char === '}' || char === ']') {
345
- depth--
346
- if (depth === 0 && start !== -1) { results.push(text.slice(start, i + 1)); start = -1 }
347
- }
348
- }
349
-
350
- return results
351
- }
352
- }
@@ -1,74 +0,0 @@
1
- /*
2
- * File: types.ts
3
- * Project: qwenproxy
4
- * UltraToolCallLinter - Core type definitions
5
- */
6
-
7
- export type ToolCallSource = 'openai' | 'claude' | 'gemini' | 'react' | 'unknown'
8
-
9
- export interface CanonicalToolCall {
10
- tool: string
11
- input: Record<string, unknown>
12
- meta?: {
13
- source: ToolCallSource
14
- confidence: number
15
- repaired: boolean
16
- }
17
- }
18
-
19
- export interface ParserState {
20
- buffer: string
21
- insideCodeBlock: boolean
22
- braceDepth: number
23
- bracketDepth: number
24
- inString: boolean
25
- escapeNext: boolean
26
- potentialToolStart: boolean
27
- }
28
-
29
- export interface PartialASTNode {
30
- type: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'null' | 'unknown'
31
- value?: unknown
32
- raw: string
33
- confidence: number
34
- children?: PartialASTNode[]
35
- }
36
-
37
- export interface RawToolCandidate {
38
- source: ToolCallSource
39
- raw: Record<string, unknown>
40
- rawString: string
41
- confidence: number
42
- }
43
-
44
- export interface ParseResult {
45
- text: string
46
- toolCalls: CanonicalToolCall[]
47
- errors: string[]
48
- confidence: number
49
- }
50
-
51
- export interface SecurityViolation {
52
- type: 'shell_injection' | 'filesystem_access' | 'ssrf' | 'prompt_injection' | 'encoded_payload'
53
- field: string
54
- value: string
55
- detail: string
56
- }
57
-
58
- export interface ToolRegistry {
59
- [name: string]: {
60
- name: string
61
- description: string
62
- parameters: Record<string, unknown>
63
- required?: string[]
64
- strict?: boolean
65
- }
66
- }
67
-
68
- export interface ToolDefinition {
69
- name: string
70
- description: string
71
- parameters: Record<string, unknown>
72
- required?: string[]
73
- strict?: boolean
74
- }