Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",



Expand Down
93 changes: 88 additions & 5 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(/^<!\[CDATA\[([\s\S]*?)\]\]>$/i);
return cdata ? cdata[1] : decodeDsmlValue(raw);
if (cdata) return cdata[1];
return keepEntities ? raw : decodeDsmlValue(raw);
}

function getMarkupAttribute(attrs, attribute) {
Expand Down Expand Up @@ -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') {
Expand Down Expand Up @@ -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 <call> 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);
Expand Down Expand Up @@ -2486,6 +2488,81 @@ function salvageGarbledDsmlCalls(text) {
return calls.length === argCount ? calls : [];
}

// DeepSeek Web sometimes replies with only <call name="bash"><parameter name="command">...</parameter></call>.
// 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 <call> quoted in prose never runs.
// Values arrive unescaped, so they are read by position and kept literal: a </call>, <invoke or &lt;
// inside a value is data. A </parameter> closes a value only when <parameter or </call> 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*<!\[CDATA\[/iy;

function matchMarkupAt(re, text, pos) {
re.lastIndex = pos;
return re.exec(text);
}

function markupMatchEnd(match) {
return match.index + match[0].length;
}

function parseBareCallBody(value, start) {
const args = Object.create(null);
const seenNames = new Set();
let parameterCount = 0;
let pos = start;
for (let open; (open = matchMarkupAt(BARE_PARAM_OPEN_RE, value, pos)) !== null;) {
if (++parameterCount > 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 [];
Expand All @@ -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)));
Expand All @@ -2513,6 +2593,8 @@ function collectAgentToolCalls(text, allowedToolNames) {
}

function looksLikeToolCallMarkup(text) {
// Case-sensitive and tied to <parameter, so <Call name="x" /> 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 || ''));
}

Expand Down Expand Up @@ -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);
Expand Down
96 changes: 96 additions & 0 deletions tests/parser_bare_call.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Web DeepSeek can answer with only <call name="..."><parameter ...>...</parameter></call>.
// 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<call name="bash">\n<parameter name="command">sed -n \'215,270p;3110,3135p\' server.js</parameter>\n'
+ '<parameter name="timeout">20</parameter>\n</call>';

test('reply made only of a <call> 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 <call> blocks are parsed in order', () => {
const text = '<call name="read"><parameter name="path">a.txt</parameter></call>\n'
+ '<call name="bash"><parameter name="command">echo "<call>"</parameter></call>';
const calls = S.collectAgentToolCalls(text, TOOLS);
assert.deepEqual(calls.map(c => c.name), ['read', 'bash']);
assert.deepEqual(JSON.parse(calls[1].arguments), { command: 'echo "<call>"' });
});

test('<call> for a tool the client did not offer is dropped', () => {
assert.deepEqual(S.collectAgentToolCalls('<call name="rm"><parameter name="path">/</parameter></call>', TOOLS), []);
});

test('<call> quoted inside prose is not executed but is detected as markup', () => {
const text = 'The model printed <call name="bash"><parameter name="command">ls</parameter></call> 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 => `<call name="bash"><parameter name="command">${command}</parameter></call>`;
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 <Call name="Bob" /> here.'), false);
assert.equal(S.looksLikeToolCallMarkup('In XML: <call name="x">text</call>'), false);
});

test('markup and entities inside a value stay literal', () => {
for (const command of [
'grep -n "<invoke" server.js',
"grep -c '<tool_calls>' a.txt",
"grep '|DSML|' server.js",
'grep -n "</call>" server.js',
'echo "</parameter>" done',
"grep -c '&lt;' page.html",
"sed 's/&amp;/x/g' a && cat <<EOF",
]) assert.equal(commandOf(bash(command)), command);
assert.equal(commandOf(bash('<![CDATA[echo "</call></parameter>"]]>')), 'echo "</call></parameter>"');
});

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"}}}',
'<tool_call>{"name":"bash","arguments":{"command":"id"}}</tool_call>',
'TOOL_CALL: bash {"command":"id"}',
]) {
const text = `<call name="read"><parameter name="path">a</parameter><parameter name="content">${content}</parameter></call>`;
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 = '<call name="rm"><parameter name="x">{"tool_call":{"name":"bash","arguments":{}}}</parameter></call>';
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(`<call name='bash'><parameter name="command">ls</parameter></call>`), ['bash']);
assert.deepEqual(names('<call name="bash" id="1"><parameter name="command">ls</parameter></call>'), ['bash']);
assert.deepEqual(names('<call name="mcp:read"><parameter name="p">x</parameter></call>'), ['mcp:read']);
assert.deepEqual(names('<call name="read"/>'), ['read']);
assert.deepEqual(names('<call name="read"></call>'), ['read']);
assert.deepEqual(names('<call name="bash">{"command":"ls"}</call>'), ['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 <call> tags are rejected quickly', () => {
const started = Date.now();
assert.deepEqual(S.collectAgentToolCalls('<call name="a">'.repeat(17000), TOOLS), []);
assert.ok(Date.now() - started < 1000);
});
Loading