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 { parseToolArgs } from './_shared';
9 import { BuiltInTool } from '$lib/enums';
10 import type { AgenticSection } from '$lib/utils';
12 export type RunJavascriptMeta = {
15 errorMessage?: string;
18 export function parseRunJavascriptMeta(section: AgenticSection): RunJavascriptMeta | null {
19 const args = parseToolArgs(BuiltInTool.RUN_JAVASCRIPT, section);
21 if (!args) return null;
23 const code = typeof args.code === 'string' ? args.code : '';
25 if (!code) return null;
27 const timeoutRaw = Number(args.timeout_ms);
28 const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined;
30 let errorMessage: string | undefined;
32 const toolResultString = section.toolResult;
34 if (toolResultString) {
35 // Branches matter here: a JSON object can carry `error`, but a
36 // JSON array always represents successful output (sandbox returns
37 // the array of values). Only when the result isn't a JSON object
38 // do we scan raw lines for the `Error:` prefix.
39 let parsedObject: Record<string, unknown> | null = null;
42 const parsed: unknown = JSON.parse(toolResultString);
44 if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
45 parsedObject = parsed as Record<string, unknown>;
51 if (typeof parsedObject?.error === 'string') {
52 errorMessage = parsedObject.error;
53 } else if (!parsedObject) {
54 const errorLine = toolResultString
56 .map((line) => line.trim())
57 .find((line) => line.startsWith('Error:'));
59 if (errorLine) errorMessage = errorLine.slice('Error:'.length).trim();
63 return { code, errorMessage, timeoutMs };