feat(ui): add symbolic math support to JS sandbox via nerdamer (#25948)
* feat(ui): add symbolic math support to JS sandbox via nerdamer Preload nerdamer (with decimal.js) in the sandboxed worker, exposing the `nerdamer` global for symbolic computation: simplify, expand, factor, diff, integrate, solve, laplace, ilt, limit, partfrac, gcd/lcm, roots, coefficients, and more. Mirrors the math.js integration pattern from the feature/sandbox-symbolic-math branch, but uses nerdamer for a lighter, more focused symbolic math engine. * Update sandbox-harness.ts * docs(ui): update sandbox tool description with detailed nerdamer usage guide * Clarify nerdamer usage in sandbox tool description Updated the description of the sandbox tool to clarify usage of nerdamer. * ui: build nerdamer sandbox prelude from vendored source Replace the vendored all.min.js with the readable nerdamer-prime source and its two bundled deps (big-integer, decimal.js), licenses included. A vite plugin bundles and minifies them at build time with the upstream esbuild flags, exposed as virtual:nerdamer and imported lazily on first sandbox use. The vendors package.json pins commonjs so the project level type: module does not break esbuild format detection. The harness gains a CSP removing network egress from the worker, and browser tests cover the prelude, exact arithmetic, the fetch block and the timeout. Upstream snapshot: together-science/nerdamer-prime@1936145 * feat(ui): make symbolic math (nerdamer) a user-toggleable setting - Add SYMBOLIC_MATH_ENABLED setting key and registry entry (checkbox, default false) - Convert SANDBOX_TOOL_DEFINITION to buildSandboxToolDefinition(includeSymbolicMath) so the tool description includes/excludes nerdamer API docs dynamically - Cache sandbox harness per variant ('nerdamer' / 'plain') for instant toggle - Deprecate SANDBOX_TOOL_DEFINITION constant alias for backward compatibility - Update tools store to pass symbolic math config into tool definition * docs(ui): tell LLM to list nerdamer functions first, do not guess * test(ui): enable symbolic math in sandbox tests via settingsStore config * style(ui): fix formatting for tools.svelte.ts --------- Co-authored-by: Pascal <admin@serveurperso.com>
This commit is contained in:
@@ -276,7 +276,7 @@ export { MCPService } from './mcp.service';
|
||||
* - **toolsStore**: Exposes the tool definition when the sandbox is enabled
|
||||
* - **agenticStore**: Dispatches ToolSource.FRONTEND calls here
|
||||
*
|
||||
* @see SANDBOX_TOOL_DEFINITION in constants/sandbox.ts - tool schema sent to the LLM
|
||||
* @see buildSandboxToolDefinition in constants/sandbox.ts - tool schema sent to the LLM
|
||||
* @see agenticStore in stores/agentic.svelte.ts - tool dispatch
|
||||
*/
|
||||
export { SandboxService } from './sandbox.service';
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
import { NEWLINE } from '$lib/constants';
|
||||
import WORKER_SHIM from './sandbox-worker.js?raw';
|
||||
|
||||
/**
|
||||
* CSP for the harness document, inherited by the blob worker. connect-src
|
||||
* falls back to default-src, removing network egress for model and vendored
|
||||
* code. 'unsafe-eval' is required by the worker's AsyncFunction constructor,
|
||||
* 'unsafe-inline' by the inline script below, worker-src by the blob worker.
|
||||
*/
|
||||
const HARNESS_CSP = `default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; worker-src blob:`;
|
||||
|
||||
/**
|
||||
* Harness loaded as srcdoc into a sandboxed iframe (allow-scripts only).
|
||||
* The opaque origin is the security boundary: no access to the app origin,
|
||||
* its storage or its API. The harness spawns a worker so model code never
|
||||
* runs on a main thread, which makes the parent timeout enforceable by
|
||||
* removing the iframe.
|
||||
* removing the iframe. The prelude runs in the worker before the shim,
|
||||
* exposing globals such as `nerdamer` to model code.
|
||||
*/
|
||||
export const SANDBOX_HARNESS_HTML = `<!doctype html><script>
|
||||
const SHIM = ${JSON.stringify(WORKER_SHIM)};
|
||||
export function buildSandboxHarness(preludeJs: string): string {
|
||||
return `<!doctype html><meta http-equiv="Content-Security-Policy" content="${HARNESS_CSP}"><script>
|
||||
const SHIM = ${JSON.stringify(preludeJs + NEWLINE + WORKER_SHIM)};
|
||||
addEventListener('message', (event) => {
|
||||
const respond = (payload) => parent.postMessage(payload, '*');
|
||||
let worker;
|
||||
@@ -23,3 +34,4 @@ addEventListener('message', (event) => {
|
||||
worker.postMessage({ code: event.data.code });
|
||||
});
|
||||
</script>`;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,9 @@ self.onmessage = async (event) => {
|
||||
const reply = { logs, result: null, error: null };
|
||||
try {
|
||||
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
||||
const value = await new AsyncFunction(event.data.code)();
|
||||
// The prelude bundled ahead of this shim defines self.nerdamer,
|
||||
// passed into the execution scope as the `nerdamer` parameter.
|
||||
const value = await new AsyncFunction('nerdamer', event.data.code)(self.nerdamer);
|
||||
if (value !== undefined) reply.result = fmt(value);
|
||||
} catch (err) {
|
||||
reply.error = err instanceof Error ? err.stack || err.message : String(err);
|
||||
|
||||
@@ -7,9 +7,32 @@ import {
|
||||
SANDBOX_TOOL_NAME,
|
||||
SANDBOX_TRUNCATION_NOTICE
|
||||
} from '$lib/constants';
|
||||
import { SANDBOX_HARNESS_HTML } from './sandbox-harness';
|
||||
import { buildSandboxHarness } from './sandbox-harness';
|
||||
import { config } from '$lib/stores/settings.svelte';
|
||||
import type { ToolExecutionResult } from '$lib/types';
|
||||
|
||||
/** Cached harnesses keyed by whether nerdamer is included. */
|
||||
const harnessCache: Record<string, string> = {};
|
||||
|
||||
/**
|
||||
* Build the sandbox harness. When symbolic math is enabled, loads the
|
||||
* nerdamer prelude lazily; otherwise builds a plain harness with an empty
|
||||
* prelude. Cached per variant so toggling the setting is instant.
|
||||
*/
|
||||
async function getHarness(): Promise<string> {
|
||||
const enabled = !!config().symbolicMathEnabled;
|
||||
const key = enabled ? 'nerdamer' : 'plain';
|
||||
if (!harnessCache[key]) {
|
||||
if (enabled) {
|
||||
const { default: nerdamerJs } = await import('virtual:nerdamer');
|
||||
harnessCache[key] = buildSandboxHarness(nerdamerJs);
|
||||
} else {
|
||||
harnessCache[key] = buildSandboxHarness('');
|
||||
}
|
||||
}
|
||||
return harnessCache[key];
|
||||
}
|
||||
|
||||
interface SandboxReply {
|
||||
logs?: unknown;
|
||||
result?: unknown;
|
||||
@@ -45,20 +68,22 @@ export class SandboxService {
|
||||
* timeout or abort. Removing the iframe terminates the worker
|
||||
* at the browser level, so runaway code cannot outlive it.
|
||||
*/
|
||||
static executeTool(
|
||||
static async executeTool(
|
||||
toolName: string,
|
||||
params: Record<string, unknown>,
|
||||
signal?: AbortSignal
|
||||
): Promise<ToolExecutionResult> {
|
||||
if (toolName !== SANDBOX_TOOL_NAME) {
|
||||
return Promise.resolve({ content: `Unknown frontend tool: ${toolName}`, isError: true });
|
||||
return { content: `Unknown frontend tool: ${toolName}`, isError: true };
|
||||
}
|
||||
|
||||
const code = typeof params.code === 'string' ? params.code : '';
|
||||
if (!code) {
|
||||
return Promise.resolve({ content: 'Missing required parameter: code', isError: true });
|
||||
return { content: 'Missing required parameter: code', isError: true };
|
||||
}
|
||||
|
||||
const harness = await getHarness();
|
||||
|
||||
const requested = Number(params.timeout_ms);
|
||||
const timeoutMs =
|
||||
Number.isFinite(requested) && requested > 0
|
||||
@@ -69,7 +94,7 @@ export class SandboxService {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.setAttribute('sandbox', 'allow-scripts');
|
||||
iframe.style.display = 'none';
|
||||
iframe.srcdoc = SANDBOX_HARNESS_HTML;
|
||||
iframe.srcdoc = harness;
|
||||
|
||||
let settled = false;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user