diff --git a/package.json b/package.json index 4737bcf..1afa3b3 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "deepseek:auth": "node scripts/deepseek_chrome_auth.js", "setup:agents": "node scripts/setup-agents.js", "test:syntax": "node --check server.js && node --check lib/pow.js && node --check lib/updater.js && node --check scripts/start.js && node --check scripts/auth.js && node --check scripts/lib/tui-menu.js && node --check scripts/lib/chrome-setup.js && node --check scripts/auth_import.js && node --check scripts/doctor.js && node --check scripts/deepseek_chrome_auth.js && node --check scripts/probe_deepseek_models.js && node --check scripts/setup-agents.js && node --check scripts/render-stars-chart.js && node --check scripts/live_agentic_smoke_tests.mjs && node --check public/dashboard/i18n.js && node --check public/dashboard/core.js && node --check public/dashboard/charts.js && node --check public/dashboard/markdown.js && node --check public/dashboard/status.js && node --check public/dashboard/accounts.js && node --check public/dashboard/usage.js && node --check public/dashboard/requests.js && node --check public/dashboard/settings.js && node --check public/dashboard/glyphfield.js && node --check public/dashboard/chat.js && node --check public/dashboard/agents.js && node --check public/dashboard/app.js", - "test:unit": "node --test tests/unit.test.js tests/account-failover.test.js tests/no_tools_regression.test.js tests/parser_delimiter_repair.test.js tests/parser_recovery_boundary.test.js tests/parser_fullwidth_tool_call.test.js tests/parser_garbled_dsml.test.js tests/glyph-field.test.js tests/chrome-setup.test.js tests/updater.test.js tests/update-api.test.js tests/agents-api.test.js tests/audit-auth.test.js tests/audit-tooling.test.js tests/audit-dashboard.test.js tests/ipv6-image-guard.test.js tests/wasm-host.test.js", + "test:unit": "node --test tests/unit.test.js tests/account-failover.test.js tests/no_tools_regression.test.js tests/parser_delimiter_repair.test.js tests/parser_recovery_boundary.test.js tests/parser_fullwidth_tool_call.test.js tests/parser_bare_call.test.js tests/parser_garbled_dsml.test.js tests/glyph-field.test.js tests/chrome-setup.test.js tests/updater.test.js tests/update-api.test.js tests/agents-api.test.js tests/audit-auth.test.js tests/audit-tooling.test.js tests/audit-dashboard.test.js tests/ipv6-image-guard.test.js tests/wasm-host.test.js", diff --git a/server.js b/server.js index 1057999..264deb6 100755 --- a/server.js +++ b/server.js @@ -2098,10 +2098,11 @@ function decodeDsmlValue(value) { .replace(/&/gi, '&'); } -function decodeDsmlParameterValue(value) { +function decodeDsmlParameterValue(value, keepEntities = false) { const raw = String(value || ''); const cdata = raw.trim().match(/^$/i); - return cdata ? cdata[1] : decodeDsmlValue(raw); + if (cdata) return cdata[1]; + return keepEntities ? raw : decodeDsmlValue(raw); } function getMarkupAttribute(attrs, attribute) { @@ -2183,12 +2184,12 @@ function scanDsmlStructuralTags(text) { return tags; } -function parseDsmlParameter(attrs, rawBody, args, seenNames) { +function parseDsmlParameter(attrs, rawBody, args, seenNames, keepEntities = false) { const parameterName = getMarkupAttribute(attrs, 'name'); if (!parameterName || !/^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/.test(parameterName) || seenNames.has(parameterName)) return false; seenNames.add(parameterName); const stringMode = getMarkupAttribute(attrs, 'string'); - const rawValue = decodeDsmlParameterValue(rawBody); + const rawValue = decodeDsmlParameterValue(rawBody, keepEntities); if (rawValue.length > MAX_TOOL_ARGUMENT_CHARS) return false; let value = rawValue; if (stringMode && stringMode.toLowerCase() === 'false') { @@ -2254,6 +2255,7 @@ function extractToolCallScope(normalized) { } // Narrow repair: tolerate a missing opening wrapper only when a closing // wrapper exists. A bare invoke without this sentinel is never executable. + // The one sentinel-free form is parseBareCallBlocks: a reply made only of blocks. if (closings.length > 0) { const closing = closings[closings.length - 1]; const invokeOpenings = tags.filter(tag => tag.name === 'invoke' && !tag.closing && tag.start < closing.start); @@ -2486,6 +2488,81 @@ function salvageGarbledDsmlCalls(text) { return calls.length === argCount ? calls : []; } +// DeepSeek Web sometimes replies with only .... +// Accepted trade-off: a reply made only of such blocks runs, even if the model was quoting one verbatim; +// the client whitelist still applies, and a quoted in prose never runs. +// Values arrive unescaped, so they are read by position and kept literal: a , closes a value only when follows it. +const BARE_CALL_OPEN_RE = /\s*[<<]call\s([^<><>]{0,1024})[>>]/y; +const BARE_CALL_CLOSE_RE = /\s*[<<]\/call\s*[>>]/y; +const BARE_CALL_END_RE = /[<<]\/call\s*[>>]/g; +const BARE_PARAM_OPEN_RE = /\s*[<<]parameter\s([^<><>]{0,1024})[>>]/y; +const BARE_PARAM_END_RE = /[<<]\/parameter\s*[>>]/g; +const BARE_PARAM_NEXT_RE = /\s*[<<](?:parameter\s|\/call\s*[>>])/y; +const BARE_CDATA_OPEN_RE = /\s* MAX_DSML_PARAMETERS) return null; + const bodyStart = markupMatchEnd(open); + let searchFrom = bodyStart; + const cdata = matchMarkupAt(BARE_CDATA_OPEN_RE, value, bodyStart); + if (cdata) { + const cdataEnd = value.indexOf(']]>', markupMatchEnd(cdata)); + if (cdataEnd === -1) return null; + searchFrom = cdataEnd + 3; + } + let close; + do { + close = matchMarkupAt(BARE_PARAM_END_RE, value, searchFrom); + if (!close) return null; + searchFrom = markupMatchEnd(close); + } while (!matchMarkupAt(BARE_PARAM_NEXT_RE, value, searchFrom)); + if (!parseDsmlParameter(open[1], value.substring(bodyStart, close.index), args, seenNames, true)) return null; + pos = searchFrom; + } + if (parameterCount > 0) { + const close = matchMarkupAt(BARE_CALL_CLOSE_RE, value, pos); + return close ? { args, end: markupMatchEnd(close) } : null; + } + + const close = matchMarkupAt(BARE_CALL_END_RE, value, start); + if (!close) return null; + const body = value.substring(start, close.index).trim(); + try { return { args: body ? JSON.parse(body) : {}, end: markupMatchEnd(close) }; } + catch (e) { return null; } +} + +function parseBareCallBlocks(text) { + const value = String(text || ''); + if (value.length > MAX_TOOL_MARKUP_CHARS) return []; + const calls = []; + let pos = 0; + for (let open; (open = matchMarkupAt(BARE_CALL_OPEN_RE, value, pos)) !== null;) { + const block = open[1].trimEnd().endsWith('/') + ? { args: {}, end: markupMatchEnd(open) } + : parseBareCallBody(value, markupMatchEnd(open)); + const call = block && buildToolCall(getMarkupAttribute(open[1], 'name'), block.args); + if (!call) return []; + calls.push(call); + pos = block.end; + } + return value.substring(pos).trim() ? [] : calls; +} + function collectAgentToolCalls(text, allowedToolNames) { const allowed = allowedToolNames instanceof Set ? allowedToolNames : new Set(allowedToolNames || []); if (!text || allowed.size === 0) return []; @@ -2499,6 +2576,9 @@ function collectAgentToolCalls(text, allowedToolNames) { } return calls; }; + // First, so a tool envelope or DSML tag inside a parameter value stays data. + const bareCalls = parseBareCallBlocks(text); + if (bareCalls.length > 0) return keepAllowed(bareCalls); const calls = keepAllowed(hasDsmlToolMarkup(text) ? listDsmlToolCalls(text) : collectJsonToolCalls(text)); if (calls.length > 0 || !hasDsmlToolMarkup(text)) return calls; const repaired = keepAllowed(listDsmlToolCalls(repairGarbledDsmlStructure(text))); @@ -2513,6 +2593,8 @@ function collectAgentToolCalls(text, allowedToolNames) { } function looksLikeToolCallMarkup(text) { + // Case-sensitive and tied to in a JSX or XML answer stays text. + if (/[<<]call\s[^<><>]{0,1024}[>>]\s*[<<]parameter\s/.test(String(text || ''))) return true; return /TOOL_CALL:\s*[\w-]+|<\s*[||]*\s*tool_call\b|[||]+\s*DSML\s*[||]+|[<<]\s*\/?\s*(?:DSML)?(?:[\w.-]+:)?(?:tool[\s_-]*calls|function[\s_-]*calls|invoke)\b|["'](?:tool_call|tool_calls|function_call)["']\s*:/i.test(String(text || '')); } @@ -5472,7 +5554,8 @@ async function handleRequest(req, res) { toolCall = null; } - const dsmlCalls = listDsmlToolCalls(fullContent); + const bareCalls = parseBareCallBlocks(fullContent); + const dsmlCalls = bareCalls.length > 0 ? bareCalls : listDsmlToolCalls(fullContent); const nativeOnlyDsml = dsmlCalls.length > 0 && dsmlCalls.every(call => isDeepSeekNativeTool(call.name)); const shouldRepairNative = !noToolsMode && !toolCall && (Boolean(ignoredNativeTool) || nativeOnlyDsml); const shouldRepairMarkup = !noToolsMode && !toolCall && !shouldRepairNative && looksLikeToolCallMarkup(fullContent); diff --git a/tests/parser_bare_call.test.js b/tests/parser_bare_call.test.js new file mode 100644 index 0000000..dd031ae --- /dev/null +++ b/tests/parser_bare_call.test.js @@ -0,0 +1,96 @@ +// Web DeepSeek can answer with only .... +// Before the fix this was neither parsed nor detected as tool markup, so the raw block +// was streamed to the client as the final answer. +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const S = require('../server.js').__test; +const TOOLS = new Set(['bash', 'read']); + +const SEEN = '\n\n\nsed -n \'215,270p;3110,3135p\' server.js\n' + + '20\n'; + +test('reply made only of a block is parsed', () => { + const calls = S.collectAgentToolCalls(SEEN, TOOLS); + assert.deepEqual(calls.map(c => c.name), ['bash']); + assert.deepEqual(JSON.parse(calls[0].arguments), { command: "sed -n '215,270p;3110,3135p' server.js", timeout: '20' }); +}); + +test('several blocks are parsed in order', () => { + const text = 'a.txt\n' + + 'echo ""'; + const calls = S.collectAgentToolCalls(text, TOOLS); + assert.deepEqual(calls.map(c => c.name), ['read', 'bash']); + assert.deepEqual(JSON.parse(calls[1].arguments), { command: 'echo ""' }); +}); + +test(' for a tool the client did not offer is dropped', () => { + assert.deepEqual(S.collectAgentToolCalls('/', TOOLS), []); +}); + +test(' quoted inside prose is not executed but is detected as markup', () => { + const text = 'The model printed ls as text.'; + assert.deepEqual(S.collectAgentToolCalls(text, TOOLS), []); + assert.equal(S.looksLikeToolCallMarkup(text), true); + assert.equal(S.looksLikeToolCallMarkup('I will call the bash tool next.'), false); +}); + +const bash = command => `${command}`; +const commandOf = text => { + const calls = S.collectAgentToolCalls(text, TOOLS); + assert.deepEqual(calls.map(c => c.name), ['bash']); + return JSON.parse(calls[0].arguments).command; +}; + +test('a tag named call in a code answer is not tool markup', () => { + assert.equal(S.looksLikeToolCallMarkup('Render here.'), false); + assert.equal(S.looksLikeToolCallMarkup('In XML: text'), false); +}); + +test('markup and entities inside a value stay literal', () => { + for (const command of [ + 'grep -n "' a.txt", + "grep '|DSML|' server.js", + 'grep -n "" server.js', + 'echo "" done', + "grep -c '<' page.html", + "sed 's/&/x/g' a && cat <"]]>')), 'echo ""'); +}); + +test('a tool envelope inside a value does not replace the outer call', () => { + for (const content of [ + '{"tool_call":{"name":"bash","arguments":{"command":"rm -rf build"}}}', + '{"name":"bash","arguments":{"command":"id"}}', + 'TOOL_CALL: bash {"command":"id"}', + ]) { + const text = `a${content}`; + const calls = S.collectAgentToolCalls(text, TOOLS); + assert.deepEqual(calls.map(c => c.name), ['read']); + assert.equal(JSON.parse(calls[0].arguments).content, content); + } + const dropped = '{"tool_call":{"name":"bash","arguments":{}}}'; + assert.deepEqual(S.collectAgentToolCalls(dropped, TOOLS), []); +}); + +test('other spellings of the tag are parsed', () => { + const tools = new Set(['bash', 'read', 'mcp:read']); + const names = text => S.collectAgentToolCalls(text, tools).map(c => c.name); + assert.deepEqual(names(`ls`), ['bash']); + assert.deepEqual(names('ls'), ['bash']); + assert.deepEqual(names('x'), ['mcp:read']); + assert.deepEqual(names(''), ['read']); + assert.deepEqual(names(''), ['read']); + assert.deepEqual(names('{"command":"ls"}'), ['bash']); + const fullwidth = '<call name="bash"><parameter name="command">ls</parameter></call>'; + assert.deepEqual(names(fullwidth), ['bash']); + assert.equal(S.looksLikeToolCallMarkup(`Sure: ${fullwidth}`), true); +}); + +test('unclosed tags are rejected quickly', () => { + const started = Date.now(); + assert.deepEqual(S.collectAgentToolCalls(''.repeat(17000), TOOLS), []); + assert.ok(Date.now() - started < 1000); +});