]> git.djapps.eu Git - pkg/ggml/sources/llama.cpp/blob
a74153d4dcd35656ed8778e813e50d67e8962208
[pkg/ggml/sources/llama.cpp] /
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
6 // are handled.
7
8 import { parseToolArgs } from './_shared';
9 import { BuiltInTool } from '$lib/enums';
10 import type { AgenticSection } from '$lib/utils';
11
12 export type RunJavascriptMeta = {
13 code: string;
14 timeoutMs?: number;
15 errorMessage?: string;
16 };
17
18 export function parseRunJavascriptMeta(section: AgenticSection): RunJavascriptMeta | null {
19 const args = parseToolArgs(BuiltInTool.RUN_JAVASCRIPT, section);
20
21 if (!args) return null;
22
23 const code = typeof args.code === 'string' ? args.code : '';
24
25 if (!code) return null;
26
27 const timeoutRaw = Number(args.timeout_ms);
28 const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined;
29
30 let errorMessage: string | undefined;
31
32 const toolResultString = section.toolResult;
33
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;
40
41 try {
42 const parsed: unknown = JSON.parse(toolResultString);
43
44 if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
45 parsedObject = parsed as Record<string, unknown>;
46 }
47 } catch {
48 parsedObject = null;
49 }
50
51 if (typeof parsedObject?.error === 'string') {
52 errorMessage = parsedObject.error;
53 } else if (!parsedObject) {
54 const errorLine = toolResultString
55 .split('\n')
56 .map((line) => line.trim())
57 .find((line) => line.startsWith('Error:'));
58
59 if (errorLine) errorMessage = errorLine.slice('Error:'.length).trim();
60 }
61 }
62
63 return { code, errorMessage, timeoutMs };
64 }