diff --git a/Dockerfile b/Dockerfile index f6560ee1..82f096cf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -56,7 +56,8 @@ RUN set -e; \ ver="${ENGINE_VERSION:-$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1)}"; \ cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1); cudamajor=${cudafull%%.*}; \ if [ "$cudamajor" = 13 ]; then mindriver=580.65; else mindriver=575.51; fi; \ - echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true}" > /stage/BUILD.json; \ + vision_archs=""; [ -f /stage/strata-vision ] && vision_archs=", \"vision_archs\": \"$CUDA_ARCHITECTURES\""; \ + echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true${vision_archs}}" > /stage/BUILD.json; \ python3 packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out /stage --also 'libcublasLt.so*'; \ archs=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do archs="$archs --arch sm_$a"; done; \ last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index 5ba21961..db9c1990 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -111,11 +111,12 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve * @param {string|null} [options.componentsDir] where installed components live * @param {() => Array} options.localInstances ready local instances (see profile.mjs) * @param {() => Array} options.connections saved API connections WITH their keys (host-internal) + * @param {() => (string|null)} [options.defaultLocalId] the local instance the chat runs on: its tool servers are the agent's (T5) * @param {NodeJS.ProcessEnv} [options.env] * @param {string} [options.nodePath] the Node runtime that runs the Harness * @param {(line:string)=>void} [options.log] */ -export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) { +export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, defaultLocalId = () => null, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) { const root = join(dataDir, 'agent'); const home = join(root, 'home'); const sessionsFile = join(root, 'sessions.json'); @@ -171,7 +172,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ let shapeTargets = {}; function buildProfileNow() { - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock }); + const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock, defaultLocalId: defaultLocalId() }); shapeTargets = profile.shapeTargets ?? {}; return profile; } @@ -193,6 +194,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = harness: { version: h.version }, runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null, routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })), + // tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so + skippedServers: profile.mcpSkipped ?? [], activeTurns: activeTurns(), pendingApprovals: pending.size, }; diff --git a/apps/host/server/agent/custom-command-run.mjs b/apps/host/server/agent/custom-command-run.mjs new file mode 100644 index 00000000..5543b38f --- /dev/null +++ b/apps/host/server/agent/custom-command-run.mjs @@ -0,0 +1,103 @@ +/** + * Runs the command of a command tool the person wrote (Settings -> Tools). Split from custom-tools-mcp.mjs so it can be tested. + * + * T7 (tools and images review, 2026-10-22). It used to run every command with `shell: true` (cmd.exe on Windows, so `Get-Content x` failed with + * "not recognized"), in whatever folder the host happened to run in (so `python tools/foo.py` could not find its file), and ended it after two + * minutes with 20,000 characters of output, silently cut. + * + * shell 'auto' (default): PowerShell for a Windows command that reads as PowerShell (Get-Content, Start-Process, $env:X, $(...)), cmd.exe for + * any other Windows command (so every command that worked keeps working), /bin/sh elsewhere. 'cmd', 'powershell', 'bash' and 'sh' name one. + * cwd the folder to run in: the tool's own, or the one the assistant names in the call (it knows the chat's folder); else the person's home. + * timeoutSec the time allowed, 1 to 3600 (default 120). A command that runs over is ended together with the programs it started. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, statSync } from 'node:fs'; +import { homedir } from 'node:os'; + +export const DEFAULT_TIMEOUT_SEC = 120; +export const MAX_TIMEOUT_SEC = 3600; +export const OUT_MAX = 20000; +export const SHELLS = ['auto', 'cmd', 'powershell', 'bash', 'sh']; + +/** A Windows command that is PowerShell and would fail in cmd.exe. */ +const POWERSHELL_LOOKS = /(^|[\s;|(&])[A-Z][A-Za-z]+-[A-Z][A-Za-z]+\b|\$\w|\$\(|\$env:|@\(|\|\s*(?:%|\?)\s*\{/; +export const looksLikePowerShell = command => POWERSHELL_LOOKS.test(String(command ?? '')); + +let powershellFound; +/** pwsh when it is installed (PowerShell 7), else the Windows PowerShell every Windows has. */ +function powershellExe(platform) { + if (powershellFound) return powershellFound; + if (platform !== 'win32') return (powershellFound = 'pwsh'); + try { if (spawnSync('where', ['pwsh'], { windowsHide: true, timeout: 5000 }).status === 0) return (powershellFound = 'pwsh'); } catch { /* none */ } + return (powershellFound = 'powershell.exe'); +} + +/** + * -> { file, args, shell } for spawn: which program runs `command`. + * @param {string} command + * @param {{shell?: string, platform?: string}} [options] + */ +export function planShell(command, { shell = 'auto', platform = process.platform } = {}) { + const windows = platform === 'win32'; + let choice = SHELLS.includes(shell) ? shell : 'auto'; + if (choice === 'auto') choice = windows ? (looksLikePowerShell(command) ? 'powershell' : 'cmd') : 'sh'; + if (choice === 'powershell') return { file: powershellExe(platform), args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], shell: false, name: 'PowerShell' }; + if (choice === 'bash') return { file: 'bash', args: ['-c', command], shell: false, name: 'bash' }; + if (choice === 'sh') return windows ? { file: 'sh', args: ['-c', command], shell: false, name: 'sh' } : { file: command, args: [], shell: true, name: 'sh' }; + return { file: command, args: [], shell: true, name: windows ? 'cmd.exe' : 'sh' }; // cmd: spawn's shell:true is cmd.exe on Windows +} + +/** The folder a command runs in: -> { cwd } or { error } with a plain sentence. */ +export function resolveCwd(...candidates) { + for (const candidate of candidates) { + const text = typeof candidate === 'string' ? candidate.trim() : ''; + if (!text) continue; + const expanded = text.replace(/^~(?=$|[\\/])/, homedir()); + try { + if (!existsSync(expanded) || !statSync(expanded).isDirectory()) return { error: `The folder “${text}” does not exist, so the command was not run.` }; + } catch { return { error: `The folder “${text}” could not be opened, so the command was not run.` }; } + return { cwd: expanded }; + } + return { cwd: homedir() }; +} + +export const clampTimeoutSec = value => { + const n = Number(value); + return Number.isFinite(n) && n >= 1 ? Math.min(Math.floor(n), MAX_TIMEOUT_SEC) : DEFAULT_TIMEOUT_SEC; +}; + +function endTree(child) { + try { + if (process.platform === 'win32' && child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 10000 }); + else child.kill('SIGKILL'); + } catch { /* gone */ } +} + +/** + * @param {{command: string, input?: string, cwd?: string, callCwd?: string, shell?: string, timeoutSec?: number, platform?: string}} job + * @returns {Promise<{ok: boolean, text: string}>} + */ +export function runCommand({ command, input = '', cwd, callCwd, shell = 'auto', timeoutSec, platform = process.platform }) { + return new Promise(resolve => { + const where = resolveCwd(callCwd, cwd); + if (where.error) return resolve({ ok: false, text: where.error }); + const plan = planShell(command, { shell, platform }); + const limit = clampTimeoutSec(timeoutSec); + let child; + try { + child = spawn(plan.file, plan.args, { shell: plan.shell, windowsHide: true, cwd: where.cwd, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (e) { return resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); } + let text = '', cut = false, timedOut = false; + const take = chunk => { if (text.length < OUT_MAX + 1) text += chunk.toString(); else cut = true; }; + child.stdout.on('data', take); child.stderr.on('data', take); + const timer = setTimeout(() => { timedOut = true; endTree(child); }, limit * 1000); + child.on('error', e => { clearTimeout(timer); resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); }); + child.on('close', code => { + clearTimeout(timer); + if (text.length > OUT_MAX) { cut = true; text = text.slice(0, OUT_MAX); } + const out = text.trim() + (cut ? `\n\n(The output was cut after ${OUT_MAX.toLocaleString('en-US')} characters.)` : ''); + if (timedOut) return resolve({ ok: false, text: `The command was stopped after ${limit} seconds.${out ? '\n' + out : ''}` }); + resolve({ ok: code === 0, text: out || (code === 0 ? 'The command finished without any error. It printed nothing.' : `The command failed (exit code ${code}) and printed nothing.`) }); + }); + }); +} diff --git a/apps/host/server/agent/custom-tools-mcp.mjs b/apps/host/server/agent/custom-tools-mcp.mjs index 93cb40f6..99a97f3d 100644 --- a/apps/host/server/agent/custom-tools-mcp.mjs +++ b/apps/host/server/agent/custom-tools-mcp.mjs @@ -8,49 +8,35 @@ * It speaks the Model Context Protocol over stdio (newline-delimited JSON-RPC), the transport the Harness's MCP client uses for a program * it starts. The file is re-read on every request, so a change in Settings is seen without restarting anything. The assistant's text for * a command tool reaches the command in the STRATA_INPUT environment variable (never spliced into the command line, so it cannot add - * commands of its own). A command gets 2 minutes and 20,000 characters of output. + * commands of its own). A command runs in the shell that suits it (PowerShell for a Windows command that reads as PowerShell, cmd.exe for + * the rest, sh elsewhere), in its own folder or the one the assistant names, gets 2 minutes unless its tool allows more (up to an hour) and + * 20,000 characters of output (custom-command-run.mjs). */ -import { spawn } from 'node:child_process'; import { readFileSync } from 'node:fs'; import { createInterface } from 'node:readline'; +import { runCommand } from './custom-command-run.mjs'; const [mode, file] = process.argv.slice(2); if (!['instructions', 'commands'].includes(mode) || !file) { console.error('usage: custom-tools-mcp.mjs instructions|commands '); process.exit(2); } const load = () => { try { return JSON.parse(readFileSync(file, 'utf8'))[mode] ?? {}; } catch { return {}; } }; -const OUT_MAX = 20000; -const TIME_MS = 120000; const schema = mode === 'commands' - ? { type: 'object', properties: { input: { type: 'string', description: 'Text to give the command (optional).' } }, additionalProperties: false } + ? { type: 'object', properties: { + input: { type: 'string', description: 'Text to give the command (optional).' }, + cwd: { type: 'string', description: 'The folder to run the command in (optional). Give the working folder of this chat when the command uses relative paths.' }, + }, additionalProperties: false } : { type: 'object', properties: {}, additionalProperties: false }; function listTools() { return Object.entries(load()).map(([name, t]) => ({ name, description: String(t.description ?? ''), inputSchema: schema, annotations: mode === 'instructions' ? { readOnlyHint: true } : {} })); } -function runCommand(command, input) { - return new Promise(resolve => { - const child = spawn(command, { shell: true, windowsHide: true, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] }); - let text = ''; - const take = chunk => { if (text.length < OUT_MAX) text += chunk.toString(); }; - child.stdout.on('data', take); child.stderr.on('data', take); - const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, TIME_MS); - child.on('error', e => { clearTimeout(timer); resolve({ ok: false, text: `The command could not start: ${e.message}` }); }); - child.on('close', (code, signal) => { - clearTimeout(timer); - const out = text.slice(0, OUT_MAX).trim(); - if (signal) resolve({ ok: false, text: `The command was stopped after ${TIME_MS / 1000} seconds.${out ? '\n' + out : ''}` }); - else resolve({ ok: code === 0, text: out || (code === 0 ? 'The command finished without any error. It printed nothing.' : `The command failed (exit code ${code}) and printed nothing.`) }); - }); - }); -} - async function call(name, args) { const t = load()[name]; if (!t) return { isError: true, content: [{ type: 'text', text: 'That tool is no longer available.' }] }; if (mode === 'instructions') return { content: [{ type: 'text', text: String(t.text ?? '') }] }; - const r = await runCommand(String(t.command ?? ''), args?.input); + const r = await runCommand({ command: String(t.command ?? ''), input: args?.input, callCwd: args?.cwd, cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec }); return { isError: !r.ok, content: [{ type: 'text', text: r.text }] }; } diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs index a8b82de8..67908509 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -157,6 +157,9 @@ export function withPlain(raw) { return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw; } +/** What a launch that printed nothing proves, and no more. */ +export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.'; + /** A command whose whole point is to open something: it has no output to show when it worked. */ const LAUNCH = /(^|[\s;|&(])(start-process|start|invoke-item|ii|explorer(?:\.exe)?|xdg-open|open|notepad(?:\.exe)?|code)(?=[\s;|&)]|$)/i; @@ -172,9 +175,10 @@ export function outcomeText(tool, text, args = {}) { text = text.replace(/\r?\n?\[stderr\]\r?\n(?:Cannot create type\. Only core types are supported in this language mode\.[\s\S]*?CannotCreateTypeConstrainedLanguage\s*)+$/, ''); if (!text.trim()) text = '(no output)'; } - // Starting a program or opening a folder prints nothing when it worked. The model used to read "finished, nothing to show" as "cannot tell - // whether it opened" and told the person so; a launch that returned without an error did start, and the result says that plainly. - if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return 'Started. The program, folder or file was opened.'; + // Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a + // program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to + // confirm it renders"). It says what is known: the command returned without an error. + if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return LAUNCHED_TEXT; if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.'; return text; } diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjs index 68ac9312..9ec6e3dd 100644 --- a/apps/host/server/agent/plan.mjs +++ b/apps/host/server/agent/plan.mjs @@ -117,7 +117,7 @@ export function stepObjective(plan, index) { `You are on step ${index + 1} of ${n}: ${s.text}${s.detail ? ` (${s.detail})` : ''}.`, done ? `Already done: ${done}.` : '', plan.briefing ? String(plan.briefing) : '', - isViewStep(s.text) ? 'This step is about seeing the result in a browser. Never wait for a program to close. If a person is at this computer, start the browser so the command returns at once (Windows: Start-Process; macOS: open; Linux: xdg-open) and say it is open. If there is no screen, check the page without a visible window: use the headless browser tool if you have one, otherwise read the file and its script for mistakes, and say in one plain sentence what you could and could not check. Then finish the step.' : '', + isViewStep(s.text) ? 'This step is about seeing the result. To show a local image, SVG, HTML page or PDF, use the present tool (a browser cannot open file:// addresses). Never wait for a program to close. If a person is at this computer and you start a browser, start it so the command returns at once (Windows: Start-Process; macOS: open; Linux: xdg-open) and say only that you started it, not that the page rendered. If there is no screen, check the page without a visible window: use the headless browser tool if you have one, otherwise read the file and its script for mistakes, and say in one plain sentence what you could and could not check. Then finish the step.' : '', 'Do only this step, check that it worked, and then finish the goal.', index + 1 < n ? 'The next steps are handled separately: do not start them.' : '', ].filter(Boolean).join(' '); diff --git a/apps/host/server/agent/plugins/strata-gate.mjs b/apps/host/server/agent/plugins/strata-gate.mjs index d25d76c0..dfc75bc9 100644 --- a/apps/host/server/agent/plugins/strata-gate.mjs +++ b/apps/host/server/agent/plugins/strata-gate.mjs @@ -219,8 +219,13 @@ export function apply(ctx, config = {}) { ctx.on('tools/pre-execute', async (exec, next) => { const agent = exec.agent; if (!agent || exec.name === 'run_code') return next(); + // Fail closed (T4): a session whose preset cannot be read (a reset in progress, a helper whose chat is gone) is treated as Manual, so + // anything this file cannot prove is read-only still asks. It used to run unasked. let preset; - try { preset = effectivePreset(agent.session); } catch { return next(); } + try { preset = effectivePreset(agent.session); } catch (e) { + preset = MANUAL_PRESET; + try { console.warn(`[strata-gate] could not read the permission mode for this call (${e?.message ?? e}); treating it as Manual`); } catch { /* logging must never decide a permission */ } + } // A helper that was set to ask while the chat was in Manual must stop asking the moment the chat leaves Manual, // so a mode change applies to the very next tool call of a running goal and its helpers. if (preset !== MANUAL_PRESET && agent.session.header?.origin === 'subagent' && ctx.approval.overrideOf(agent.session) === 'ask') { diff --git a/apps/host/server/agent/preset.mjs b/apps/host/server/agent/preset.mjs index 6088b4f9..5927959a 100644 --- a/apps/host/server/agent/preset.mjs +++ b/apps/host/server/agent/preset.mjs @@ -42,8 +42,8 @@ export const AGENT_PROMPT = [ 'You are a helpful assistant that can also work on this computer through your tools. You are running as {{model}}.', 'Answer questions directly and briefly; use a tool only when the task needs one. The person reads your replies in a chat: use plain words, not tool names or technical jargon.', 'Look before you change: read a file before you edit or overwrite it, and prefer a small edit to a rewrite. Search with the glob and grep tools and read files with the read tool; use the shell for running programs.', - 'When you start a program or open a folder or file for the person, the command returning without an error means it worked: say plainly that it is open. Do not say you could not confirm it. If a command fails, say what went wrong in one sentence and what you will try next.', - 'To open a page or a file for the person (a browser, an app, a folder), start it so the command returns at once and never wait for the program to close: on Windows use Start-Process, on macOS open, on Linux xdg-open. Then say plainly that it is open.', + 'A command that starts a program, folder or page only tells you that it started. Never say a window opened, a page rendered or that you checked how it looks unless a tool confirmed it. If a command fails, say what went wrong in one sentence and what you will try next.', + 'To show the person an image, SVG, HTML page or PDF from their folders, use the present tool: the app shows it next to the chat. A browser cannot open file:// addresses. If you do start a program, start it so the command returns at once and never wait for it to close: Start-Process on Windows, open on macOS, xdg-open on Linux.', 'When the person asks you to ask a subagent, a helper or another model ("ask a subagent", "ask model X"), use the subagent tool and name the model in its model field. Never look for a model with shell commands, and never wait for a helper with sleep: end your turn; its answer arrives as a new message.', 'Tokens prefixed with @ are files or folders the person pointed at. A failed or refused action changed nothing; say so, and do not claim work you did not do.', ].join('\n\n'); diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index 2637b87f..4b68eb8f 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -20,6 +20,7 @@ import { createHash } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { standardPreset } from './preset.mjs'; +import { validMcpName } from '../mcp-names.mjs'; import { BUDGETS, isPrivateHost } from './llm-shape.mjs'; import { DDG_PROVIDER_ID } from '../web-search-ddg.mjs'; @@ -71,11 +72,17 @@ const NO_TOOLS_SETTINGS = Object.freeze({ off: new Set(), search: { provider: 'b * `mcp____`. A command or URL goes into the patch as text; a secret (an env value or a header) never does: the row * carries `!!js process.env.` and the value travels in the agent process's environment (returned in `env`). */ -export function mcpRows(servers, env) { +export function mcpRows(servers, env, skipped = []) { const rows = []; + const ids = new Set(); let index = 0; for (const [name, server] of Object.entries(servers ?? {})) { - if (!server || server.disabled === true || !/^[A-Za-z0-9_-]{1,32}$/.test(name)) continue; + if (!server || server.disabled === true) continue; // switched off on purpose: not an error + // A server that cannot be wired is REPORTED (T6): the model never sees its tools, and a silent drop looked like "the tool does not work". + if (!validMcpName(name)) { skipped.push({ name, why: 'name' }); continue; } + if (!server.command && !server.url) { skipped.push({ name, why: 'address' }); continue; } + if (ids.has(`mcp-${slug(name)}`)) { skipped.push({ name, why: 'duplicate' }); continue; } + ids.add(`mcp-${slug(name)}`); const token = (kind, key, value) => { const variable = `STRATA_MCP_${index}_${kind}_${slug(key).replace(/-/g, '_').toUpperCase()}`; env[variable] = String(value); @@ -91,6 +98,24 @@ export function mcpRows(servers, env) { return rows; } +/** + * What the chat says when a tool server was left out (one notice per reason). The sentences are interface copy: they are in every language's + * catalog (src/locales/tools-.json), and the {0} is the list of names exactly as the person wrote them. + */ +const SKIPPED_TEXT = { + name: 'These tool servers were left out because their names are not allowed: {0}. A name can have up to 32 letters, numbers, hyphens or underscores.', + address: 'These tool servers were left out because they have no program or web address: {0}.', + duplicate: 'These tool servers were left out because another one has almost the same name: {0}.', +}; +export function mcpSkippedNotices(skipped) { + const out = []; + for (const why of Object.keys(SKIPPED_TEXT)) { + const names = (skipped ?? []).filter(s => s.why === why).map(s => String(s.name).slice(0, 40)); + if (names.length) out.push({ code: `mcp-skipped-${why}-${names.join(',')}`.slice(0, 160), message: SKIPPED_TEXT[why].replace('{0}', names.join(', ')) }); + } + return out; +} + const slug = value => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'x'; /** Identity of one route's wire configuration, secret included by hash only. */ @@ -166,7 +191,7 @@ export function outputBudget(context, maxOutput = null) { /** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */ const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } }; -export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null }) { +export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null, defaultLocalId = null }) { const providers = {}; const env = {}; const routes = []; @@ -257,9 +282,13 @@ export function buildProfile({ local = [], connections = [], gate = true, tools for (const m of conn.models) routes.push({ route, fp, kind: 'api', connectionId: conn.id, connectionName: conn.name, modelId: m.id, name: m.name || m.id, contextWindow: m.contextMax ?? ASSUMED_API_CONTEXT, ...(shaped ? { shaped } : {}) }); }); - const defaultRoute = routes.find(r => r.kind === 'local') ?? null; + // The model the chat really runs on is the default instance, not whichever one was loaded first (T5: with two models loaded, the tool servers of the + // first one were wired to a chat on the second). + const defaultInstance = local.find(i => i.id === defaultLocalId) ?? local[0] ?? null; + const defaultRoute = routes.find(r => r.kind === 'local' && r.instanceId === defaultInstance?.id) ?? routes.find(r => r.kind === 'local') ?? null; // One Harness, one set of tool servers: the default local model's. - const mcp = mcpRows({ ...(local[0]?.mcpServers ?? {}), ...(tools.servers ?? {}) }, mcpEnv); + const mcpSkipped = []; + const mcp = mcpRows({ ...(defaultInstance?.mcpServers ?? {}), ...(tools.servers ?? {}) }, mcpEnv, mcpSkipped); Object.assign(env, mcpEnv); // The person's own instruction and command tools come from the app's tool server; a command tool asks in Manual like any connected tool. const own = (kind, on) => on && tools.toolFile ? [{ id: `mcp-strata-${kind}`, name: '@deepseek-ai/dsh-mcp-client', config: { serverName: `strata-${kind}`, transport: 'stdio', command: process.execPath, args: [CUSTOM_TOOLS_SCRIPT, kind, tools.toolFile] } }] : []; @@ -309,7 +338,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools // What the agent is offered (tool groups, web search, tool servers, the person's own tools) decides whether a running agent must be // restarted for the next message; the routes are compared separately (a changed context size alone does not restart it). const toolsSignature = createHash('sha256').update(JSON.stringify([mcp, ownRows, webRows, entries.find(e => e.id === 'preset-standard'), env.STRATA_SEARCH_KEY ?? '', mcpEnv])).digest('hex').slice(0, 16); - return { patch, env, routes, defaultRoute, signature, toolsSignature, shapeTargets }; + return { patch, env, routes, defaultRoute, signature, toolsSignature, shapeTargets, mcpSkipped }; } /** Find the route for a chat's model choice. */ diff --git a/apps/host/server/agent/tools-settings.mjs b/apps/host/server/agent/tools-settings.mjs index 4a919e30..0adba80c 100644 --- a/apps/host/server/agent/tools-settings.mjs +++ b/apps/host/server/agent/tools-settings.mjs @@ -13,6 +13,7 @@ import { mkdirSync, renameSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { GROUP_IDS, TOOL_GROUPS } from './tools-catalog.mjs'; +import { SHELLS, clampTimeoutSec } from './custom-command-run.mjs'; export const SEARCH_PROVIDERS = ['builtin', 'exa', 'perplexity', 'deepseek']; const KINDS = ['instructions', 'command', 'server']; @@ -38,6 +39,8 @@ function normalize(raw) { id: String(t.id), name: String(t.name), about: clean(t.about, 300), kind: t.kind, enabled: t.enabled !== false, instructions: clean(t.instructions, 20000), command: clean(t.command, 2000), address: clean(t.address, 2000), args: (Array.isArray(t.args) ? t.args : []).slice(0, 50).map(a => clean(a, 1000)), + // a command tool's folder, shell and time allowed (custom-command-run.mjs); '' / 'auto' / 120 when not set + cwd: clean(t.cwd, 1000).trim(), shell: SHELLS.includes(t.shell) ? t.shell : 'auto', timeoutSec: clampTimeoutSec(t.timeoutSec), })), }; } @@ -49,7 +52,7 @@ function validateCustom(body, existing) { if (!about) throw new Error('Say what the tool does, in a sentence. The assistant reads this to decide when to use it.'); const kind = body?.kind; if (!KINDS.includes(kind)) throw new Error('Choose how the tool works.'); - const out = { name, about, kind, instructions: '', command: '', address: '', args: [] }; + const out = { name, about, kind, instructions: '', command: '', address: '', args: [], cwd: '', shell: 'auto', timeoutSec: clampTimeoutSec(undefined) }; if (kind === 'instructions') { out.instructions = clean(body.instructions, 20000).trim(); if (!out.instructions) throw new Error('Write the instructions the assistant should follow when it uses this tool.'); @@ -57,6 +60,14 @@ function validateCustom(body, existing) { out.command = clean(body.command, 2000).trim(); if (!out.command) throw new Error('Enter the command to run.'); if (/[\r\n]/.test(out.command)) throw new Error('Put the command on one line.'); + // The edit form of Settings does not send these three: an edit keeps what the tool had. + const before = existing.find(t => t.id === body.id && t.kind === 'command'); + out.cwd = body.cwd !== undefined ? clean(body.cwd, 1000).trim() : before?.cwd ?? ''; + if (/[\r\n]/.test(out.cwd)) throw new Error('Put the folder on one line.'); + if (body.shell !== undefined && !SHELLS.includes(body.shell)) throw new Error('Choose how the command runs: automatic, cmd, PowerShell, bash or sh.'); + out.shell = body.shell !== undefined ? body.shell : before?.shell ?? 'auto'; + if (body.timeoutSec !== undefined && !(Number(body.timeoutSec) >= 1 && Number(body.timeoutSec) <= 3600)) throw new Error('Give the time allowed in seconds, from 1 to 3600.'); + out.timeoutSec = body.timeoutSec !== undefined ? clampTimeoutSec(body.timeoutSec) : before?.timeoutSec ?? clampTimeoutSec(undefined); } else { out.address = clean(body.address, 2000).trim(); if (!out.address) throw new Error('Enter the tool server’s web address, or the program that starts it.'); @@ -91,7 +102,7 @@ export function createAgentTools({ read, write, dataDir, browser = () => ({ foun for (const t of s.custom.filter(t => t.enabled)) { const key = t.id; if (t.kind === 'instructions') instructions[key] = { description: t.about, text: t.instructions }; - else if (t.kind === 'command') commands[key] = { description: t.about, command: t.command }; + else if (t.kind === 'command') commands[key] = { description: t.about, command: t.command, cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec }; } mkdirSync(join(dataDir, 'agent'), { recursive: true }); const tmp = `${filePath}.tmp`; @@ -115,6 +126,7 @@ export function createAgentTools({ read, write, dataDir, browser = () => ({ foun id: t.id, name: t.name, about: t.about, kind: t.kind, enabled: t.enabled, summary: t.kind === 'instructions' ? t.instructions.slice(0, 80) : t.kind === 'command' ? t.command : t.address, instructions: t.instructions, command: t.command, address: t.address, args: t.args, + ...(t.kind === 'command' ? { cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec } : {}), })), }; } diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index f8d638ad..68d69b60 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -15,6 +15,7 @@ import { materializeSkills, parseSkillFile, skillSlug, writeCreatedSkill } from import { systemFonts } from './fonts.mjs'; import { tuningDir } from './platform-paths.mjs'; import { createAgentBridge, plainTurnFailure } from './agent/agent-bridge.mjs'; +import { mcpSkippedNotices } from './agent/profile.mjs'; import { createAgentTools } from './agent/tools-settings.mjs'; import { withPlainStatus } from './agent/status.mjs'; import { findBrowser, findPlaywrightMcp } from './agent/browser-probe.mjs'; @@ -180,6 +181,7 @@ const agent = createAgentBridge({ componentsDir: componentsDirectory(), // The installer ships the Harness next to the host (/host/server -> /harness). bundledDir: resolve(HERE, '..', '..', 'harness'), + defaultLocalId: () => native.defaultInstanceId(), localInstances: () => native.readyInstances().map(i => ({ id: i.id, label: i.label, baseUrl: `http://127.0.0.1:${i.port}/v1`, modelId: i.apiModelId, context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision, @@ -1934,6 +1936,8 @@ async function api(req, res, path, method, url) { if (chatId && !agentSkip) { const capability = agent.status(); if (capability.state !== 'unavailable') { + const skipped = mcpSkippedNotices(capability.skippedServers); + for (const notice of skipped) res.write(`${JSON.stringify({ type: 'notice', ...notice })}\n`); await runAgentTurn({ res, controller, chatId, body, message, workspaceId, images }); res.end(); return undefined; diff --git a/apps/host/server/mcp-names.mjs b/apps/host/server/mcp-names.mjs new file mode 100644 index 00000000..a4776f52 --- /dev/null +++ b/apps/host/server/mcp-names.mjs @@ -0,0 +1,10 @@ +// The one rule for the name of a tool server (MCP), shared by the Settings editor (src/lib/mcp-names.ts keeps a copy; tests/mcp-rows.test.mjs +// checks they agree), the save check (native-settings.mjs) and the agent profile (agent/profile.mjs). +// +// The model sees every tool as `mcp____`, and an OpenAI-style API takes at most 64 characters for that name, so the server's +// part is limited to 32 (T6, tools and images review 2026-10-22). Before, the editor and the save check accepted 64 and the profile quietly +// dropped everything over 32 (or with a dot): the model never saw the tool and nothing said why. +export const MCP_NAME_MAX = 32; +export const MCP_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/; +export const validMcpName = name => typeof name === 'string' && MCP_NAME_RE.test(name); +export const MCP_NAME_HELP = 'Use a simple server name of up to 32 characters: letters, numbers, hyphens or underscores.'; diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 0dab2c8d..a4380e79 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -482,5 +482,5 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;}; async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} - return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,interruptedMove,finishInterruptedMove,leaveInterruptedMove,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; + return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,interruptedMove,finishInterruptedMove,leaveInterruptedMove,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),defaultInstanceId:()=>defaultId,close}; } diff --git a/apps/host/server/native-settings.mjs b/apps/host/server/native-settings.mjs index eebab7f9..f8b248da 100644 --- a/apps/host/server/native-settings.mjs +++ b/apps/host/server/native-settings.mjs @@ -1,3 +1,4 @@ +import { validMcpName, MCP_NAME_HELP } from './mcp-names.mjs'; /** Editable native keys. Unknown config keys and program paths stay intact. */ export const NATIVE_FIELDS=[ {id:'reasoning_budget_tokens',label:'Thinking token budget',group:'Responses',type:'number',min:0,max:1048576,hint:'Leave blank for the model default.'}, @@ -56,7 +57,9 @@ export function publicMcpServers(servers){return Object.fromEntries(Object.entri export function validateMcpServers(servers,previous={}){ if(!servers||typeof servers!=='object'||Array.isArray(servers)||Object.keys(servers).length>30)throw new Error('MCP servers must be an object with at most 30 entries.'); const out={};for(const [name,s] of Object.entries(servers)){ - if(!/^[a-z0-9_-]{1,64}$/i.test(name)||!s||typeof s!=='object'||Array.isArray(s))throw new Error('Give each tool server a simple, unique name.'); + if(!s||typeof s!=='object'||Array.isArray(s))throw new Error('Give each tool server a simple, unique name.'); + // a name that was saved before the 32-character rule stays saveable (unrelated settings must not be blocked); the agent reports it as left out + if(!validMcpName(name)&&!Object.hasOwn(previous??{},name))throw new Error(MCP_NAME_HELP); if(!!s.command===!!s.url)throw new Error(`${name}: choose a command or HTTP URL.`); for(const key of Object.keys(s))if(!['command','args','env','cwd','url','headers','disabled'].includes(key))throw new Error(`${name}: unsupported property ${key}.`); if(s.command&&(typeof s.command!=='string'||s.command.length>1000||/[\n\r\0]/.test(s.command)))throw new Error(`${name}: choose a valid program.`); diff --git a/apps/host/src/components/Markdown.tsx b/apps/host/src/components/Markdown.tsx index 87e6c327..996b191f 100644 --- a/apps/host/src/components/Markdown.tsx +++ b/apps/host/src/components/Markdown.tsx @@ -5,8 +5,21 @@ import { Btn, IconBtn } from './ui'; import { SyntaxCode } from './SyntaxCode'; import { MathView } from './MathView'; import { displayBlock, hasMath, splitMath } from '../lib/math'; -function inlineMarks(text: string, onOpenLink?: (url: string) => void): ReactNode { - return text.split(/(`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => { +import { imagePlan } from '../lib/markdown-images'; +function inlineMarks(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode { + return text.split(/(!\[[^\]]*\]\([^\s)]+\)|`[^`]+`|\*\*[^*]+\*\*|\*[^*\n]+\*|\[[^\]]+\]\([^\s)]+\))/g).map((part, i) => { + const image = part.match(/^!\[([^\]]*)\]\(([^\s)]+)\)$/); + if (image) { + const plan = imagePlan(image[2], imageSession); + if (plan.kind === 'img') + return {image[1]}; + if (plan.kind === 'link') + return { if (onOpenLink) { + e.preventDefault(); + onOpenLink(plan.href); + } }}>{image[1] || plan.href}; + return {image[1] || part}; + } if (part.startsWith('`') && part.endsWith('`')) return {part.slice(1, -1)}; if (part.startsWith('**') && part.endsWith('**')) @@ -23,21 +36,23 @@ function inlineMarks(text: string, onOpenLink?: (url: string) => void): ReactNod }); } /** Text with its inline marks and, outside code spans, its math (#3268). Math is cut out first: a * or _ inside a formula is not emphasis. */ -function inline(text: string, onOpenLink?: (url: string) => void): ReactNode { +function inline(text: string, onOpenLink?: (url: string) => void, imageSession?: string | null): ReactNode { if (!hasMath(text)) - return inlineMarks(text, onOpenLink); + return inlineMarks(text, onOpenLink, imageSession); return text.split(/(`[^`]+`)/g).map((chunk, c) => { if (chunk.length > 1 && chunk.startsWith('`') && chunk.endsWith('`')) - return {inlineMarks(chunk, onOpenLink)}; + return {inlineMarks(chunk, onOpenLink, imageSession)}; return {splitMath(chunk).map((part, p) => part.kind === 'math' ? - : {inlineMarks(part.text, onOpenLink)})}; + : {inlineMarks(part.text, onOpenLink, imageSession)})}; }); } -export function Markdown({ text, onOpenLink, onPreviewHtml }: { +export function Markdown({ text, onOpenLink, onPreviewHtml, imageSession }: { text: string; onOpenLink?: (url: string) => void; onPreviewHtml?: (html: string) => void; + /** The chat whose folder a picture path in the answer is read from (the host serves only files inside it). */ + imageSession?: string | null; }) { const nodes: ReactNode[] = []; const lines = text.split('\n'); @@ -66,7 +81,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { const heading = line.match(/^(#{1,6})\s+(.+)$/); if (heading) { const Tag = heading[1].length <= 2 ? 'h2' : heading[1].length === 3 ? 'h3' : 'h4'; - nodes.push({tr(inline(heading[2], onOpenLink))}); + nodes.push({tr(inline(heading[2], onOpenLink, imageSession))}); i++; continue; } @@ -90,7 +105,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { i += 2; while (i < lines.length && lines[i].includes('|')) rows.push(cells(lines[i++])); - nodes.push(
{tr(header.map((c, j) => ))}{tr(rows.map((r, j) => {tr(r.map((c, k) => ))}))}
{tr(inline(c, onOpenLink))}
{tr(inline(c, onOpenLink))}
); + nodes.push(
{tr(header.map((c, j) => ))}{tr(rows.map((r, j) => {tr(r.map((c, k) => ))}))}
{tr(inline(c, onOpenLink, imageSession))}
{tr(inline(c, onOpenLink, imageSession))}
); continue; } if (/^>\s?/.test(line)) { @@ -98,7 +113,7 @@ export function Markdown({ text, onOpenLink, onPreviewHtml }: { i++; continue; } - nodes.push(

{tr(inline(line, onOpenLink))}

); + nodes.push(

{tr(inline(line, onOpenLink, imageSession))}

); i++; } return <>{tr(nodes)}; diff --git a/apps/host/src/components/NativeMcpEditor.tsx b/apps/host/src/components/NativeMcpEditor.tsx index 471c4118..c3d08615 100644 --- a/apps/host/src/components/NativeMcpEditor.tsx +++ b/apps/host/src/components/NativeMcpEditor.tsx @@ -1,6 +1,7 @@ import { tr } from '../lib/i18n'; import { useState } from 'react'; import { Btn, Dialog, ErrorNotice, IconBtn, Select } from './ui'; +import { MCP_NAME_HELP, validMcpName } from '../lib/mcp-names'; export function NativeMcpEditor({ text, onChange }: { text: string; onChange: (text: string) => void; @@ -19,8 +20,8 @@ export function NativeMcpEditor({ text, onChange }: { function open(id: string) { const server = servers[id] ?? {}; setEditing(id); setName(id); setTransport(server.url ? 'url' : 'command'); setAddress(server.url ?? server.command ?? ''); setArgs((server.args ?? []).join('\n')); setAdvanced(JSON.stringify(Object.fromEntries(Object.entries(server).filter(([k]) => !['url', 'command', 'args', 'disabled'].includes(k))), null, 2)); setError(''); } function save() { try { - if (!/^[a-z0-9_-]{1,64}$/i.test(name)) - throw new Error('Use a simple server name: letters, numbers, hyphens or underscores.'); + if (!validMcpName(name)) + throw new Error(MCP_NAME_HELP); if (!address.trim()) throw new Error('Enter the server URL or program.'); if (name !== editing && servers[name]) diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 320d2213..b6d80683 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -7,6 +7,14 @@ import tune_es from '../locales/tune-es.json'; import tune_ru from '../locales/tune-ru.json'; import tune_pt from '../locales/tune-pt.json'; import tune_ko from '../locales/tune-ko.json'; +import tools_en from '../locales/tools-en.json'; +import tools_zh from '../locales/tools-zh.json'; +import tools_ja from '../locales/tools-ja.json'; +import tools_de from '../locales/tools-de.json'; +import tools_es from '../locales/tools-es.json'; +import tools_ru from '../locales/tools-ru.json'; +import tools_pt from '../locales/tools-pt.json'; +import tools_ko from '../locales/tools-ko.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -18,8 +26,9 @@ import base_ko from '../locales/ko.json'; export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ -const english:Record={...baseEnglish,...tune_en}; -const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh},{...base_ja,...tune_ja},{...base_de,...tune_de},{...base_es,...tune_es},{...base_ru,...tune_ru},{...base_pt,...tune_pt},{...base_ko,...tune_ko}] as Record[]; +/* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-.json for the same reason. */ +const english:Record={...baseEnglish,...tune_en,...tools_en}; +const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh},{...base_ja,...tune_ja,...tools_ja},{...base_de,...tune_de,...tools_de},{...base_es,...tune_es,...tools_es},{...base_ru,...tune_ru,...tools_ru},{...base_pt,...tune_pt,...tools_pt},{...base_ko,...tune_ko,...tools_ko}] as Record[]; const catalogs:Record>={en:english,zh,ja,de,es,ru,pt,ko}; const entities:Record={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); diff --git a/apps/host/src/lib/markdown-images.ts b/apps/host/src/lib/markdown-images.ts new file mode 100644 index 00000000..d6c3ba47 --- /dev/null +++ b/apps/host/src/lib/markdown-images.ts @@ -0,0 +1,32 @@ +import { rawUrlOf } from './deliverables'; + +/** + * Which picture addresses a model's Markdown may put in an (tools and images review O3, 2026-10-22). + * + * An answer can carry `![chart](...)`. It is shown only when the picture is already on this computer or inside the message: + * - a data: address of a PNG, JPEG, WebP or GIF (never SVG: an SVG can carry script and styles); + * - the host's own /api/files/raw address (a file inside the chat's folder, served by the host and by nobody else); + * - a path without a scheme, which is read as a file of the chat's folder through that same address. + * Nothing is fetched from the internet by default (an address in the answer would tell its owner that the answer was read, and + * which IP read it): an http(s) picture stays a link the person can open. file:, javascript:, blob: and every other scheme show as text. + */ +export type ImagePlan = + | { kind: 'img'; src: string } + | { kind: 'link'; href: string } + | { kind: 'text' }; + +const DATA_IMAGE = /^data:image\/(?:png|jpe?g|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/i; +const SCHEME = /^[a-z][a-z0-9+.-]*:/i; + +export function imagePlan(src: string, sessionId?: string | null): ImagePlan { + const value = src.trim(); + if (!value) return { kind: 'text' }; + if (DATA_IMAGE.test(value)) return { kind: 'img', src: value }; + if (/^https?:\/\//i.test(value)) return { kind: 'link', href: value }; + if (value.startsWith('/api/files/raw?')) return { kind: 'img', src: value }; + // a drive letter (C:\x.png, C:/x.png) is a path, not a scheme + if (SCHEME.test(value) && !/^[a-z]:[\\/]/i.test(value)) return { kind: 'text' }; + if (value.startsWith('//') || value.startsWith('\\\\')) return { kind: 'text' }; // another computer's share + if (!sessionId) return { kind: 'text' }; + return { kind: 'img', src: rawUrlOf(sessionId, value) }; +} diff --git a/apps/host/src/lib/mcp-names.ts b/apps/host/src/lib/mcp-names.ts new file mode 100644 index 00000000..bbae4009 --- /dev/null +++ b/apps/host/src/lib/mcp-names.ts @@ -0,0 +1,5 @@ +/** The one rule for the name of a tool server. A copy of server/mcp-names.mjs (tests/mcp-rows.test.mjs checks that they agree). */ +export const MCP_NAME_MAX = 32; +export const MCP_NAME_RE = /^[A-Za-z0-9_-]{1,32}$/; +export const validMcpName = (name: string) => MCP_NAME_RE.test(name); +export const MCP_NAME_HELP = 'Use a simple server name of up to 32 characters: letters, numbers, hyphens or underscores.'; diff --git a/apps/host/src/locales/tools-de.json b/apps/host/src/locales/tools-de.json new file mode 100644 index 00000000..ff28a2dc --- /dev/null +++ b/apps/host/src/locales/tools-de.json @@ -0,0 +1,6 @@ +{ + "tl01": "Verwende einen einfachen Servernamen mit höchstens 32 Zeichen: Buchstaben, Zahlen, Bindestriche oder Unterstriche.", + "tl02": "Diese Tool-Server wurden weggelassen, weil ihre Namen nicht erlaubt sind: {0}. Ein Name darf bis zu 32 Buchstaben, Zahlen, Bindestriche oder Unterstriche enthalten.", + "tl03": "Diese Tool-Server wurden weggelassen, weil sie kein Programm und keine Webadresse haben: {0}.", + "tl04": "Diese Tool-Server wurden weggelassen, weil ein anderer fast den gleichen Namen hat: {0}." +} diff --git a/apps/host/src/locales/tools-en.json b/apps/host/src/locales/tools-en.json new file mode 100644 index 00000000..d5b4d846 --- /dev/null +++ b/apps/host/src/locales/tools-en.json @@ -0,0 +1,6 @@ +{ + "tl01": "Use a simple server name of up to 32 characters: letters, numbers, hyphens or underscores.", + "tl02": "These tool servers were left out because their names are not allowed: {0}. A name can have up to 32 letters, numbers, hyphens or underscores.", + "tl03": "These tool servers were left out because they have no program or web address: {0}.", + "tl04": "These tool servers were left out because another one has almost the same name: {0}." +} diff --git a/apps/host/src/locales/tools-es.json b/apps/host/src/locales/tools-es.json new file mode 100644 index 00000000..7fb02da5 --- /dev/null +++ b/apps/host/src/locales/tools-es.json @@ -0,0 +1,6 @@ +{ + "tl01": "Usa un nombre de servidor sencillo de hasta 32 caracteres: letras, números, guiones o guiones bajos.", + "tl02": "Estos servidores de herramientas se han omitido porque sus nombres no están permitidos: {0}. Un nombre puede tener hasta 32 letras, números, guiones o guiones bajos.", + "tl03": "Estos servidores de herramientas se han omitido porque no tienen programa ni dirección web: {0}.", + "tl04": "Estos servidores de herramientas se han omitido porque otro tiene casi el mismo nombre: {0}." +} diff --git a/apps/host/src/locales/tools-ja.json b/apps/host/src/locales/tools-ja.json new file mode 100644 index 00000000..6896a5ba --- /dev/null +++ b/apps/host/src/locales/tools-ja.json @@ -0,0 +1,6 @@ +{ + "tl01": "サーバー名は32文字以内で、英字、数字、ハイフン、アンダースコアを使ってください。", + "tl02": "名前が使えないため、次のツールサーバーは除外されました: {0}。名前には、英字、数字、ハイフン、アンダースコアを32文字まで使えます。", + "tl03": "プログラムまたはWebアドレスがないため、次のツールサーバーは除外されました: {0}。", + "tl04": "ほぼ同じ名前の別のサーバーがあるため、次のツールサーバーは除外されました: {0}。" +} diff --git a/apps/host/src/locales/tools-ko.json b/apps/host/src/locales/tools-ko.json new file mode 100644 index 00000000..893ed5fd --- /dev/null +++ b/apps/host/src/locales/tools-ko.json @@ -0,0 +1,6 @@ +{ + "tl01": "32자 이내의 간단한 서버 이름을 사용하세요. 영문자, 숫자, 하이픈, 밑줄을 쓸 수 있습니다.", + "tl02": "이름을 사용할 수 없어 다음 도구 서버를 제외했습니다: {0}. 이름은 영문자, 숫자, 하이픈, 밑줄로 최대 32자까지 지을 수 있습니다.", + "tl03": "프로그램이나 웹 주소가 없어 다음 도구 서버를 제외했습니다: {0}.", + "tl04": "이름이 거의 같은 다른 서버가 있어 다음 도구 서버를 제외했습니다: {0}." +} diff --git a/apps/host/src/locales/tools-pt.json b/apps/host/src/locales/tools-pt.json new file mode 100644 index 00000000..3f89aff0 --- /dev/null +++ b/apps/host/src/locales/tools-pt.json @@ -0,0 +1,6 @@ +{ + "tl01": "Use um nome de servidor simples com até 32 caracteres: letras, números, hífens ou sublinhados.", + "tl02": "Estes servidores de ferramentas foram deixados de fora porque os nomes não são permitidos: {0}. Um nome pode ter até 32 letras, números, hífens ou sublinhados.", + "tl03": "Estes servidores de ferramentas foram deixados de fora porque não têm programa nem endereço web: {0}.", + "tl04": "Estes servidores de ferramentas foram deixados de fora porque outro tem quase o mesmo nome: {0}." +} diff --git a/apps/host/src/locales/tools-ru.json b/apps/host/src/locales/tools-ru.json new file mode 100644 index 00000000..fc7b37e9 --- /dev/null +++ b/apps/host/src/locales/tools-ru.json @@ -0,0 +1,6 @@ +{ + "tl01": "Используйте простое имя сервера не длиннее 32 символов: буквы, цифры, дефисы или подчёркивания.", + "tl02": "Эти серверы инструментов пропущены, потому что их имена недопустимы: {0}. Имя может содержать до 32 букв, цифр, дефисов или подчёркиваний.", + "tl03": "Эти серверы инструментов пропущены, потому что у них нет программы или веб-адреса: {0}.", + "tl04": "Эти серверы инструментов пропущены, потому что у другого почти такое же имя: {0}." +} diff --git a/apps/host/src/locales/tools-zh.json b/apps/host/src/locales/tools-zh.json new file mode 100644 index 00000000..d881b95d --- /dev/null +++ b/apps/host/src/locales/tools-zh.json @@ -0,0 +1,6 @@ +{ + "tl01": "请使用不超过 32 个字符的简单服务器名称:字母、数字、连字符或下划线。", + "tl02": "以下工具服务器已被忽略,因为名称不被允许:{0}。名称最多可包含 32 个字母、数字、连字符或下划线。", + "tl03": "以下工具服务器已被忽略,因为没有程序或网址:{0}。", + "tl04": "以下工具服务器已被忽略,因为另一个服务器的名称几乎相同:{0}。" +} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 2a95cedc..aa32de7a 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -615,7 +615,7 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp const [sentTime, setSentTime] = useState(() => relTime(m.at)); if (m.role === 'user') { return (
setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}> -
{tr(m.photos?.length ? : null)}{m.markdown ? : m.content}
+
{tr(m.photos?.length ? : null)}{m.markdown ? : m.content}
@@ -639,8 +639,8 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus) ?
{tr(planCard ? : null)} {tr(m.error ? () : null)} - {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? : onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)} - {tr(m.content && !planCard && !grouped ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? ( + {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? : onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)} + {tr(m.content && !planCard && !grouped ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? ( diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index c740716c..bb27e246 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -2467,6 +2467,12 @@ textarea.st-input { border: 1px solid var(--st-line); } +.md-image { + max-width: 100%; + height: auto; + border-radius: 8px; +} + .typing { display: inline-flex; gap: 4px; diff --git a/apps/host/tests/custom-command-tools.test.mjs b/apps/host/tests/custom-command-tools.test.mjs new file mode 100644 index 00000000..95c447d5 --- /dev/null +++ b/apps/host/tests/custom-command-tools.test.mjs @@ -0,0 +1,144 @@ +// T7 (tools and images review, 2026-10-22): a custom command tool runs in the shell that suits it, in the folder it needs, and with a time +// limit the person can raise. These tests run real commands; they use only what every machine has (node). +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync, realpathSync } from 'node:fs'; +import { tmpdir, homedir } from 'node:os'; +import { join } from 'node:path'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { createAgentTools } from '../server/agent/tools-settings.mjs'; +import { runCommand, planShell, looksLikePowerShell, resolveCwd, clampTimeoutSec, DEFAULT_TIMEOUT_SEC } from '../server/agent/custom-command-run.mjs'; + +const SERVER = fileURLToPath(new URL('../server/agent/custom-tools-mcp.mjs', import.meta.url)); +const node = JSON.stringify(process.execPath); +const WIN = process.platform === 'win32'; + +test('a Windows command that reads as PowerShell goes to PowerShell, the rest to cmd.exe, and a named shell is honoured', () => { + for (const c of ['Get-Content notes.txt', 'Start-Process notepad', 'Get-ChildItem | Where-Object { $_.Length -gt 1 }', '$env:HOME', 'echo $(Get-Date)']) + assert.ok(looksLikePowerShell(c), c); + for (const c of ['dir', 'type notes.txt', 'python tools\\foo.py --x', 'npm run build && echo done', 'echo %PATH%', 'git status']) + assert.ok(!looksLikePowerShell(c), c); + const ps = planShell('Get-Content x', { platform: 'win32' }); + assert.match(ps.file, /^(pwsh|powershell\.exe)$/); + assert.deepEqual(ps.args.slice(0, 5), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command']); + assert.equal(ps.args.at(-1), 'Get-Content x'); + assert.deepEqual(planShell('dir', { platform: 'win32' }), { file: 'dir', args: [], shell: true, name: 'cmd.exe' }); + assert.equal(planShell('dir', { platform: 'win32', shell: 'powershell' }).args.at(-1), 'dir'); + assert.equal(planShell('Get-Content x', { platform: 'win32', shell: 'cmd' }).shell, true); + assert.deepEqual(planShell('ls -la', { platform: 'linux' }), { file: 'ls -la', args: [], shell: true, name: 'sh' }); + assert.deepEqual(planShell('ls | wc -l', { platform: 'linux', shell: 'bash' }), { file: 'bash', args: ['-c', 'ls | wc -l'], shell: false, name: 'bash' }); + assert.equal(planShell('Get-Content x', { platform: 'linux' }).name, 'sh', 'on Linux and macOS a PowerShell-looking command is not rerouted'); +}); + +test('the time allowed is 2 minutes unless the tool says more, at most an hour', () => { + assert.equal(DEFAULT_TIMEOUT_SEC, 120); + assert.equal(clampTimeoutSec(undefined), 120); + assert.equal(clampTimeoutSec(600), 600); + assert.equal(clampTimeoutSec(99999), 3600); + assert.equal(clampTimeoutSec(0), 120); + assert.equal(clampTimeoutSec('abc'), 120); +}); + +test('a command runs in the folder the call names, then the tool\'s, then the home folder; a missing folder is a plain refusal', async () => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-'))); + const other = join(dir, 'other'); mkdirSync(other); + try { + const pwd = `${node} -e "console.log(process.cwd())"`; + const here = await runCommand({ command: pwd, cwd: dir }); + assert.equal(realpathSync(here.text), dir); + const named = await runCommand({ command: pwd, cwd: dir, callCwd: other }); + assert.equal(realpathSync(named.text), other, 'the folder named in the call wins'); + const home = await runCommand({ command: pwd }); + assert.equal(realpathSync(home.text), realpathSync(homedir())); + const gone = await runCommand({ command: pwd, cwd: join(dir, 'nope') }); + assert.equal(gone.ok, false); + assert.match(gone.text, /does not exist, so the command was not run/); + assert.deepEqual(resolveCwd(''), { cwd: homedir() }); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('a relative path in the command finds its file in the tool\'s folder', async () => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-'))); + try { + mkdirSync(join(dir, 'tools')); + writeFileSync(join(dir, 'tools', 'foo.js'), 'console.log("from foo " + (process.env.STRATA_INPUT || ""));'); + const r = await runCommand({ command: `${node} tools/foo.js`, cwd: dir, input: 'hello' }); + assert.deepEqual([r.ok, r.text], [true, 'from foo hello']); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('a command over the limit is ended and says so; output over the cap says it was cut', async () => { + const slow = await runCommand({ command: `${node} -e "setTimeout(()=>{}, 30000)"`, timeoutSec: 1 }); + assert.equal(slow.ok, false); + assert.match(slow.text, /stopped after 1 seconds/); + const big = await runCommand({ command: `${node} -e "process.stdout.write('x'.repeat(50000))"` }); + assert.equal(big.ok, true); + assert.match(big.text, /\(The output was cut after 20,000 characters\.\)$/); + assert.ok(big.text.length < 20100); +}); + +test('PowerShell commands run on Windows (Get-ChildItem, $env:)', { skip: !WIN && 'PowerShell is checked on Windows' }, async () => { + const r = await runCommand({ command: 'Write-Output ("a" + $env:STRATA_INPUT)', input: 'b' }); + assert.deepEqual([r.ok, r.text], [true, 'ab']); + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-'))); + try { + writeFileSync(join(dir, 'note.txt'), 'hi'); + const read = await runCommand({ command: 'Get-Content note.txt', cwd: dir }); + assert.deepEqual([read.ok, read.text], [true, 'hi']); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('Settings keeps a command tool\'s folder, shell and time, validates them, and an edit that does not send them keeps them', () => { + let stored; + const dir = mkdtempSync(join(tmpdir(), 'strata-cmdset-')); + try { + const tools = createAgentTools({ read: () => stored, write: v => { stored = v; }, dataDir: dir }); + tools.addCustom({ name: 'Build', about: 'Builds the project.', kind: 'command', command: 'npm run build', cwd: 'C:\\work\\app', shell: 'cmd', timeoutSec: 900 }); + let tool = tools.view().custom[0]; + assert.deepEqual([tool.cwd, tool.shell, tool.timeoutSec], ['C:\\work\\app', 'cmd', 900]); + tools.editCustom(tool.id, { name: 'Build', about: 'Builds the project, quickly.', kind: 'command', command: 'npm run build' }); // the form sends none of the three + tool = tools.view().custom[0]; + assert.deepEqual([tool.about, tool.cwd, tool.shell, tool.timeoutSec], ['Builds the project, quickly.', 'C:\\work\\app', 'cmd', 900]); + assert.throws(() => tools.editCustom(tool.id, { name: 'Build', about: 'x', kind: 'command', command: 'npm run build', timeoutSec: 99999 }), /1 to 3600/); + assert.throws(() => tools.editCustom(tool.id, { name: 'Build', about: 'x', kind: 'command', command: 'npm run build', shell: 'fish' }), /Choose how the command runs/); + tools.addCustom({ name: 'Plain', about: 'Plain.', kind: 'command', command: 'echo hi' }); + const plain = tools.view().custom[1]; + assert.deepEqual([plain.cwd, plain.shell, plain.timeoutSec], ['', 'auto', 120]); + // the tool server's file carries them + const file = JSON.parse(require_read(tools.filePath)); + assert.deepEqual(file.commands.build, { description: 'Builds the project, quickly.', command: 'npm run build', cwd: 'C:\\work\\app', shell: 'cmd', timeoutSec: 900 }); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +import { readFileSync } from 'node:fs'; +const require_read = file => readFileSync(file, 'utf8'); + +test('the tool server over stdio: the call may name a folder, and the tool\'s own settings apply', async () => { + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmdsrv-'))); + const work = join(dir, 'work'); mkdirSync(work); + const file = join(dir, 'tools.json'); + writeFileSync(file, JSON.stringify({ commands: { + where: { description: 'Prints its folder.', command: `${node} -e "console.log(process.cwd())"` }, + pinned: { description: 'Runs in work.', command: `${node} -e "console.log(process.cwd())"`, cwd: work }, + } })); + const child = spawn(process.execPath, [SERVER, 'commands', file], { stdio: ['pipe', 'pipe', 'inherit'] }); + const lines = []; let buffer = ''; + child.stdout.on('data', d => { buffer += d; let i; while ((i = buffer.indexOf('\n')) >= 0) { lines.push(JSON.parse(buffer.slice(0, i))); buffer = buffer.slice(i + 1); } }); + const ask = async (id, method, params) => { + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n'); + for (let n = 0; n < 200; n++) { const hit = lines.find(l => l.id === id); if (hit) return hit.result; await new Promise(r => setTimeout(r, 25)); } + throw new Error('no answer'); + }; + try { + const listed = await ask(1, 'tools/list', {}); + assert.ok(listed.tools.every(t => t.inputSchema.properties.cwd?.type === 'string'), 'the optional folder is offered'); + const pinned = await ask(2, 'tools/call', { name: 'pinned', arguments: {} }); + assert.equal(realpathSync(pinned.content[0].text), work); + const named = await ask(3, 'tools/call', { name: 'where', arguments: { cwd: dir } }); + assert.equal(realpathSync(named.content[0].text), dir); + const missing = await ask(4, 'tools/call', { name: 'where', arguments: { cwd: join(dir, 'nope') } }); + assert.equal(missing.isError, true); + assert.match(missing.content[0].text, /does not exist/); + } finally { child.kill(); rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/apps/host/tests/functional-fixes.test.mjs b/apps/host/tests/functional-fixes.test.mjs index b83b93e2..534107a6 100644 --- a/apps/host/tests/functional-fixes.test.mjs +++ b/apps/host/tests/functional-fixes.test.mjs @@ -96,22 +96,28 @@ test('item 7: tool rows say what happened in plain words, with what it was about } }); -test('item 8: starting a program that prints nothing is reported as started, plainly', () => { +test('item 8 / T9: starting a program that prints nothing is reported as started, never as opened', () => { for (const command of ['Start-Process explorer.exe C:\\work', 'explorer.exe C:\\work', 'start notepad', 'Invoke-Item C:\\work\\a.pdf', 'ii .', 'xdg-open .', 'open .']) { - assert.match(outcomeText('pwsh', '(no output)', { command }), /^Started\./, command); + const said = outcomeText('pwsh', '(no output)', { command }); + assert.match(said, /^The command finished without an error, so the program was started\./, command); + assert.match(said, /cannot confirm that a window or page actually opened/, command); + assert.ok(!/was opened|is open/i.test(said), command); } assert.match(outcomeText('pwsh', '(no output)', { command: 'New-Item x.txt | Out-Null' }), /finished without any error/, 'other silent commands keep their wording'); assert.equal(outcomeText('pwsh', 'hello', { command: 'echo hello' }), 'hello', 'a command that printed something shows it'); const p = new TurnProjector({ startedAt: 0 }); p.consume(ev('tool/call', { callId: 'e1', name: 'pwsh', arguments: JSON.stringify({ command: 'Start-Process explorer.exe C:\\work' }) })); const res = p.consume(ev('tool/result', { message: { toolCallId: 'e1', content: [{ type: 'text', text: '(no output)' }] } }))[0].tool; - assert.match(res.result, /^Started\./); assert.equal(res.verb, 'Ran a command'); + assert.match(res.result, /cannot confirm that a window or page actually opened/); assert.equal(res.verb, 'Ran a command'); }); test('item 7/10: our prompt has no internal terms and is short', () => { assert.ok(AGENT_PROMPT.length < 1600, `${AGENT_PROMPT.length} chars`); assert.doesNotMatch(AGENT_PROMPT, /DSH|DeepSeek|sandbox|isolated session|file policy|Harness/i); - assert.match(AGENT_PROMPT, /do not say you could not confirm/i); + // O6 / #3576: the prompt points at the present tool for local files and never tells the model to claim a window opened + assert.match(AGENT_PROMPT, /use the present tool/); + assert.match(AGENT_PROMPT, /Never say a window opened, a page rendered/); + assert.doesNotMatch(AGENT_PROMPT, /say plainly that it is open|do not say you could not confirm/i); }); test('items 3, 7, 10: what the agent sends the model is small, plain, and carries Thinking Off', { skip }, async t => { diff --git a/apps/host/tests/gate-fail-closed.test.mjs b/apps/host/tests/gate-fail-closed.test.mjs new file mode 100644 index 00000000..71c0c375 --- /dev/null +++ b/apps/host/tests/gate-fail-closed.test.mjs @@ -0,0 +1,36 @@ +// T4 (tools and images review, 2026-10-22): the approval gate fails closed. When the permission mode of a session cannot be read, a call +// that is not provably read-only asks, as in Manual; it used to run without a card. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { apply, MANUAL_PRESET } from '../server/agent/plugins/strata-gate.mjs'; + +function gate(current) { + let handler; + apply({ on: (_e, h) => { handler = h; }, inject: () => {}, sessions: new Map(), permissionPresets: { current }, approval: { overrideOf: () => 'never' } }); + return handler; +} +const session = { header: { origin: 'user' } }; +const allow = async () => ({ kind: 'allow' }); +const quiet = async fn => { const warn = console.warn; const lines = []; console.warn = (...a) => lines.push(a.join(' ')); try { return [await fn(), lines]; } finally { console.warn = warn; } }; + +test('a call that changes things asks when the preset cannot be resolved', async () => { + const handler = gate(() => { throw new Error('unknown session'); }); + const [result, lines] = await quiet(() => handler({ name: 'write', agent: { session }, input: { file_path: 'x' } }, allow)); + assert.equal(result.kind, 'ask'); + assert.match(lines.join('\n'), /could not read the permission mode.*unknown session.*Manual/); +}); + +test('a provably read-only call still goes through, and a shell write asks', async () => { + const handler = gate(() => { throw new Error('gone'); }); + const [read] = await quiet(() => handler({ name: 'read', agent: { session }, input: { file_path: 'x' } }, allow)); + assert.equal(read.kind, 'allow'); + const [shell] = await quiet(() => handler({ name: 'bash', agent: { session }, input: { command: 'rm -rf x' } }, allow)); + assert.equal(shell.kind, 'ask'); +}); + +test('with a readable preset nothing changes: Bypass runs, Manual asks', async () => { + const bypass = gate(() => 'strata-bypass'); + assert.equal((await bypass({ name: 'write', agent: { session }, input: { file_path: 'x' } }, allow)).kind, 'allow'); + const manual = gate(() => MANUAL_PRESET); + assert.equal((await manual({ name: 'write', agent: { session }, input: { file_path: 'x' } }, allow)).kind, 'ask'); +}); diff --git a/apps/host/tests/markdown-images.test.mjs b/apps/host/tests/markdown-images.test.mjs new file mode 100644 index 00000000..732cb092 --- /dev/null +++ b/apps/host/tests/markdown-images.test.mjs @@ -0,0 +1,77 @@ +// O3 (tools and images review, 2026-10-22): a Markdown image in an answer renders as a picture when it is already on this computer or inside +// the message, and never fetches anything from the internet by default. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { resolve } from 'node:path'; +import { createRequire } from 'node:module'; +import { build } from 'esbuild'; + +const root = resolve(import.meta.dirname, '..'); +const PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; + +async function load() { + const bundle = await build({ + stdin: { contents: `import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { Markdown } from './src/components/Markdown.tsx'; import { imagePlan } from './src/lib/markdown-images.ts'; export { imagePlan }; export const render = (text, imageSession) => renderToStaticMarkup(React.createElement(Markdown, { text, imageSession }));`, resolveDir: root }, + bundle: true, write: false, platform: 'node', format: 'cjs', jsx: 'automatic', external: ['katex', 'katex/dist/katex.min.css'], + plugins: [{ name: 'copy-control-stub', setup(b) { + b.onResolve({ filter: /^\.\/ui$/ }, () => ({ path: 'ui', namespace: 'test-stub' })); + b.onLoad({ filter: /.*/, namespace: 'test-stub' }, () => ({ contents: 'export const IconBtn = () => null; export const Btn = () => null;' })); + } }], + }); + const mod = { exports: {} }; + new Function('require', 'module', 'exports', bundle.outputFiles[0].text)(createRequire(import.meta.url), mod, mod.exports); + return mod.exports; +} + +test('a data: PNG, JPEG, WebP or GIF renders as an ', async () => { + const { render } = await load(); + const html = render(`Here it is: ![dot](${PNG}) done`); + assert.match(html, /]*src="data:image\/png;base64,/); + assert.match(html, /alt="dot"/); + assert.match(html, /referrerPolicy|referrerpolicy="no-referrer"/i); + for (const type of ['jpeg', 'jpg', 'webp', 'gif']) assert.match(render(`![x](data:image/${type};base64,QUJD)`), /', async () => { + const { render } = await load(); + for (const src of ['data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=', 'data:text/html;base64,QUJD', 'javascript:alert(1)', 'file:///C:/secret.png', + 'blob:https://x/1', 'ftp://x/y.png', '//host/share/x.png', '\\\\host\\share\\x.png', 'data:image/png;base64,QUJD" onerror="alert(1)']) { + const html = render(`![x](${src})`, 'chat-1'); + assert.ok(!/ { + const { render, imagePlan } = await load(); + const html = render('![Monthly sales](https://example.com/sales.png)', 'chat-1'); + assert.ok(!/]*href="https:\/\/example.com\/sales.png"[^>]*>Monthly sales<\/a>/); + assert.deepEqual(imagePlan('http://example.com/a.png'), { kind: 'link', href: 'http://example.com/a.png' }); +}); + +test('a path in the chat folder is read through the host, and only when the chat is known', async () => { + const { render, imagePlan } = await load(); + const html = render('![chart](plots/sales.png)', 'chat 1'); + assert.match(html, /]*src="\/api\/files\/raw\?sessionId=chat%201&path=plots%2Fsales.png"/); + assert.match(render('![chart](C:\\work\\sales.png)', 'c1'), /]*path=C%3A%5Cwork%5Csales.png/); + assert.ok(!/ { + const { render } = await load(); + const html = render('See [the report](https://example.com/r) and `code` and **bold**. ![a](' + PNG + ')'); + assert.match(html, /]*>the report<\/a>/); + assert.match(html, /code<\/code>/); + assert.match(html, /bold<\/strong>/); + assert.ok(!html.includes('>!<') && !/! { + const { render } = await load(); + const text = `Chart:\n\n![sales](${PNG})\n\nand ![b](https://example.com/b.png) end`; + for (let i = 0; i <= text.length; i += 7) assert.equal(typeof render(text.slice(0, i), 'c1'), 'string'); +}); diff --git a/apps/host/tests/mcp-rows.test.mjs b/apps/host/tests/mcp-rows.test.mjs new file mode 100644 index 00000000..c44411ea --- /dev/null +++ b/apps/host/tests/mcp-rows.test.mjs @@ -0,0 +1,92 @@ +// T5 / T6 (tools and images review, 2026-10-22): the agent's tool servers are the default model's, one naming rule is shared by the editor, the +// save check and the profile, and a server that is left out is reported instead of vanishing. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { mcpRows, mcpSkippedNotices, buildProfile } from '../server/agent/profile.mjs'; +import { MCP_NAME_MAX, MCP_NAME_RE, validMcpName, MCP_NAME_HELP } from '../server/mcp-names.mjs'; +import { validateMcpServers } from '../server/native-settings.mjs'; + +const cmd = { command: 'node', args: ['x.js'] }; + +test('one rule: 32 characters of letters, numbers, hyphens and underscores', () => { + assert.equal(MCP_NAME_MAX, 32); + for (const ok of ['files', 'my_server-1', 'A', 'x'.repeat(32)]) assert.ok(validMcpName(ok), ok); + for (const bad of ['', 'my.server', 'x'.repeat(33), 'x'.repeat(40), 'a b', 'ä', 'a/b']) assert.ok(!validMcpName(bad), bad); + assert.match(MCP_NAME_HELP, /up to 32/); +}); + +test('the editor keeps the same rule as the host (a copy in src/lib/mcp-names.ts)', async () => { + const text = await readFile(new URL('../src/lib/mcp-names.ts', import.meta.url), 'utf8'); + assert.ok(text.includes(String(MCP_NAME_RE)), 'same regular expression'); + assert.ok(text.includes(`MCP_NAME_MAX = ${MCP_NAME_MAX}`)); + assert.ok(text.includes(MCP_NAME_HELP), 'same help sentence'); + const editor = await readFile(new URL('../src/components/NativeMcpEditor.tsx', import.meta.url), 'utf8'); + assert.ok(editor.includes('validMcpName(name)') && !editor.includes('{1,64}')); +}); + +test('the save check refuses a new name over 32 but does not block the other settings of a name saved before', () => { + const long = 'x'.repeat(40); + assert.throws(() => validateMcpServers({ [long]: cmd }, {}), /up to 32/); + assert.throws(() => validateMcpServers({ 'my.server': cmd }, {}), /up to 32/); + assert.deepEqual(Object.keys(validateMcpServers({ [long]: cmd }, { [long]: cmd })), [long]); + assert.deepEqual(Object.keys(validateMcpServers({ files: cmd }, {})), ['files']); +}); + +test('a server that cannot be wired is reported with its reason, not dropped silently', () => { + const skipped = []; + const rows = mcpRows({ + files: cmd, [`${'y'.repeat(40)}`]: cmd, 'my.server': cmd, empty: {}, off: { ...cmd, disabled: true }, + Files2: cmd, 'files2': cmd, + }, {}, skipped); + assert.deepEqual(rows.map(r => r.config.serverName), ['files', 'Files2']); + assert.deepEqual(skipped.map(s => [s.name.slice(0, 6), s.why]), [['yyyyyy', 'name'], ['my.ser', 'name'], ['empty', 'address'], ['files2', 'duplicate']]); + // switched off on purpose is not an error + assert.ok(!skipped.some(s => s.name === 'off')); +}); + +test('the notices name the servers, one sentence per reason, in the catalog wording', async () => { + const notices = mcpSkippedNotices([{ name: 'a.b', why: 'name' }, { name: 'c'.repeat(33), why: 'name' }, { name: 'e', why: 'address' }]); + assert.equal(notices.length, 2); + assert.match(notices[0].message, /^These tool servers were left out because their names are not allowed: a\.b, c{33}\./); + assert.match(notices[1].message, /no program or web address: e\.$/); + assert.notEqual(notices[0].code, notices[1].code); + assert.deepEqual(mcpSkippedNotices([]), []); + // every sentence is in the catalog of every language (src/locales/tools-.json) + for (const lang of ['en', 'de', 'es', 'pt', 'ru', 'ja', 'ko', 'zh']) { + const catalog = JSON.parse(await readFile(new URL(`../src/locales/tools-${lang}.json`, import.meta.url), 'utf8')); + const english = JSON.parse(await readFile(new URL('../src/locales/tools-en.json', import.meta.url), 'utf8')); + for (const text of ['These tool servers were left out because their names are not allowed: {0}. A name can have up to 32 letters, numbers, hyphens or underscores.', + 'These tool servers were left out because they have no program or web address: {0}.', + 'These tool servers were left out because another one has almost the same name: {0}.']) { + const id = Object.keys(english).find(k => english[k] === text); + assert.ok(id, text); + assert.ok(catalog[id]?.includes('{0}'), `${lang}:${id}`); + } + } +}); + +test('the agent gets the tool servers of the DEFAULT instance, not the first one loaded', () => { + const local = [ + { id: 'first', modelId: 'm1', baseUrl: 'http://127.0.0.1:1/v1', mcpServers: { alpha: cmd } }, + { id: 'second', modelId: 'm2', baseUrl: 'http://127.0.0.1:2/v1', mcpServers: { beta: cmd } }, + ]; + const names = profile => profile.patch.match(/"serverName": "([^"]+)"/g)?.map(s => s.slice(15, -1)) ?? []; + assert.deepEqual(names(buildProfile({ local, defaultLocalId: 'second' })), ['beta']); + assert.deepEqual(names(buildProfile({ local, defaultLocalId: 'first' })), ['alpha']); + assert.deepEqual(names(buildProfile({ local })), ['alpha'], 'no default named: the first, as before'); + assert.deepEqual(names(buildProfile({ local, defaultLocalId: 'gone' })), ['alpha'], 'a default that is not loaded: the first'); + // the agent's own default model follows the same instance, and a different default changes what a running agent must be restarted for + assert.equal(buildProfile({ local, defaultLocalId: 'second' }).defaultRoute.instanceId, 'second'); + assert.notEqual(buildProfile({ local, defaultLocalId: 'second' }).toolsSignature, buildProfile({ local, defaultLocalId: 'first' }).toolsSignature); + // the Settings servers are added for every default + const withSettings = buildProfile({ local, defaultLocalId: 'second', tools: { off: new Set(), search: { provider: 'builtin', key: '' }, servers: { gamma: cmd } } }); + assert.deepEqual(names(withSettings).sort(), ['beta', 'gamma']); +}); + +test('buildProfile hands the skipped servers on for the chat to report', () => { + const local = [{ id: 'a', modelId: 'm', baseUrl: 'http://127.0.0.1:1/v1', mcpServers: { ['z'.repeat(33)]: cmd, ok: cmd } }]; + const profile = buildProfile({ local, defaultLocalId: 'a' }); + assert.deepEqual(profile.mcpSkipped.map(s => s.why), ['name']); + assert.match(profile.patch, /"serverName": "ok"/); +}); diff --git a/apps/host/tests/tools-locales.test.mjs b/apps/host/tests/tools-locales.test.mjs new file mode 100644 index 00000000..294ddb7a --- /dev/null +++ b/apps/host/tests/tools-locales.test.mjs @@ -0,0 +1,42 @@ +// The strings of the tools and images fixes (src/locales/tools-.json) exist in every language with the same slots and no empty text, +// do not collide with the main catalog, and translate through tr(). +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { build } from 'esbuild'; + +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tools-${l}.json`, 'utf8'))]))); +const main = JSON.parse(await readFile('src/locales/en.json', 'utf8')); +const tune = JSON.parse(await readFile('src/locales/tune-en.json', 'utf8')); +const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort(); +const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } }); +const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); + +test('every language has every tools string with the same slots and no empty text', () => { + for (const l of languages) { + assert.deepEqual(Object.keys(catalogs[l]), Object.keys(catalogs.en), l); + for (const [id, source] of Object.entries(catalogs.en)) { + assert.ok(catalogs[l][id].trim(), `${l}:${id} is empty`); + assert.deepEqual(slots(catalogs[l][id]), slots(source), `${l}:${id}`); + } + } +}); + +test('the ids and texts do not collide with the main or Tune catalogs, and translate through tr()', () => { + const seen = new Set([...Object.values(main), ...Object.values(tune)]); + for (const [id, text] of Object.entries(catalogs.en)) { + assert.ok(!(id in main) && !(id in tune), id); + assert.ok(!seen.has(text), `already in another catalog: ${text}`); + } + const first = Object.keys(catalogs.en)[0]; + for (const l of languages) { + setTranslationLanguage(l); + assert.equal(tr(catalogs.en[first]), catalogs[l][first], l); + } + setTranslationLanguage('de'); + const withName = Object.entries(catalogs.en).find(([, t]) => t.includes('{0}')); + const shown = tr(withName[1].replace('{0}', 'files, a.b')); + assert.equal(shown, catalogs.de[withName[0]].replace('{0}', 'files, a.b')); + setTranslationLanguage('en'); +}); diff --git a/packaging/ENGINE-COMPONENT.md b/packaging/ENGINE-COMPONENT.md index ea76ae39..642c2f0b 100644 --- a/packaging/ENGINE-COMPONENT.md +++ b/packaging/ENGINE-COMPONENT.md @@ -96,16 +96,16 @@ the manifest file (which holds every file's hash), used as the package's digest | Package | Built on | Contents | Notes | |---|---|---|---| -| `windows-x86_64` cuda, variant `cuda13` | the owner PC, the same cmake line as the release zips (CUDA 13.0, `75;86;89;120` real + `120` PTX, `STRATA_PORTABLE=ON`) | `strata.exe`, `strata_kq.dll`, `strata-vision.exe` (reused, unchanged since 0.1.44), `BUILD.json` | `min_driver` nvidia 580.65 | -| `windows-x86_64` cuda, variant `cuda12` | the owner PC (CUDA 12.9, `60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same four files | experimental, `min_driver` nvidia 575.51; the CUDA 13 build wins when both fit | +| `windows-x86_64` cuda, variant `cuda13` | the owner PC, the same cmake line as the release zips (CUDA 13.0, `75;86;89;120` real + `120` PTX, `STRATA_PORTABLE=ON`) | `strata.exe`, `strata_kq.dll`, `strata-vision.exe` (built for this variant's archs by `packaging/build_vision_windows.bat cuda13 `, which writes `vision_archs` into BUILD.json), `BUILD.json` | `min_driver` nvidia 580.65 | +| `windows-x86_64` cuda, variant `cuda12` | the owner PC (CUDA 12.9, `60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same four files, with its own `strata-vision.exe` (`packaging/build_vision_windows.bat cuda12 `: sm_60 .. sm_89; the CUDA 13 reader has no Pascal code, #3669) | experimental, `min_driver` nvidia 575.51; the CUDA 13 build wins when both fit | | `windows-x86_64` hip | the owner PC, `tools/hip/build_windows.bat` (ROCm 10.2 nightly wheels) then `tools/hip/package_windows.py` | `strata.exe`, `strata-device.exe`, the ROCm DLLs and the rocBLAS/hipBLASLt kernels of the zip (`--tree`) | no Windows AMD test machine yet; with `STRATA_NO_VISION` unset it also builds the two picture readers (`strata-vision.exe` on the CPU, `strata-vision-hip.exe` on the GPU) | -| `linux-x86_64` cuda, variant `cuda13` | a Linux box with the CUDA 13 toolkit, `VARIANT=cuda13 packaging/build_cuda_linux.sh` | `strata`, `libstrata_kq.so`, `libcudart/libcublas/libcublasLt` (13.x) | the GPU driver's `libcuda` stays the PC's | -| `linux-x86_64` cuda, variant `cuda12` | a Linux box with CUDA 12.9, `VARIANT=cuda12 packaging/build_cuda_linux.sh` (`60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same files with the 12.x libraries | experimental, `min_driver` nvidia 575.51; the Pascal and Volta package (the 0.2.1 one lacked sm_60 / 61 / 70, #3503); `package_engine.py` refuses a cuda12 package without them | +| `linux-x86_64` cuda, variant `cuda13` | a Linux box with the CUDA 13 toolkit, `VARIANT=cuda13 packaging/build_cuda_linux.sh` | `strata`, `libstrata_kq.so`, `strata-vision` (built by the same script for the same archs, `BUILD_VISION=0` for a text-only package), `libcudart/libcublas/libcublasLt` (13.x) | the GPU driver's `libcuda` stays the PC's | +| `linux-x86_64` cuda, variant `cuda12` | a Linux box with CUDA 12.9, `VARIANT=cuda12 packaging/build_cuda_linux.sh` (`60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same files with the 12.x libraries (the reader has sm_60 / 61 / 70 too) | experimental, `min_driver` nvidia 575.51; the Pascal and Volta package (the 0.2.1 one lacked sm_60 / 61 / 70, #3503); `package_engine.py` refuses a cuda12 package without them | | `linux-x86_64` hip | a box with ROCm (the Python wheels are enough) | `strata`, the HIP runtime, hipBLAS/hipBLASLt/rocBLAS, comgr + libLLVM, `rocblas/library` and `hipblaslt/library` for the listed gfx archs; `packaging/build_hip_linux.sh` builds it with both picture readers | | `linux-x86_64` hip, variant `rx6000` (RX 6000, gfx1030 / gfx1031) | `VARIANT=rx6000 packaging/build_hip_linux.sh` in the jammy chroot, ROCm 7.13.0a20260515 `gfx103X-all` wheels | the same set as the other HIP packages, with `rocblas/library` for gfx1030 / gfx1031; no `hipblaslt/library` kernels exist for them and no `tuning/` table | built, not tested on a real RX 6000 card (the manifest notes say so). `windows-x86_64` hip, variant `rdna2`: the same archs from `tools/hip/build_windows.bat` with `STRATA_HIP_ARCHS=gfx1030;gfx1031`, packaged with `--variant rdna2`. A PC with an RX 7000 / 9000 card beside an RX 6000 one never takes it (`engine_component.hip_preference`) | | `linux-x86_64` hip, gfx1103 (Radeon 780M / Phoenix iGPU) | `packaging/build_hip_gfx1103.sh` on the mini PC (TheRock gfx110X-all SDK) | the same set as the gfx1200/1201 package, with `rocblas/library` and `hipblaslt/library` for gfx1103 (600 MiB) | experimental, unvalidated: the iGPU resets now and then (MES REMOVE_QUEUE); never kill the engine mid-request; run configs set `STRATA_NO_ARENA_THP=1`. `engine_component.resolve` picks a HIP package only when its `archs` list a gfx target the Linux kfd topology reports | | `linux-x86_64` sycl, `archs` `intel-arc` | a Linux box with oneAPI DPC++ 2026.1 and `patchelf`, `packaging/build_sycl_linux.sh` (JIT from SPIR-V; ocloc cannot build the Alchemist FP64 kernels ahead of time, so one JIT package serves A-series and B-series) | `strata`, libsycl, the Unified Runtime adapters, the oneMKL SYCL libraries, libimf / libsvml / libirng / libintlc (about 650 MiB); every ELF file has RUNPATH `$ORIGIN` (Intel's libraries ship without it), so `env -i ./strata --version` runs | the Level Zero loader and compute runtime are the PC's driver; the user must be in the `render` group (`strata doctor` warns). No Windows package: `BACKEND_MATRIX` allows sycl on `linux-x86_64` only | -| `macos-arm64` metal | an Apple Silicon Mac | `strata`, `metal/kernels/*.metal`, `metal/engine-msl/*.metal`, `metal/ggml-common.h`, `metal/data/*.bin` | the Metal engine compiles its kernel sources when it starts; since S1 it finds them beside the executable (`metal/src/resource_path.h`: environment variable, then `/metal/`, then the compiled-in source path) | +| `macos-arm64` metal | an Apple Silicon Mac | `strata`, `strata-vision` (`packaging/build_vision_mac.sh`; `package_engine.py` refuses a macOS package without it, #3697), `metal/kernels/*.metal`, `metal/engine-msl/*.metal`, `metal/ggml-common.h`, `metal/data/*.bin` | the Metal engine compiles its kernel sources when it starts; since S1 it finds them beside the executable (`metal/src/resource_path.h`: environment variable, then `/metal/`, then the compiled-in source path) | `packaging/collect_libs.py` gathers the Linux libraries (an `ldd` closure with the dlopen'd extras named, kernel data filtered by GPU architecture) into the folder `package_engine.py` packages; libraries the distribution provides are listed in @@ -122,6 +122,20 @@ with the package). `packaging/stage_tuning.py` does it for the Linux build scrip `STRATA_HIPBLASLT_TABLE=on|off` (or `"hipblaslt_table"` in the run config) overrides; unset it follows `AUTO_USES_TABLE`, which is off until the owner decides, because a table changes the rounding of the prompt's GEMMs (docs/AMD_HIP.md, Tuning table). Tests: `tests/terminal/test_hipblaslt_tuning.py`. +## The picture reader must match the package + +`package_engine.py` (the command line, not the library call) checks the reader before it packages: + +* a CUDA package with `strata-vision` needs `vision_archs` in BUILD.json, and every `sm_NN` of the package must be in it. A reader reused from an + older build was the cause of #3669 (the cuda12 package on a Pascal card: the engine ran, the reader stopped with "device kernel image is + invalid"). `--allow-stale-vision` packages it anyway and prints which archs are missing; +* a macOS package without `strata-vision` is refused (`--no-picture-reader` ships a text-only Mac package on purpose); +* a CUDA package with no reader is allowed: it answers text only, the app says "the engine installed here does not include the picture reader + yet" and keeps Read pictures off. + +`python packaging/package_engine.py --stamp-vision --vision-archs "60;61;70;75;80;86;89"` writes the record for a reader built by hand. +At run time a reader that still cannot start tells why (stderr tail, exit status, and for a kernel-image error the card hint). + ## Picture readers in an AMD package A HIP package carries two programs for pictures next to `strata` (`vision` in its BUILD.json): `strata-vision` is the CPU reader, which diff --git a/packaging/build_cuda_linux.sh b/packaging/build_cuda_linux.sh index 6c07a5ba..dde9893e 100644 --- a/packaging/build_cuda_linux.sh +++ b/packaging/build_cuda_linux.sh @@ -36,12 +36,26 @@ cmake -G Ninja -S . -B "$build" -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA= "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR="$repo/third_party/llama.cpp" cmake --build "$build" --target strata strata_kq -j "$(nproc)" +# The picture reader is built for the SAME architectures as the engine (#3669: a reader reused from an older build had no sm_60, and on +# a Pascal card the engine ran while the reader died with "device kernel image is invalid"). BUILD_VISION=0 ships a text-only package. +vision_dir=${BUILD_VISION_DIR:-$repo/build-vision-$variant} +if [ "${BUILD_VISION:-1}" = 1 ]; then + cmake -G Ninja -S tools/vision -B "$vision_dir" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="$repo/third_party/llama.cpp" \ + -DSTRATA_VISION_CUDA=ON -DSTRATA_PORTABLE=ON -DGGML_CUDA_NCCL=OFF "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" + cmake --build "$vision_dir" --target strata-vision -j "$(nproc)" +fi + ver=$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1) stage=$(mktemp -d "${TMPDIR:-/tmp}/strata-engine-stage.XXXXXX") trap 'rm -rf "$stage"' EXIT cp "$build/strata" "$stage/" [ -f "$build/libstrata_kq.so" ] && cp "$build/libstrata_kq.so" "$stage/" -echo "{\"version\": \"$ver\", \"source\": \"packaging/build_cuda_linux.sh\", \"archs\": \"$archs\", \"cuda\": \"$cudafull\", \"portable\": true}" > "$stage/BUILD.json" +vision_json="" +if [ -f "$vision_dir/bin/strata-vision" ]; then + cp "$vision_dir/bin/strata-vision" "$stage/" + vision_json=", \"vision_archs\": \"$archs\"" # package_engine.py refuses a reader whose archs do not cover the engine's +fi +echo "{\"version\": \"$ver\", \"source\": \"packaging/build_cuda_linux.sh\", \"archs\": \"$archs\", \"cuda\": \"$cudafull\", \"portable\": true$vision_json}" > "$stage/BUILD.json" "$py" packaging/collect_libs.py --binary "$build/strata" --search /usr/local/cuda/lib64 --out "$stage" --also 'libcublasLt.so*' arch_args=""; for a in $(echo "$archs" | tr ';,' ' '); do arch_args="$arch_args --arch sm_$a"; done mkdir -p "$out" diff --git a/packaging/build_vision_windows.bat b/packaging/build_vision_windows.bat new file mode 100644 index 00000000..f751f655 --- /dev/null +++ b/packaging/build_vision_windows.bat @@ -0,0 +1,69 @@ +@echo off +rem The Windows CUDA picture reader for an engine package: strata-vision.exe built for the SAME architectures as the package's strata.exe. +rem +rem packaging\build_vision_windows.bat cuda12 CUDA 12.9: 60;61;70;75;80;86;89 (+ 89 PTX) the Pascal / Volta package +rem packaging\build_vision_windows.bat cuda13 CUDA 13.0: 75;86;89;120 (+ 120 PTX) +rem +rem Why: the cuda12 and cuda13 packages used to share one strata-vision.exe, built before the Pascal code existed (unchanged since 0.1.44). On a +rem Tesla P100 / GTX 10 card the engine ran and the reader stopped with "IM2COL failed / device kernel image is invalid" (#3669), and the +rem app only said "the vision encoder did not start". Now each variant has its own reader and packaging\package_engine.py refuses a package +rem whose BUILD.json vision_archs do not cover its archs. +rem +rem Needs: Visual Studio 2022 Build Tools (run from a "x64 Native Tools" prompt, or let this call vcvars64), CMake + Ninja, the CUDA toolkit of +rem the variant (CUDA_PATH_V12_9 / CUDA_PATH_V13_0, or CUDA_PATH already pointing at it), and the pinned llama.cpp (python -c "import setup; +rem setup.get_llama_cpp()", or STRATA_GGML_DIR). +rem +rem Settings (all optional): STRATA_GGML_DIR the llama.cpp checkout (default third_party\llama.cpp) VISION_BUILD_DIR the build folder +rem VISION_ARCHS override the architecture list (semicolons) BUILD_JOBS the number of compile jobs (default 4: the CUDA compiler uses RAM) +rem +rem It copies strata-vision.exe into and writes vision_archs into \BUILD.json. Nothing is uploaded. +setlocal EnableDelayedExpansion +set "VARIANT=%~1" +set "STAGE=%~2" +if "%VARIANT%"=="" goto usage +if "%STAGE%"=="" goto usage +for %%I in ("%~dp0..") do set "SRC=%%~fI" +if /i "%VARIANT%"=="cuda12" ( + set "ARCHS=60;61;70;75;80;86;89" + if defined CUDA_PATH_V12_9 set "CUDA_PATH=%CUDA_PATH_V12_9%" +) else if /i "%VARIANT%"=="cuda13" ( + set "ARCHS=75;86;89;120" + if defined CUDA_PATH_V13_0 set "CUDA_PATH=%CUDA_PATH_V13_0%" +) else goto usage +if defined VISION_ARCHS set "ARCHS=%VISION_ARCHS%" +if not defined CUDA_PATH (echo CUDA_PATH is not set: install the %VARIANT% toolkit & exit /b 1) +if not exist "%CUDA_PATH%\bin\nvcc.exe" (echo no nvcc.exe in %CUDA_PATH%\bin & exit /b 1) +if not defined BUILD_JOBS set "BUILD_JOBS=4" +if not defined STRATA_GGML_DIR set "STRATA_GGML_DIR=%SRC%\third_party\llama.cpp" +set "LLAMA=%STRATA_GGML_DIR:\=/%" +if not exist "%LLAMA%/tools/mtmd" (echo llama.cpp with tools/mtmd not found in %LLAMA% - set STRATA_GGML_DIR & exit /b 1) +if not defined VISION_BUILD_DIR set "VISION_BUILD_DIR=%SRC%\build-vision-%VARIANT%-win" +if not exist "%STAGE%" mkdir "%STAGE%" + +where cl >nul 2>nul || ( + for %%V in ("%ProgramFiles%\Microsoft Visual Studio\2022\BuildTools" "%ProgramFiles%\Microsoft Visual Studio\2022\Community" "%ProgramFiles(x86)%\Microsoft Visual Studio\2022\BuildTools") do ( + if exist "%%~V\VC\Auxiliary\Build\vcvars64.bat" if not defined VCVARS set "VCVARS=%%~V\VC\Auxiliary\Build\vcvars64.bat" + ) + if defined VCVARS call "!VCVARS!" >nul +) +where cl >nul 2>nul || (echo cl.exe not found: run this from an x64 Native Tools prompt & exit /b 1) + +rem every arch real, and PTX for the newest one, the way the engine is built +set "REAL=" +for %%A in (%ARCHS:;= %) do ( + set "LAST=%%A" + if defined REAL (set "REAL=!REAL!;%%A-real") else (set "REAL=%%A-real") +) +cmake -G Ninja -S "%SRC%\tools\vision" -B "%VISION_BUILD_DIR%" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="%LLAMA%" ^ + -DSTRATA_VISION_CUDA=ON -DSTRATA_PORTABLE=ON -DGGML_CUDA_NCCL=OFF ^ + "-DCMAKE_CUDA_ARCHITECTURES=!REAL!;!LAST!-virtual" -DCMAKE_C_COMPILER=cl -DCMAKE_CXX_COMPILER=cl ^ + "-DCMAKE_CUDA_COMPILER=%CUDA_PATH%/bin/nvcc.exe" "-DCUDAToolkit_ROOT=%CUDA_PATH%" || exit /b 1 +cmake --build "%VISION_BUILD_DIR%" --target strata-vision -j %BUILD_JOBS% || exit /b 1 +copy /y "%VISION_BUILD_DIR%\bin\strata-vision.exe" "%STAGE%\strata-vision.exe" >nul || exit /b 1 +py -3 "%~dp0package_engine.py" --stamp-vision "%STAGE%" --vision-archs "%ARCHS%" || exit /b 1 +echo built: %STAGE%\strata-vision.exe (%VARIANT%, archs %ARCHS%) +exit /b 0 + +:usage +echo usage: packaging\build_vision_windows.bat cuda12^|cuda13 ^ +exit /b 2 diff --git a/packaging/package_engine.py b/packaging/package_engine.py index 86e58368..f9f3e148 100644 --- a/packaging/package_engine.py +++ b/packaging/package_engine.py @@ -27,6 +27,7 @@ import fnmatch import hashlib import json import os +import re import shutil import subprocess import sys @@ -56,6 +57,78 @@ def wanted(path: Path) -> bool: or name.startswith("license") or name in ("strata-vision", "strata-vision.exe", "strata-vision-hip", "strata-vision-hip.exe")) # the picture readers (CPU, AMD GPU) beside the engine +READER_NAMES = ("strata-vision", "strata-vision.exe") + + +def _arch_numbers(value) -> set[int]: + """The CUDA architectures in a BUILD.json `archs` / `vision_archs` value ("60;61;70", [60, "sm_61", "70-real"], ...), as numbers.""" + if isinstance(value, str): + value = re.split(r"[;,\s]+", value) + found: set[int] = set() + for item in value or []: + m = re.fullmatch(r"(?:sm_|compute_)?(\d+)(?:a|f)?(?:-real|-virtual)?", str(item).strip().lower()) + if m: + found.add(int(m.group(1))) + return found + + +def check_picture_reader(src: Path, backend: str, target: str, archs: tuple[str, ...], *, variant: str = "", + allow_stale: bool = False, allow_none: bool = False) -> list[str]: + """The picture reader of a package must run on every card and Mac the package does (tools tests: I1, I2, #3669, #3697). + + * CUDA package with a reader: BUILD.json (beside the engine) must list `vision_archs`, and every `sm_NN` the package carries + code for must be there. A reader reused from an older build (the Windows zips' strata-vision.exe, unchanged since 0.1.44, had no + sm_60) stops with "device kernel image is invalid" on a Pascal card while the engine runs. Refused, unless allow_stale. + * macOS package without a reader: refused (a Mac with this package cannot read a picture), unless allow_none. + * CUDA package without a reader: allowed (text-only), reported in the returned notes so the build log says it. + Returns notes to print.""" + reader = next((n for n in READER_NAMES if (src / n).is_file()), None) + notes: list[str] = [] + if target.startswith("macos"): + if reader is None and not allow_none: + raise SystemExit("refusing to package the macOS engine without its picture reader: a Mac with this package could not read " + "a picture (#3697). Build it with packaging/build_vision_mac.sh and copy strata-vision beside strata " + "(or give --no-picture-reader to ship a text-only package on purpose).") + if reader is None: + notes.append("no picture reader in this macOS package: pictures are off for it") + return notes + if backend != "cuda": + return notes + if reader is None: + notes.append("no picture reader in this CUDA package: the engine answers text only (the app says pictures need the reader)") + return notes + needed = {n for n in _arch_numbers([a for a in archs if str(a).lower().startswith("sm_")])} + have: set[int] = set() + build_json = src / "BUILD.json" + try: + have = _arch_numbers(json.loads(build_json.read_text(encoding="utf-8-sig")).get("vision_archs")) + except (OSError, ValueError, AttributeError): + pass + missing = sorted(needed - have) + if missing and not allow_stale: + what = ("BUILD.json has no vision_archs: the reader's build is not recorded" if not have + else "the reader has no code for " + ", ".join(f"sm_{n}" for n in missing)) + raise SystemExit(f"refusing to package the {variant or backend} engine with this picture reader: {what}. A reader reused from an " + "older build stops with 'device kernel image is invalid' on a card it was not built for (#3669). Build it for the " + "package's architectures (packaging/build_vision_windows.bat, packaging/build_cuda_linux.sh) and record them as " + "vision_archs in BUILD.json (or give --allow-stale-vision).") + if missing: + notes.append("picture reader NOT built for " + ", ".join(f"sm_{n}" for n in missing) + " (allowed by --allow-stale-vision)") + return notes + + +def stamp_vision_archs(stage: Path, archs: str) -> None: + """Record the architectures the picture reader in `stage` was built for as BUILD.json `vision_archs` (the build recipes for Windows + call this after building strata-vision.exe; check_picture_reader compares it with the package's archs).""" + path = stage / "BUILD.json" + try: + data = json.loads(path.read_text(encoding="utf-8-sig")) if path.is_file() else {} + except (OSError, ValueError): + data = {} + data["vision_archs"] = ";".join(str(n) for n in sorted(_arch_numbers(archs))) + path.write_text(json.dumps(data, indent=1) + chr(10), encoding="utf-8") + + def git_build_id(repo: Path = ROOT) -> str: """The source commit of the engine build, `-dirty` when the tree had changes. `unknown` outside a checkout.""" try: @@ -90,7 +163,8 @@ def select(src: Path, entrypoint: str, *, tree: bool, include: list[str]) -> lis def build(src: Path, backend: str, version: str, target: str, out: Path, *, entry: str | None = None, archs: tuple[str, ...] = (), min_driver: dict | None = None, build_id: str | None = None, min_runtime: str | None = None, notes: str = "", tree: bool = False, include: list[str] | None = None, - variant: str = "", search: list[Path] | None = None, allow_libs: list[str] | None = None) -> Path: + variant: str = "", search: list[Path] | None = None, allow_libs: list[str] | None = None, + check_reader: bool = False, allow_stale_vision: bool = False, allow_no_reader: bool = False) -> Path: if backend not in BACKEND_MATRIX: raise SystemExit(f"unknown backend {backend!r}") if backend != "cpu" and not archs: @@ -108,6 +182,10 @@ def build(src: Path, backend: str, version: str, target: str, out: Path, *, entr entrypoint = entry or ("strata.exe" if target.startswith("windows") else "strata") if not (src / entrypoint).is_file(): raise SystemExit(f"{src / entrypoint} does not exist") + if check_reader: # the release recipes and the CLI ask for it; the library call keeps its old behaviour + for note in check_picture_reader(src, backend, target, archs, variant=variant, allow_stale=allow_stale_vision, + allow_none=allow_no_reader): + print("note: " + note) folder = out / (f"{version}-{target}-{backend}" + (f"-{variant}" if variant else "")) if folder.exists(): raise SystemExit(f"{folder} already exists; remove it first (packages are immutable)") @@ -218,6 +296,11 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--allow-lib", action="append", default=[], metavar="NAME", help="an imported library that really is provided by the target system (rare; named so the check passes)") ap.add_argument("--include", action="append", default=[], metavar="GLOB", help="more files, relative to --src") + ap.add_argument("--stamp-vision", type=Path, metavar="STAGE", help="write --vision-archs into STAGE/BUILD.json and exit") + ap.add_argument("--vision-archs", default="", help="with --stamp-vision: the architectures the reader was built for, e.g. '60;61;70;75;80;86;89'") + ap.add_argument("--allow-stale-vision", action="store_true", + help="package a CUDA picture reader whose BUILD.json vision_archs do not cover the package's archs (it will fail on those cards)") + ap.add_argument("--no-picture-reader", action="store_true", help="ship a macOS package without strata-vision on purpose (pictures stay off)") a = ap.parse_args(argv) if a.verify: try: @@ -233,6 +316,12 @@ def main(argv: list[str] | None = None) -> int: return 1 print(f"{a.verify}: ok ({len(component.files)} files, manifest sha256 {package_sha256(a.verify)})") return 0 + if a.stamp_vision: + if not _arch_numbers(a.vision_archs): + ap.error("--stamp-vision needs --vision-archs, for example '60;61;70;75;80;86;89'") + stamp_vision_archs(a.stamp_vision, a.vision_archs) + print(f"{a.stamp_vision / 'BUILD.json'}: vision_archs {a.vision_archs}") + return 0 for needed in ("src", "backend", "version", "out"): if getattr(a, needed) is None: ap.error(f"--{needed} is required") @@ -246,7 +335,8 @@ def main(argv: list[str] | None = None) -> int: folder = build(a.src, a.backend, a.version, a.platform or host_platform(), a.out, entry=a.entrypoint, archs=tuple(a.arch), min_driver=drivers, build_id=a.build_id, min_runtime=a.min_runtime, notes=a.notes, tree=a.tree, include=a.include, variant=a.variant, - search=a.search, allow_libs=a.allow_lib) + search=a.search, allow_libs=a.allow_lib, check_reader=True, allow_stale_vision=a.allow_stale_vision, + allow_no_reader=a.no_picture_reader) entries = [p for p in folder.rglob("*") if p.is_file()] total = sum(p.stat().st_size for p in entries) print(f"{folder} ({total / (1 << 20):.1f} MiB, {len(entries)} files, manifest sha256 {package_sha256(folder)})") diff --git a/serve/frontend.py b/serve/frontend.py index 4cf0b4fa..be376833 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -895,8 +895,18 @@ class OutputParser: # the client has no tool to run). The Responses route leaves it off: a Codex compaction request keeps its # conversation's tools in the prompt only, and its calls come back as before. self.declared_only = declared_only - self._alias = {k.replace(".", "__", 1) for k in self.schemas if isinstance(k, str) and "." in k} + # PR #3556: the native namespace__member spelling of a declared namespace.member tool is accepted without advertising a + # duplicate tool. Only an unambiguous alias counts (two namespaces can end in the same member), and an exactly declared + # name always wins over an alias. + aliases = {} + for name in self.schemas: + if isinstance(name, str) and "." in name: + namespace, member = name.rsplit(".", 1) + aliases.setdefault(f"{namespace}__{member}", set()).add(name) + self.aliases = {alias: next(iter(names)) for alias, names in aliases.items() + if len(names) == 1 and alias not in self.schemas} self.unread = 0 # #3441: `` blocks that opened like a call and were returned as text + self.unread_names: list[str] = [] # the names (first few) of those that named a tool the request did not declare # stream_tools: a tool call is also reported while it is being written - "tool_start" (its name and id) as # soon as the name is known, then "tool_args" pieces of its JSON arguments (string parameters character by # character; other types whole, once complete) - before the final "tool_call". Without it, a client sees @@ -930,7 +940,7 @@ class OutputParser: none declared, only where `declared_only` is off.""" if not self.schemas: return not self.declared_only - return name in self.schemas or name in self._alias + return name in self.schemas or name in self.aliases def _loose_open(self, after: str): """#3441: `after` (text after a ``, whitespace dropped) opens a call in a drifted form that names a @@ -945,7 +955,7 @@ class OutputParser: bare = after[1:].strip().lstrip("=").strip() if after[1:].lstrip().startswith(("=", "function")): return "wait" - if any(k.startswith(bare) for k in list(self.schemas) + list(self._alias) if isinstance(k, str)): + if any(k.startswith(bare) for k in list(self.schemas) + list(self.aliases) if isinstance(k, str)): return "wait" return None @@ -981,8 +991,10 @@ class OutputParser: while p >= 0: if self._ok_at(p): gt = self.buf.find(">", p) - name = self.buf[p + len(FUNC_START):gt if gt >= 0 else len(self.buf)] - if gt < 0 and not any(c.isspace() for c in name): + raw_name = self.buf[p + len(FUNC_START):gt if gt >= 0 else len(self.buf)] + name = raw_name.strip() + name = self.aliases.get(name, name) + if gt < 0 and re.fullmatch(r"\s*[^<>\s]*\s*", raw_name): return p, False if gt >= 0 and name in self.schemas: return p, True @@ -1082,7 +1094,7 @@ class OutputParser: def _reset_scan(self): self._call_end_checked = 0 # closing-tag search progress for the current wrapped call self.sp = 0 # how much of self.buf (the call body) the scanner has consumed - self.ss = "name" # name -> between -> str|raw -> ... -> done + self.ss = "name" # name -> between -> str|raw -> ... -> function_done -> done self.scall = None # the ToolCall being streamed (its id is reused by the final event) self.sfirst = True self.sval_started = False @@ -1116,7 +1128,11 @@ class OutputParser: b = rest.find(">", a + 10) if a >= 0 else -1 if b < 0: return out - name = rest[a + 10:b] + raw_name = rest[a + 10:b] + name = raw_name.strip() + name = self.aliases.get(name, name) + if raw_name != raw_name.strip() and name not in self.schemas: + return out self.scall = ToolCall(name=name, arguments={}) props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {} self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()} @@ -1141,9 +1157,8 @@ class OutputParser: else: self.ss = "raw" elif stripped.startswith(""): - args("}") self.sp += len("") - self.ss = "done" + self.ss = "function_done" else: return out # a tag still arriving (or trailing text): wait elif self.ss == "str": @@ -1191,7 +1206,7 @@ class OutputParser: return out def _close_scan(self) -> list[Event]: - """A streamed call that ended without a clean : close its JSON so clients can still parse it.""" + """Close streamed JSON only after its call boundary has been confirmed.""" out = [] if self.scall is None or self.ss == "done": return out @@ -1236,8 +1251,10 @@ class OutputParser: call = None try: name = body[:end].strip()[len("", 1)[0].strip() + name = self.aliases.get(name, name) if name in self.schemas: call = parse_tool_call(body[:end], self.schemas.get(name)) + call.name = name except ValueError: pass raw = self.buf[:len(CALL_START) + end + len(CALL_END)] @@ -1393,11 +1410,19 @@ class OutputParser: continue if kind == "wait": after = "" - if after and not after.startswith(FUNC_START) and not FUNC_START.startswith(after): + is_call = re.match(r"\s]+\s*)>", after) + if is_call: + raw_name = is_call.group(1) + name = raw_name.strip() + name = self.aliases.get(name, name) + if raw_name != raw_name.strip() and name not in self.schemas: + is_call = None # only declared names gain whitespace normalization + is_partial = FUNC_START.startswith(after) or re.fullmatch(r"\s]*\s*", after) + if not is_call and not is_partial: out.append(Event("content", self._track(self.buf[:i + len(CALL_START)]))) self.buf = self.buf[i + len(CALL_START):] continue - if not after.startswith(FUNC_START): + if not is_call: j = i while j > 0 and self.buf[j - 1] == "\n": j -= 1 @@ -1418,6 +1443,9 @@ class OutputParser: self.buf = self.buf[j:] return out if gt >= 0 and (nl < 0 or gt < nl) and not self._callable(after[len(FUNC_START):gt].strip()): + self.unread += 1 # logged by the server: otherwise "the model ignored my tool" is the only clue + if len(self.unread_names) < 5: + self.unread_names.append(after[len(FUNC_START):gt].strip()[:80]) out.append(Event("content", self._track(self.buf[:i + len(CALL_START)]))) self.buf = self.buf[i + len(CALL_START):] continue @@ -1452,9 +1480,12 @@ class OutputParser: i = self._wrapped_call_end() if i >= 0: drop = len(CALL_END) - if self.recover: # a batch in one wrapper: the next call follows this one's - f = function_end(self.buf) # (or opens as ) - nxt = self.buf[f:].lstrip() if f >= 0 else "" + # Only a following call opener confirms an omitted wrapper closer. + f = function_end(self.buf) + nxt = self.buf[f:].lstrip() if f >= 0 else "" + if re.match(r"\s*\s]+\s*>", nxt): + i, drop = f, 0 + if self.recover: # a batch in one wrapper: the next call follows if nxt.startswith(PARAM_START) and self._follower(nxt) == "param": at = len(self.buf) - len(nxt) self.buf = self.buf[:at] + FUNC_START + nxt[len(PARAM_START):] @@ -1496,8 +1527,12 @@ class OutputParser: return out if self.state == "call" and self.stream_tools and self.scall is not None: out += self._scan() # the output ended inside a call that was already announced - if self.ss == "done": # only its is missing: the call itself is whole + if self.ss == "function_done" and not self.buf[self.sp:].strip() and reason in (None, "stop"): + # A natural end immediately after retains native streaming recovery. + out += self._close_scan() out.append(Event("tool_call", call=self.scall)) + elif self.ss == "function_done": + out.append(Event("content", self._track(CALL_START + self.buf))) self.buf = "" self._reset_scan() return out @@ -1514,10 +1549,15 @@ class OutputParser: def _finish_call(self, body: str) -> list[Event]: """A whole call body in the template's form -> its tool_call event. With recover, one that still does not parse is the text it is instead of an error that ends the request.""" - name = body.strip()[len(FUNC_START):].split(">", 1)[0].strip() + raw_name = body.strip()[len(FUNC_START):].split(">", 1)[0] + name = raw_name.strip() + name = self.aliases.get(name, name) bare, self.bare = self.bare, False try: + if raw_name != raw_name.strip() and name not in self.schemas: + raise ValueError("whitespace tool name is not declared") call = parse_tool_call(body, self.schemas.get(name)) + call.name = name except ValueError: if not self.recover: raise diff --git a/serve/responses.py b/serve/responses.py index 2ef1dffa..8b7241b9 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -265,10 +265,6 @@ def request_tools(req: dict): "required": ["input"]} tools.append({"name": flat, "description": description, "parameters": params}) names[flat] = (namespace, name, kind) - if namespace: - # Qwen writes Codex's MCP tools as `mcp__server__tool` (the flat name it - # learned), not `mcp__server.tool`: map that spelling back as well. - names.setdefault(f"{namespace}__{name}", (namespace, name, kind)) for i, tool in enumerate(given): param = f"tools[{i}]" @@ -523,12 +519,12 @@ class Assembler: def index(self) -> int: return len(self.response["output"]) - 1 - def close(self, status="completed") -> list[dict]: + def close(self, status=None) -> list[dict]: item, self.item = self.item, None if item is None: return [] at, out = self.response["output"].index(item), [] - item["status"] = status + item["status"] = status or ("incomplete" if item["type"] in ("function_call", "custom_tool_call") else "completed") if item["type"] == "message": part = item["content"][0] out += [self.event("response.output_text.done", item_id=item["id"], output_index=at, content_index=0, @@ -606,7 +602,7 @@ class Assembler: item["input"] = value if isinstance(value, str) else json.dumps(ev.call.arguments, ensure_ascii=False) out.append(self.event("response.custom_tool_call_input.delta", item_id=item["id"], output_index=self.index, delta=item["input"])) - out += self.close() + out += self.close("completed") return out def _release(self, text: str) -> list[dict]: diff --git a/serve/server.py b/serve/server.py index 632d3c04..171e6860 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2489,29 +2489,67 @@ def network_path(path: str) -> bool: return p.startswith("\\\\") or p.startswith("\\??\\") -def vision_start_error(line: str, log=None) -> str: - """The message when the image encoder answered something other than READY. #1445: a card in the Exclusive_Process - compute mode (or one another process holds) refuses the encoder's CUDA context with "busy or unavailable"; that - cause is named instead of leaving the user the first line of a traceback. `log` is the encoder's stderr file, whose - tail is searched too (the CUDA error is printed there).""" - text = line.strip() - tail = "" +def vision_log_tail(log=None, limit: int = 16384) -> str: + """The last `limit` bytes of the encoder's stderr file (`log` is the file object it was started with; "" when there + is none or it cannot be read).""" try: name = getattr(log, "name", None) if name: with open(name, "rb") as f: f.seek(0, 2) - f.seek(max(0, f.tell() - 16384)) - tail = f.read().decode("utf-8", "replace") + f.seek(max(0, f.tell() - limit)) + return f.read().decode("utf-8", "replace") except (OSError, ValueError): pass - if "busy or unavailable" in (text + tail).lower(): + return "" + + +# What the CUDA / HIP runtimes print when the reader has no code for the card it runs on (a binary built without that +# architecture: #3669, the Windows cuda12 package's reader on a Pascal card). +_VISION_ARCH_SIGNS = ("device kernel image is invalid", "no kernel image is available", "im2col failed", + "unsupported gpu architecture", "invalid device function", "unknown gpu architecture") + + +def vision_start_error(line: str, log=None, code: int | None = None, waited: float | None = None) -> str: + """The message when the image encoder answered something other than READY. #1445: a card in the Exclusive_Process + compute mode (or one another process holds) refuses the encoder's CUDA context with "busy or unavailable"; that + cause is named instead of leaving the user the first line of a traceback. `log` is the encoder's stderr file, whose + tail is searched too (the CUDA error is printed there). An encoder that dies before it prints anything (#3645, #3444, + #3669, #3697) used to give a blank sentence: now the last lines of its stderr, its exit status (`code`) and, for a + kernel-image error, the card/architecture hint come with it. `waited`: it said nothing for that many seconds.""" + text = line.strip() + tail = vision_log_tail(log) + both = (text + chr(10) + tail).lower() + if "busy or unavailable" in both: return ("the vision encoder did not start: the GPU refused a second CUDA context (\"CUDA-capable device(s) " "is/are busy or unavailable\"). This is usually the compute mode Exclusive_Process: only one process " "may use the card, and the engine already holds it. Check with: nvidia-smi --query-gpu=compute_mode " "--format=csv; set it back with: sudo nvidia-smi -c DEFAULT (or run the encoder on another card). " "First line from the encoder: " + (text or "(none)")) - return "the vision encoder did not start: " + text + lines = [x.strip() for x in tail.splitlines() if x.strip()] + if any(sign in both for sign in _VISION_ARCH_SIGNS): + evidence = next((x for x in reversed(lines) if any(sign in x.lower() for sign in _VISION_ARCH_SIGNS)), text) + return ("the vision encoder did not start: it has no code for this graphics card (a kernel-image error: the " + "picture reader in this engine package was built for other card generations than yours). Update the " + "engine, or read pictures on the CPU (Models, Read pictures, Image encoder device: CPU; or run setup " + "again with --vision cpu). From the encoder: " + evidence[:300]) + if text: + msg = "the vision encoder did not start: " + text + elif waited is not None: + msg = f"the vision encoder did not start: it said nothing for {waited:g} s (it never reported READY)" + else: + msg = "the vision encoder did not start: it ended without saying anything" + extra = [] + if code is not None: + words = engine_exit_words(code) + if words: + extra.append(words) + shown = [x for x in lines[-3:] if x != text] + if shown: + extra.append("last lines of its log: " + " | ".join(x[:200] for x in shown)) + if extra: + msg += " (" + "; ".join(extra) + ")" + return msg class Vision: @@ -2554,12 +2592,28 @@ class Vision: # opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the # first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps # elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down) + self.max_tokens = self.token_limit(cfg) self.elastic = cfg.get("elastic") is True self.elastic_mib = int(cfg.get("elastic_mib") or 2048) self.elastic_idle_s = float(cfg.get("elastic_idle_s") or 120) if not lazy and not self.elastic: self._start() + # What a picture may become when the config does not say (setup writes the same numbers, setup.VISION): an old, hand-edited or migrated + # config without vision.max_tokens left the reader unclamped, and #3690 saw one picture become 93,700 image tokens (I7). A key that is + # there is the person's: 0 means no limit, as before. + DEFAULT_MAX_TOKENS = {"gpu": 1024, "cpu": 300} + + @staticmethod + def token_limit(cfg: dict) -> int: + """The --max-tokens of a reader config: its max_tokens, else the default of its kind (GPU 1024, CPU 300).""" + if cfg.get("max_tokens") is not None: + try: + return max(0, int(cfg["max_tokens"])) + except (TypeError, ValueError): + pass + return Vision.DEFAULT_MAX_TOKENS["gpu" if cfg.get("gpu") else "cpu"] + @staticmethod def reader_args(cfg: dict) -> list: absolute = lambda p: os.path.abspath(p) if os.path.dirname(str(p)) else p # the encoder runs in its own dir (#480) # noqa: E731 @@ -2568,8 +2622,9 @@ class Vision: args.append("--gpu") if cfg.get("threads"): args += ["--threads", str(cfg["threads"])] - if cfg.get("max_tokens"): - args += ["--max-tokens", str(cfg["max_tokens"])] + limit = Vision.token_limit(cfg) + if limit: + args += ["--max-tokens", str(limit)] if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) args += ["--min-tokens", str(cfg["min_tokens"])] return args @@ -2607,16 +2662,21 @@ class Vision: line = self._readline(VISION_READY_S, "the vision encoder did not start") except RuntimeError as e: # silent for VISION_READY_S: it was ended, and it is not left half-started self.proc, self.stopped = None, True + if VISION_READY_S: + raise RuntimeError(vision_start_error("", log, waited=VISION_READY_S)) from None raise RuntimeError(str(e)) from None if not line.startswith("READY"): proc, self.proc = self.proc, None self.stopped = True + code = proc.poll() if hasattr(proc, "poll") else None # an encoder that died by itself has its status already try: proc.kill() proc.wait(timeout=5) except (OSError, subprocess.TimeoutExpired): pass - raise RuntimeError(vision_start_error(line, self.spawn[1])) + if code is None: + code = getattr(proc, "returncode", None) + raise RuntimeError(vision_start_error(line, log, code)) self.stopped = False def _readline(self, timeout: float, what: str) -> str: @@ -2765,6 +2825,8 @@ class Vision: if key in self.cache: self.cache[key] = self.cache.pop(key) # most recently used last return self.cache[key] + if self.proc is None or self.proc.stdin is None: # an elastic encoder not started yet, or one that was unloaded + raise ValueError("the picture reader is not running") img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve" img.write_bytes(data) try: @@ -2781,6 +2843,7 @@ class Vision: raise ValueError("the image could not be read: " + (line[4:] if line.startswith("ERR") else "the vision encoder stopped")) self.cache[key] = (out, int(line.split()[1])) + self.warn_if_over_limit(self.cache[key][1]) held = {str(p) for p in keep} | {str(out)} for old in list(self.cache): # oldest first, but never one still in use if len(self.cache) <= 64: @@ -2789,6 +2852,15 @@ class Vision: self.cache.pop(old)[0].unlink(missing_ok=True) return self.cache[key] + def warn_if_over_limit(self, tokens: int) -> None: + """I7: one picture that became more than 4 times the limit is logged with the numbers, so the next report has them (the reader's own + stderr has the warm-up line). A reader built before the limit was enforced inside it (strata-vision refuses these now) still lets them by.""" + limit = getattr(self, "max_tokens", 0) + if limit and tokens > 4 * limit: + print(f"[strata] images: one picture became {tokens} image tokens, more than 4 times the limit of {limit} (vision.max_tokens); " + "the picture reader is not applying its limit. Update the engine, and send the line 'strata-vision: warmed up at N image " + "tokens' from the reader's log with the report", flush=True) + def close(self): proc, self.proc = self.proc, None if proc is None: @@ -4628,8 +4700,9 @@ class Service: if src.startswith(("http://", "https://")): src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare() with self._turn(cancel): # the encoder takes its turn with the requests (see below) + self._vision_up() # an elastic encoder is not running until a picture needs it self.vision.encode(src) - except (ValueError, OSError) as e: + except (ValueError, OSError, RuntimeError) as e: # RuntimeError: the encoder did not start why = str(e) if why is not None: print(f"[strata] a picture a tool returned was left out of the prompt: {why}", flush=True) @@ -5391,9 +5464,10 @@ class Service: print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as " f"reasoning (quoted, or the turn did not end on a stop)", flush=True) if parser.unread: + named = getattr(parser, "unread_names", None) print(f"[strata] {parser.unread} block(s) in the answer did not read as a call of a declared " "tool and went back as text (a name the request did not declare, or a form the template does " - "not use)", flush=True) + "not use)" + (f"; the names the model wrote: {', '.join(named)}" if named else ""), flush=True) if stops is not None and stops.hit is None and stops.held: yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), diff --git a/serve/test_native_tool_parser.py b/serve/test_native_tool_parser.py new file mode 100644 index 00000000..342137ad --- /dev/null +++ b/serve/test_native_tool_parser.py @@ -0,0 +1,150 @@ +"""Native tool parsing regressions; no model or GPU required.""" +import unittest +from serve.frontend import OutputParser + +CALL = "\n\n\n123\n\n\n" +TOOLS = [{"name": "mcp__files.read", "parameters": {"properties": {"path": {"type": "string"}}}}] + +class NativeTools(unittest.TestCase): + def test_unclosed_think_call_and_split_tags(self): + for streaming in (False, True): + for step in (1, 7, 4096): + parser = OutputParser(thinking=True, tools=TOOLS, stream_tools=streaming) + events = [] + text = "Inspect the file.\n" + CALL + for i in range(0,len(text),step): + events += parser.feed(text[i:i+step]) + events += parser.finish() + calls = [e.call for e in events if e.kind == "tool_call"] + self.assertEqual(len(calls),1) + self.assertEqual((calls[0].name, calls[0].arguments), ("mcp__files.read", {"path": "123"})) + self.assertEqual("".join(e.text for e in events if e.kind == "reasoning"), "Inspect the file.\n") + + + def test_whitespace_name_keeps_namespace_schema_and_stream_events(self): + for thinking, prefix in ((True, "Inspect the file.\n"), (True, "Ready.\n\n"), (False, "")): + for whitespace in (" ", "\t", " \t"): + text = prefix + CALL.replace("", + "") + for streaming in (False, True): + for step in (1, 7, 4096): + with self.subTest(thinking=thinking, prefix=prefix, whitespace=whitespace, + streaming=streaming, step=step): + parser = OutputParser(thinking=thinking, tools=TOOLS, stream_tools=streaming) + events = [] + for i in range(0, len(text), step): + events += parser.feed(text[i:i + step]) + events += parser.finish() + calls = [event.call for event in events if event.kind == "tool_call"] + self.assertEqual([(c.name, c.arguments) for c in calls], + [("mcp__files.read", {"path": "123"})]) + self.assertTrue(all(event.call.name == "mcp__files.read" + for event in events if event.kind == "tool_start")) + + + def test_padded_unknown_wrapper_stays_text_and_unpadded_stays_native(self): + for recover in (False, True): + for streaming in (False, True): + for step in (1, 7, 4096): + for name in (" missing ", "\tmissing\t", "mcp__ files", " "): + text = "" + parser = OutputParser(thinking=False, tools=TOOLS, stream_tools=streaming, recover=recover) + events = [] + for i in range(0, len(text), step): + events += parser.feed(text[i:i + step]) + events += parser.finish() + self.assertFalse(any(event.kind.startswith("tool") for event in events)) + self.assertEqual("".join(event.text for event in events if event.kind == "content"), text) + # an unpadded name nobody declared: text where tools are declared (the 0.2.2 rule, #3075); the Responses + # route of a request with no tools (Codex compaction, declared_only off) keeps it as a native call + text = "" + for tools, declared_only, expected in ((TOOLS, False, []), (TOOLS, True, []), (None, False, ["missing"])): + parser = OutputParser(thinking=False, tools=tools, stream_tools=streaming, recover=recover, + declared_only=declared_only) + events = [] + for i in range(0, len(text), step): + events += parser.feed(text[i:i + step]) + events += parser.finish() + self.assertEqual([event.call.name for event in events if event.kind == "tool_call"], expected) + + + def test_padded_unknown_second_call_is_not_announced(self): + text = CALL[:-len("")] + "" + for step in (1, 7, 4096): + parser = OutputParser(thinking=False, tools=TOOLS, stream_tools=True, recover=True) + events = [] + for i in range(0, len(text), step): + events += parser.feed(text[i:i + step]) + events += parser.finish() + self.assertEqual([event.call.name for event in events if event.kind == "tool_call"], ["mcp__files.read"]) + self.assertEqual([event.call.name for event in events if event.kind == "tool_start"], ["mcp__files.read"]) + self.assertIn("", "".join(event.text for event in events if event.kind == "content")) + + + def test_padded_bare_alias_is_declared_and_schema_typed(self): + text = CALL.replace("\n", "").replace("\n", "").replace( + "", "") + for step in (1, 7, 4096): + parser = OutputParser(thinking=False, tools=TOOLS, stream_tools=True, recover=True) + events = [] + for i in range(0, len(text), step): + events += parser.feed(text[i:i + step]) + events += parser.finish() + self.assertEqual([(event.call.name, event.call.arguments) for event in events if event.kind == "tool_call"], + [("mcp__files.read", {"path": "123"})]) + starts = [event.call.name for event in events if event.kind == "tool_start"] + self.assertEqual(starts, ["mcp__files.read"]) + + + def test_literal_call_markers_remain_reasoning_prose(self): + for prefix in ("Quote as prose.", "Use `` in docs.", "Literal marker:\n\nContinue thinking.", "Empty is prose."): + for step in (1, 7, 4096): + parser=OutputParser(thinking=True,tools=TOOLS,stream_tools=True) + text=prefix+"\n\nVisible answer." + events=[] + for i in range(0,len(text),step):events+=parser.feed(text[i:i+step]) + events+=parser.finish() + self.assertEqual(''.join(e.text for e in events if e.kind=='reasoning'),prefix) + self.assertEqual(''.join(e.text for e in events if e.kind=='content'),'Visible answer.') + self.assertFalse(any(e.kind.startswith('tool') for e in events)) + + + def test_literal_call_markers_in_content_before_genuine_call(self): + prefix = "Use `` in docs. Empty stays text." + for streaming in (False, True): + for step in (1, 7, 4096): + parser = OutputParser(thinking=False, tools=TOOLS, stream_tools=streaming) + text = prefix + "\n" + CALL + events = [] + for i in range(0, len(text), step): + events += parser.feed(text[i:i+step]) + events += parser.finish() + self.assertEqual(''.join(e.text for e in events if e.kind == 'content'), prefix) + calls = [e.call for e in events if e.kind == 'tool_call'] + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0].arguments, {'path': '123'}) + + + def test_namespace_alias_schema_and_exact_name_precedence(self): + for streaming in (False, True): + parser = OutputParser(thinking=False, tools=TOOLS, stream_tools=streaming) + events = parser.feed(CALL) + parser.finish() + call = next(e.call for e in events if e.kind == "tool_call") + self.assertEqual((call.name,call.arguments), ("mcp__files.read", {"path": "123"})) + exact = {"name": "mcp__files__read", "parameters": {"properties": {"path": {"type": "integer"}}}} + parser = OutputParser(thinking=False, tools=[*TOOLS,exact], stream_tools=streaming) + call = next(e.call for e in parser.feed(CALL)+parser.finish() if e.kind == "tool_call") + self.assertEqual((call.name,call.arguments), ("mcp__files__read", {"path": 123})) + + ambiguous = [{"name": "a.b__c"}, {"name": "a__b.c"}] + parser = OutputParser(thinking=False, tools=ambiguous) + text = CALL.replace("mcp__files__read", "a__b__c") + events = parser.feed(text) + parser.finish() + # an ambiguous alias is no declared tool: it does not route to the first namespace; it stays text + self.assertFalse(any(e.kind == "tool_call" for e in events)) + self.assertEqual("".join(e.text for e in events if e.kind == "content"), text) + self.assertEqual(parser.unread, 1) # and it is counted, so the server logs it + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_responses.py b/serve/test_responses.py index 06c2b39d..3e6188a1 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -517,6 +517,22 @@ class ToolRoundTrip(Server): self.assertIn("\nbefore\n", second_prompt) self.assertEqual(r["output"][-1]["content"][0]["text"], "The file says before.") + def test_quoted_incomplete_wrapper_is_not_a_completed_call(self): + text = "Format: " + CALL[CALL.index(""):].removesuffix("") + "and then I explain it." + self.engine.scripts = [self.tok.encode("\n\n" + text + "<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + for stream in (False, True): + code, result = self.post({"model": "m", "input": "explain the format", "tools": TOOLS, "stream": stream}) + self.assertEqual(code, 200, result) + final = result[-1]["response"] if stream else result + calls = [item for item in final["output"] if item["type"] == "function_call"] + self.assertFalse(any(item["status"] == "completed" for item in calls)) + for call in calls: + with self.assertRaises(ValueError): + json.loads(call["arguments"]) + self.assertEqual("".join(item["content"][0]["text"] for item in final["output"] + if item["type"] == "message"), text) + def test_namespace_call_written_with_double_underscore(self): # Qwen writes Codex's MCP tools in their flat `mcp__server__tool` form; Codex only # runs the call when it comes back with its namespace. @@ -533,6 +549,36 @@ class ToolRoundTrip(Server): self.assertEqual((call["namespace"], call["name"], json.loads(call["arguments"])), ("mcp__websearch", "web_search", {"query": "strata"})) + # Two canonical names share this alias. It must not invoke the first namespace. + self.engine.scripts = [self.tok.encode( + "\n\n\n\n\n<|im_end|>", + parse_special=True)] + self.engine.script = self.engine.scripts[0] + tools = [{"type": "namespace", "name": "a", "tools": [{"type": "function", "name": "b__c"}]}, + {"type": "namespace", "name": "a__b", "tools": [{"type": "function", "name": "c"}]}] + for stream in (False, True): + code, r = self.post({"model": "m", "input": "go", "tools": tools, "stream": stream}) + self.assertEqual(code, 200, r) + output = r[-1]["response"]["output"] if stream else r["output"] + # not an alias of either: with tools declared (the 0.2.2 rule, #3075) a call for an undeclared name stays text + self.assertFalse([item for item in output if item.get("type") == "function_call"], output) + self.assertIn("a__b__c", json.dumps(output)) + + # A declared exact name wins over alias spellings and keeps its string schema. + tools.append({"type": "function", "name": "a__b__c", "parameters": { + "type": "object", "properties": {"path": {"type": "string"}}}}) + self.engine.scripts = [self.tok.encode( + "\n\n\n\n\n123\n\n" + "\n<|im_end|>", parse_special=True)] + self.engine.script = self.engine.scripts[0] + for stream in (False, True): + code, r = self.post({"model": "m", "input": "go", "tools": tools, "stream": stream}) + self.assertEqual(code, 200, r) + output = r[-1]["response"]["output"] if stream else r["output"] + call, = output + self.assertNotIn("namespace", call) + self.assertEqual((call["name"], json.loads(call["arguments"])), ("a__b__c", {"path": "123"})) + def test_namespace_and_custom_calls_come_back_under_their_own_names(self): self.engine.scripts = [self.tok.encode( "\n\n\n\n\nhi\n\n" diff --git a/serve/test_server.py b/serve/test_server.py index 82922ee4..3e60dee4 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -1187,9 +1187,10 @@ class ToolCallRecovery(unittest.TestCase): def test_bare_function_without_the_wrapper(self): # corpus 395efd4c / 6e71eed4 (x5 each): with no around it - self.check(f"Writing it now.\n\n\n{self.PARAMS}", [("write", self.CALL)], "Writing it now.") - self.check(f"\n{self.PARAMS}\n", [("write", self.CALL)], "") # stray closer - self.check(f"\n{self.PARAMS}\nDone.", [("write", self.CALL)], "Done.") + for name in ("write", " write ", "\twrite\t"): + self.check(f"Writing it now.\n\n\n{self.PARAMS}", [("write", self.CALL)], "Writing it now.") + self.check(f"\n{self.PARAMS}\n", [("write", self.CALL)], "") # stray closer + self.check(f"\n{self.PARAMS}\nDone.", [("write", self.CALL)], "Done.") def test_two_calls_in_one_wrapper(self): # corpus 0912870b / 51b155c9: a batch inside one - the second call's parameters were merged into @@ -1208,6 +1209,9 @@ class ToolCallRecovery(unittest.TestCase): self.check(inline, [], inline) unknown = "\n\n1\n\n" self.check(unknown, [], unknown) + for text in (fenced, inline, unknown): + padded = text.replace("", "").replace("", "") + self.check(padded, [], padded) class ToolCallRecoveryOff(unittest.TestCase): @@ -1329,12 +1333,28 @@ class UnfinishedToolCall(unittest.TestCase): ("anthropic", False): ("end_turn", []), # call out: it has no arguments to give ("anthropic", True): ("end_turn", cut)}) + def test_quoted_incomplete_wrapper_is_not_a_call(self): + text = "Format: " + self.WHOLE[len("\n\n"):].removesuffix("") + "and then I explain it." + answers = self.answers("\n\n" + text) + for api, stop in (("openai", "stop"), ("anthropic", "end_turn")): + self.assertEqual(answers[api, False], (stop, [])) + self.assertEqual(answers[api, True][0], stop) + with self.assertRaises(ValueError): + json.loads(answers[api, True][1]) + def test_a_call_cut_at_the_token_limit(self): """The same cut by max_tokens: "length" / "max_tokens", and the whole (non-streamed) answers leave the call out in both APIs.""" - a = self.answers(self.CUT + "rest of the file, never reached" * 40, max_tokens=len(self.CUT)) - self.assertEqual((a["openai", False], a["anthropic", False]), (("length", []), ("max_tokens", []))) - self.assertEqual((a["openai", True][0], a["anthropic", True][0]), ("length", "max_tokens")) + cases = ((self.CUT + "rest of the file, never reached" * 40, len(self.CUT)), + (self.WHOLE, len(self.WHOLE) - len(""))) + for script, limit in cases: + with self.subTest(limit=limit): + a = self.answers(script, max_tokens=limit) + self.assertEqual((a["openai", False], a["anthropic", False]), (("length", []), ("max_tokens", []))) + self.assertEqual((a["openai", True][0], a["anthropic", True][0]), ("length", "max_tokens")) + for api in ("openai", "anthropic"): + with self.assertRaises(ValueError): + json.loads(a[api, True][1]) def test_collect_keeps_calls_whose_arguments_parse(self): from serve.server import openai_collect diff --git a/serve/test_tool_call_envelope.py b/serve/test_tool_call_envelope.py index 75ec2ad2..cf3275b3 100644 --- a/serve/test_tool_call_envelope.py +++ b/serve/test_tool_call_envelope.py @@ -91,6 +91,14 @@ class OnlyDeclaredTools(unittest.TestCase): self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")]) self.assertEqual(text(evs), "I will check.\n" + raw) + def test_an_unparsed_call_is_counted_and_named_for_the_log(self): + """T1 rail: a call that went back as text is no longer silent; the server prints its count and the names the model wrote.""" + raw = body("", "symbol", "600076") + evs, p = run("I will check."+chr(10) + raw, 4, tools=TOOLS) + self.assertEqual((p.unread, p.unread_names), (1, ["get_indicators"])) + evs, p = run(body("", "cmd", "ls"), 4, tools=TOOLS) # a declared call is no unread call + self.assertEqual((p.unread, p.unread_names), (0, [])) + def test_a_declared_call_after_an_undeclared_one_is_still_a_call(self): raw = body("") + "\n" + body("", "cmd", "ls") evs, p = run(raw, 5, tools=TOOLS) @@ -99,7 +107,8 @@ class OnlyDeclaredTools(unittest.TestCase): def test_the_responses_spelling_of_a_namespace_tool_counts(self): evs, p = run(body("", "q", "x"), 4, tools=TOOLS) - self.assertEqual(calls(evs), [("ns__web_search", {"q": "x"})]) + # PR #3556: the call carries the declared spelling (ns.web_search), the one the client offered, not the model's flat one + self.assertEqual(calls(evs), [("ns.web_search", {"q": "x"})]) def test_no_tools_declared(self): raw = body("", "q", "2+2") diff --git a/serve/test_tool_call_unclosed.py b/serve/test_tool_call_unclosed.py new file mode 100644 index 00000000..38c2be65 --- /dev/null +++ b/serve/test_tool_call_unclosed.py @@ -0,0 +1,94 @@ +"""A missing wrapper closer ends before a following call, but prose alone does not confirm a call. + +A call's own separates it from the next wrapper without merging their arguments. +Parameter values may still contain call-format tags; recovery batches stay opt-in. + + python -m unittest serve.test_tool_call_unclosed -v +""" +import json +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from serve.frontend import OutputParser # noqa: E402 + +TOOLS = [{"name": "read", "parameters": {"properties": {"path": {"type": "string"}}}}, + {"name": "write", "parameters": {"properties": {"path": {"type": "string"}, "content": {"type": "string"}}}}] +READ = "\n\na.py\n\n" +WRITE = "\n\nb.py\n\n\nx = 1\n\n" + + +def run(text, stream_tools, recover, step): + p = OutputParser(thinking=False, tools=TOOLS, stream_tools=stream_tools, recover=recover) + evs = [] + for i in range(0, len(text), step): # fed in small pieces, as a stream arrives + evs += p.feed(text[i:i + step]) + evs += p.finish("stop") + calls = [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"] + if stream_tools and not calls: + arguments = "".join(e.text for e in evs if e.kind == "tool_args") + if arguments: + try: + json.loads(arguments) + except ValueError: + pass + else: + raise AssertionError("an unconfirmed call has complete streamed arguments") + return calls, "".join(e.text for e in evs if e.kind == "content") + + +class UnclosedCall(unittest.TestCase): + def check(self, text, want_calls, want_content=""): + for stream_tools in (False, True): + for recover in (False, True): + for step in (1, 3, 7, 4096): + with self.subTest(stream_tools=stream_tools, recover=recover, step=step): + calls, content = run(text, stream_tools, recover, step) + self.assertEqual(calls, want_calls) + self.assertEqual(content.strip(), want_content) + + def test_closed_calls_are_unchanged(self): + self.check("\n" + READ + "\n\n\n" + WRITE + "\n", + [("read", {"path": "a.py"}), ("write", {"path": "b.py", "content": "x = 1"})]) + + def test_a_second_call_after_an_unclosed_one_is_its_own_call(self): + self.check("\n" + READ + "\n\n" + WRITE + "\n", + [("read", {"path": "a.py"}), ("write", {"path": "b.py", "content": "x = 1"})]) + + def test_quoted_incomplete_wrapper_stays_literal(self): + text = "Format: \n" + READ + "\nand then I explain it." + self.check(text, [], text) + + def test_following_literal_marker_does_not_complete_an_unclosed_call(self): + text = "\n" + READ + "\n is a format marker." + self.check(text, [], text) + + def test_omitted_wrapper_recovers_only_on_a_natural_stop(self): + for closed in (True, False): + text = "\n" + READ + ("\n" if closed else "") + for reason in (None, "stop", "length", "cancel", "disconnect"): + for step in (1, 7, 4096): + with self.subTest(closed=closed, reason=reason, step=step): + p = OutputParser(thinking=False, tools=TOOLS, stream_tools=True) + events = [] + for offset in range(0, len(text), step): + events += p.feed(text[offset:offset + step]) + events += p.finish(reason) + calls = [e for e in events if e.kind == "tool_call"] + complete = closed or reason in (None, "stop") + self.assertEqual(len(calls), int(complete)) + if not complete: + with self.assertRaises(ValueError): + json.loads("".join(e.text for e in events if e.kind == "tool_args")) + + def test_a_value_that_holds_the_tags_still_ends_at_the_calls_own_closer(self): + value = "a and a in a string" + call = ("\n\n\nc.py\n\n\n" + value + + "\n\n\n") + self.check(call, [("write", {"path": "c.py", "content": value})]) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_vision_start_error.py b/serve/test_vision_start_error.py new file mode 100644 index 00000000..7e5fc22e --- /dev/null +++ b/serve/test_vision_start_error.py @@ -0,0 +1,78 @@ +"""I3 (tools and images review, 2026-10-22): a picture reader that dies before it prints used to say only "the vision +encoder did not start: " (#3645, #3444, #3697, #3669). The message now carries the tail of its stderr, its exit status +and, for a kernel-image error, the card/architecture hint. + + python -m serve.test_vision_start_error +""" +import io +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import serve.server as server + + +def log_with(text): + f = tempfile.NamedTemporaryFile("w+", suffix=".log", delete=False) + f.write(text) + f.flush() + return f + + +class StartError(unittest.TestCase): + def test_an_empty_line_is_never_a_blank_sentence(self): + m = server.vision_start_error("") + self.assertNotEqual(m.strip(), "the vision encoder did not start:") + self.assertIn("without saying anything", m) + + def test_exit_code_and_stderr_tail_come_with_it(self): + f = log_with("loading mmproj\nggml_cuda_init: failed\nsome last words\n") + self.addCleanup(lambda: (f.close(), Path(f.name).unlink())) + m = server.vision_start_error("", f, 3) + self.assertIn("exit code 3", m) + self.assertIn("some last words", m) + self.assertIn("ggml_cuda_init: failed", m) + + def test_a_windows_crash_status_is_named(self): + m = server.vision_start_error("", None, 0xC0000135) + self.assertIn("0xC0000135", m) + + def test_kernel_image_error_names_the_card_and_the_way_out(self): + for sign in ("CUDA error: device kernel image is invalid", "IM2COL failed", "no kernel image is available for execution"): + with self.subTest(sign=sign): + f = log_with("warm-up\n" + sign + "\n") + try: + m = server.vision_start_error("", f, 1) + finally: + f.close() + Path(f.name).unlink() + self.assertIn("no code for this graphics card", m) + self.assertIn("CPU", m) + self.assertIn(sign.split(":")[-1].strip()[:12], m) + + def test_a_timeout_names_the_seconds_and_the_last_log_line(self): + f = log_with("loading weights\nstill loading the projector\n") + self.addCleanup(lambda: (f.close(), Path(f.name).unlink())) + m = server.vision_start_error("", f, waited=300) + self.assertIn("said nothing for 300 s", m) + self.assertIn("still loading the projector", m) + + def test_the_reader_that_ends_before_READY_raises_with_its_exit_code(self): + proc = SimpleNamespace(stdin=io.StringIO(), stdout=io.StringIO(""), kill=lambda: None, wait=lambda timeout=None: 0, + poll=lambda: 7, returncode=7) + v = server.Vision.__new__(server.Vision) + v.spawn = (["strata-vision"], None, None) + v.dir = Path(tempfile.gettempdir()) + with mock.patch.object(server, "popen", lambda *a, **k: proc): + with self.assertRaises(RuntimeError) as cm: + v._start() + self.assertIn("exit code 7", str(cm.exception)) + + def test_a_normal_message_is_unchanged(self): + self.assertEqual(server.vision_start_error("ERR no mmproj\n"), "the vision encoder did not start: ERR no mmproj") + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_vision_token_limit.py b/serve/test_vision_token_limit.py new file mode 100644 index 00000000..5cb69d51 --- /dev/null +++ b/serve/test_vision_token_limit.py @@ -0,0 +1,71 @@ +"""I7 (tools and images review, 2026-10-22): a picture reader without vision.max_tokens in its config was unclamped, and #3690 saw one +picture become 93,700 image tokens. The server gives every reader a limit (GPU 1024, CPU 300) unless the config names one, and logs a +picture that came back over 4 times the limit. + + python -m unittest serve.test_vision_token_limit +""" +import io +import unittest +from contextlib import redirect_stdout + +import serve.server as server + +BASE = {"exe": "strata-vision", "mmproj": "m.gguf", "model": "t.gguf"} + + +def limit_of(cfg): + args = server.Vision.reader_args(cfg) + return int(args[args.index("--max-tokens") + 1]) if "--max-tokens" in args else None + + +class TokenLimit(unittest.TestCase): + def test_a_config_without_max_tokens_gets_the_default_of_its_kind(self): + self.assertEqual(limit_of({**BASE, "gpu": True}), 1024) + self.assertEqual(limit_of({**BASE, "gpu": False}), 300) + self.assertEqual(limit_of(dict(BASE)), 300) + + def test_a_limit_the_person_set_is_kept_not_capped(self): + self.assertEqual(limit_of({**BASE, "gpu": True, "max_tokens": 4096}), 4096) + self.assertEqual(limit_of({**BASE, "max_tokens": "512"}), 512) + + def test_zero_still_means_no_limit(self): + self.assertIsNone(limit_of({**BASE, "gpu": True, "max_tokens": 0})) + + def test_an_unreadable_value_falls_back_to_the_default(self): + self.assertEqual(limit_of({**BASE, "gpu": True, "max_tokens": "lots"}), 1024) + + def test_min_tokens_is_unchanged(self): + args = server.Vision.reader_args({**BASE, "gpu": True, "min_tokens": 768}) + self.assertEqual(args[args.index("--min-tokens") + 1], "768") + + +class Warn(unittest.TestCase): + def reader(self, limit): + v = server.Vision.__new__(server.Vision) + v.max_tokens = limit + return v + + def said(self, limit, tokens): + out = io.StringIO() + with redirect_stdout(out): + self.reader(limit).warn_if_over_limit(tokens) + return out.getvalue() + + def test_93700_tokens_under_a_1024_limit_is_logged_with_the_numbers(self): + text = self.said(1024, 93700) + self.assertIn("93700 image tokens", text) + self.assertIn("limit of 1024", text) + self.assertIn("warmed up at N image tokens", text) + + def test_a_picture_within_four_times_the_limit_is_quiet(self): + self.assertEqual(self.said(1024, 1024), "") + self.assertEqual(self.said(1024, 4096), "") + + def test_no_limit_no_warning(self): + self.assertEqual(self.said(0, 93700), "") + v = server.Vision.__new__(server.Vision) # a reader object made without the attribute (older tests) + v.warn_if_over_limit(93700) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_vision_tool_image.py b/serve/test_vision_tool_image.py new file mode 100644 index 00000000..eab440c3 --- /dev/null +++ b/serve/test_vision_tool_image.py @@ -0,0 +1,75 @@ +"""I6 (tools and images review, 2026-10-22): a picture a tool returned, with an elastic image encoder that is not running, +used to write to a process that did not exist (AttributeError, then a 400 "malformed request" that every later turn of the +conversation repeated). It starts the encoder like a picture of the user does; when it cannot start, the picture becomes +an "[image omitted: why]" note. + + python -m serve.test_vision_tool_image +""" +import tempfile +import unittest +from unittest import mock +from pathlib import Path + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, Service, Vision +from serve.test_vision_elastic import ElasticVision +from serve.test_vram import VramEngine + +ROOT = Path(__file__).resolve().parents[1] + + +def tool_turn(): + return [{"role": "user", "content": "look at it"}, + {"role": "tool", "tool_call_id": "t1", "content": [{"type": "image", "source": "x.png"}]}] + + +class FailingStart(ElasticVision): + def restart(self): + raise RuntimeError("the vision encoder did not start: it ended without saying anything (exit code 1)") + + +class ToolImage(unittest.TestCase): + def service(self, vision): + tok = ByteTokenizer() + engine = VramEngine(tok) + engine.loaded = True + return Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=vision) + + def test_an_elastic_encoder_is_started_for_a_tool_picture(self): + vision = ElasticVision(tempfile.mkdtemp()) + svc = self.service(vision) + messages = tool_turn() + svc._note_unreadable_tool_images(messages) + self.assertEqual(vision.starts, 1) + self.assertEqual(messages[1]["content"][0]["type"], "image") # kept: it was read + svc._note_unreadable_tool_images(messages) # the running encoder is used as it is + self.assertEqual(vision.starts, 1) + + def test_an_encoder_that_cannot_start_leaves_a_note_not_a_400(self): + svc = self.service(FailingStart(tempfile.mkdtemp())) + messages = tool_turn() + svc._note_unreadable_tool_images(messages) # no exception + part = messages[1]["content"][0] + self.assertEqual(part["type"], "text") + self.assertIn("[image omitted:", part["text"]) + self.assertIn("did not start", part["text"]) + + def test_prepare_survives_a_tool_picture_with_an_elastic_encoder(self): + vision = ElasticVision(tempfile.mkdtemp()) + svc = self.service(vision) + self.addCleanup(lambda: getattr(svc.embeddings, "path", None) and svc.embeddings.path.unlink(missing_ok=True)) + svc.prepare(tool_turn(), None, {}) + self.assertEqual(vision.starts, 1) + + def test_encode_without_a_running_reader_is_a_clear_value_error(self): + v = Vision.__new__(Vision) + v.dir, v.cache, v.proc = Path(tempfile.mkdtemp()), {}, None + import threading + v.lock = threading.Lock() + with mock.patch.object(Vision, "normalize", return_value=b"png"), self.assertRaises(ValueError) as cm: + v.encode(b"bytes") + self.assertIn("picture reader is not running", str(cm.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_picture_reader_package.py b/tests/terminal/test_picture_reader_package.py new file mode 100644 index 00000000..d80c6563 --- /dev/null +++ b/tests/terminal/test_picture_reader_package.py @@ -0,0 +1,94 @@ +"""I1 / I2 (tools and images review, 2026-10-22): the picture reader in an engine package must run on every card and Mac the package does. + +#3669: the Windows cuda12 package reused a strata-vision.exe built before Pascal support; the engine ran on a P100 and the reader stopped +with "device kernel image is invalid". #3697: a macOS package with no reader at all. These tests need no GPU and no toolkit.""" + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "packaging")) +import package_engine # noqa: E402 + +CUDA12 = ("sm_60", "sm_61", "sm_70", "sm_75", "sm_80", "sm_86", "sm_89", "compute_89") +CUDA13 = ("sm_75", "sm_86", "sm_89", "sm_120", "compute_120") + + +class ReaderCheck(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.src = Path(self.tmp.name) + (self.src / "strata").write_text("x") + + def reader(self, vision_archs=None): + (self.src / "strata-vision").write_text("x") + data = {"version": "0.2.3"} + if vision_archs is not None: + data["vision_archs"] = vision_archs + (self.src / "BUILD.json").write_text(json.dumps(data)) + + def check(self, backend, target, archs, **kw): + return package_engine.check_picture_reader(self.src, backend, target, archs, **kw) + + def test_a_reader_with_no_recorded_archs_is_refused_for_cuda12(self): + self.reader() + with self.assertRaises(SystemExit) as cm: + self.check("cuda", "windows-x86_64", CUDA12, variant="cuda12") + self.assertIn("vision_archs", str(cm.exception)) + self.assertIn("3669", str(cm.exception)) + + def test_a_cuda13_reader_does_not_pass_for_the_pascal_package(self): + self.reader("75;86;89;120") + with self.assertRaises(SystemExit) as cm: + self.check("cuda", "windows-x86_64", CUDA12, variant="cuda12") + for n in ("sm_60", "sm_61", "sm_70"): + self.assertIn(n, str(cm.exception)) + + def test_a_reader_built_for_the_packages_archs_passes(self): + self.reader("60;61;70;75;80;86;89") + self.assertEqual(self.check("cuda", "linux-x86_64", CUDA12, variant="cuda12"), []) + self.reader(["75", "sm_86", "89-real", 120]) + self.assertEqual(self.check("cuda", "windows-x86_64", CUDA13, variant="cuda13"), []) + + def test_allow_stale_vision_packages_it_and_says_what_is_missing(self): + self.reader("75;86;89;120") + notes = self.check("cuda", "windows-x86_64", CUDA12, variant="cuda12", allow_stale=True) + self.assertIn("sm_60", notes[0]) + + def test_a_cuda_package_without_a_reader_is_text_only_not_an_error(self): + notes = self.check("cuda", "linux-x86_64", CUDA13, variant="cuda13") + self.assertIn("text only", notes[0]) + + def test_a_macos_package_without_a_reader_is_refused(self): + with self.assertRaises(SystemExit) as cm: + self.check("metal", "macos-arm64", ()) + self.assertIn("build_vision_mac.sh", str(cm.exception)) + self.assertIn("pictures are off", self.check("metal", "macos-arm64", (), allow_none=True)[0]) + + def test_a_macos_package_with_a_reader_passes(self): + self.reader() + self.assertEqual(self.check("metal", "macos-arm64", ()), []) + + def test_build_runs_the_check_only_when_asked(self): + self.reader("75;86;89;120") + out = Path(self.tmp.name) / "out" + out.mkdir() + with self.assertRaises(SystemExit) as cm: + package_engine.build(self.src, "cuda", "0.2.3", "linux-x86_64", out, archs=CUDA12, variant="cuda12", build_id="t", + check_reader=True) + self.assertIn("picture reader", str(cm.exception)) + + def test_stamp_vision_writes_the_record(self): + (self.src / "BUILD.json").write_text(json.dumps({"version": "0.2.3", "archs": "60;61"})) + self.assertEqual(package_engine.main(["--stamp-vision", str(self.src), "--vision-archs", "60;61;70"]), 0) + data = json.loads((self.src / "BUILD.json").read_text()) + self.assertEqual(data["vision_archs"], "60;61;70") + self.assertEqual(data["archs"], "60;61") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 9cc8d321..feae4145 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -272,6 +272,11 @@ int main(int argc, char** argv) { } std::fprintf(stderr, "strata-vision: warmed up at %d image tokens in %.1f s\n", warm_tokens, std::chrono::duration(std::chrono::steady_clock::now() - warm_t0).count()); + // I7 (#3690): a picture that became 93,700 image tokens under --max-tokens 1024. The limit is not applied by this build of mtmd for + // this model, and the log line above is the evidence to ask for. + if (max_tokens > 0 && warm_tokens > max_tokens + max_tokens / 8) + std::fprintf(stderr, "strata-vision: WARNING the warm-up picture became %d image tokens, over the limit of %d (--max-tokens): " + "the limit is not applied for this model; pictures over it are refused\n", warm_tokens, max_tokens); mtmd_input_chunks_free(chunks); if (bm) mtmd_bitmap_free(bm); } @@ -308,6 +313,10 @@ int main(int argc, char** argv) { const mtmd_decoder_pos last = mtmd_image_tokens_get_decoder_pos(it, 0, (size_t) n - 1); const int nx = (int) last.x + 1, ny = (int) last.y + 1; if (nx * ny != n) err = "the image grid is not rectangular (" + std::to_string(n) + " tokens)"; + // never silently produce many times the budget (I7, #3690): over the limit (a rounding margin of an eighth) the picture is refused + if (err.empty() && max_tokens > 0 && n > max_tokens + max_tokens / 8) + err = "the picture became " + std::to_string(n) + " image tokens, over the limit of " + std::to_string(max_tokens) + + " (vision.max_tokens); send a smaller picture or raise the limit"; const float* embd = mtmd_get_output_embd(ctx); FILE* f = err.empty() ? std::fopen(out.c_str(), "wb") : nullptr; if (err.empty() && !f) err = "cannot write " + out;