1 // Meta parser for `run_javascript` tool calls. Reads the JS code and
2 // optional timeout from args (strict parsing) and surfaces any error
3 // from the result blob. SandboxService.formatReply emits a JSON object
4 // containing an `error` field on failure, but a partial/non-JSON
5 // failure renders as a flat line beginning with `Error:`. Both shapes
8 import { BuiltInTool } from '$lib/enums';
9 import type { AgenticSection } from '$lib/utils';
10 import { parseToolArgs } from './_shared';
12 export type RunJavascriptMeta = {
15 errorMessage?: string;
18 export function parseRunJavascriptMeta(section: AgenticSection): RunJavascriptMeta | null {
19 const args = parseToolArgs(BuiltInTool.RUN_JAVASCRIPT, section);
20 if (!args) return null;
22 const code = typeof args.code === 'string' ? args.code : '';
23 if (!code) return null;
25 const timeoutRaw = Number(args.timeout_ms);
26 const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined;
28 let errorMessage: string | undefined;
29 const toolResultString = section.toolResult;
30 if (toolResultString) {
31 // Branches matter here: a JSON object can carry `error`, but a
32 // JSON array always represents successful output (sandbox returns
33 // the array of values). Only when the result isn't a JSON object
34 // do we scan raw lines for the `Error:` prefix.
35 let parsedObject: Record<string, unknown> | null = null;
37 const parsed: unknown = JSON.parse(toolResultString);
38 if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
39 parsedObject = parsed as Record<string, unknown>;
44 if (typeof parsedObject?.error === 'string') {
45 errorMessage = parsedObject.error;
46 } else if (!parsedObject) {
47 const errorLine = toolResultString
49 .map((line) => line.trim())
50 .find((line) => line.startsWith('Error:'));
51 if (errorLine) errorMessage = errorLine.slice('Error:'.length).trim();
55 return { code, timeoutMs, errorMessage };