Skip to content
pi-c Artifact [c59fb07906]
Login

Artifact [c59fb07906]

Artifact c59fb07906e46ef8bd98900dcd1910011c21e1ec5358b77460ac7a536379e334:


/* The JavaScript codemode's scripts run with (codemode.c), on either engine (jsengine.h), so it is
 * ES5, so it leans on nothing an engine might lack. As C strings in chunks of at most
 * 3500 bytes (C11 promises 4095 per literal), joined when a script starts. Ported from Pi's prelude
 * (packages/codemode/src/runtime/prelude-source.ts) and source format (source.ts), with pic's
 * synchronous calls: a tool call returns its value, parallel([...]) runs calls at once. The input
 * is {"script": ...} JSON; the output is formatted here; searchTools(), describeTool() and
 * describeNamespace() answer in the engine. Edit the JavaScript in place. */

/* parseSource(inputJson): {code, timeoutMs?, maxOutputTokens?} or {error}. */
static const char *const cm_source_js[] = {
    "// The input, {\"script\": SOURCE}, and Pi's options line: {code, timeoutMs?, maxOutputTokens?} or {error}.\n"
    "function parseSource(inputJson) {\n"
    "    \"use strict\";\n"
    "    var PREFIX = \"// @options:\", FIELDS = \"`max_output_tokens` and `timeout_ms`\", MAX_TIMEOUT_MS = 2147483647;\n"
    "    var input, lines, i, first, newline, code, directive, value, key, out;\n"
    "    function fail(message) { return { error: message }; }\n"
    "    function lstrip(s) { return s.replace(/^\\s+/, \"\"); }\n"
    "    function safe(n) { return typeof n === \"number\" && n >= 0 && n === Math.floor(n) && n <= 9007199254740991; }\n"
    "    try {\n"
    "        input = JSON.parse(inputJson);\n"
    "    } catch (badInput) {\n"
    "        return fail(\"codemode input must be a JSON object with script, the JavaScript source\");\n"
    "    }\n"
    "    if (typeof input !== \"object\" || input === null || typeof input.script !== \"string\") {\n"
    "        return fail(\"codemode input must be a JSON object with script, the JavaScript source as a string\");\n"
    "    }\n"
    "    if (input.script.replace(/\\s+/g, \"\") === \"\") {\n"
    "        return fail('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {\"max_output_tokens\": 1000}`.');\n"
    "    }\n"
    "    lines = input.script.split(\"\\n\");\n"
    "    for (i = 1; i < lines.length; i++) {\n"
    "        if (lstrip(lines[i]).indexOf(PREFIX) === 0) {\n"
    "            return fail(\"The \" + PREFIX + \" line must be the first line of the input; found one on line \" + (i + 1));\n"
    "        }\n"
    "    }\n"
    "    first = lstrip(lines[0].replace(/\\r$/, \"\"));\n"
    "    if (first.indexOf(PREFIX) !== 0) return { code: input.script };\n"
    "    newline = input.script.indexOf(\"\\n\");\n"
    "    code = newline < 0 ? \"\" : input.script.slice(newline);\n"
    "    if (code.replace(/\\s+/g, \"\") === \"\") return fail(\"The @options line must be followed by JavaScript source on subsequent lines\");\n"
    "    directive = first.slice(PREFIX.length).replace(/^\\s+|\\s+$/g, \"\");\n"
    "    if (directive === \"\") return fail(\"@options must be a JSON object with supported fields \" + FIELDS);\n"
    "    try {\n"
    "        value = JSON.parse(directive);\n"
    "    } catch (badOptions) {\n"
    "        return fail(\"@options must be valid JSON with supported fields \" + FIELDS + \": \" + badOptions.message);\n"
    "    }\n"
    "    if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n"
    "        return fail(\"@options must be a JSON object with supported fields \" + FIELDS);\n"
    "    }\n"
    "    for (key in value) {\n"
    "        if (value.hasOwnProperty(key) && key !== \"max_output_tokens\" && key !== \"timeout_ms\") {\n"
    "            return fail(\"@options only supports \" + FIELDS + \"; got `\" + key + \"`\");\n"
    "        }\n"
    "    }\n"
    "    out = { code: code };\n"
    "    if (value.max_output_tokens !== undefined) {\n"
    "        if (!safe(value.max_output_tokens)) return fail(\"@options field `max_output_tokens` must be a non-negative safe integer\");\n"
    "        out.maxOutputTokens = value.max_output_tokens;\n"
    "    }\n"
    "    if (value.timeout_ms !== undefined) {\n"
    "        if (!safe(value.timeout_ms) || value.timeout_ms === 0 || value.timeout_ms > MAX_TIMEOUT_MS) {\n"
    "            return fail(\"@options field `timeout_ms` must be a positive integer up to \" + MAX_TIMEOUT_MS);\n"
    "        }\n"
    "        out.timeoutMs = value.timeout_ms;\n"
    "    }\n"
    "    return out;\n"
    "}\n",
    NULL};

/* (host, async) => {start, run, cut, stalled, finished}: host is __host (jsengine.h); "call" runs a
 * round of tool calls, "done" ends the script. */
static const char *const cm_prelude_js[] = {
    "(function (host, asyncOk) {\n"
    "    \"use strict\";\n"
    "    var stringify = JSON.stringify, parse = JSON.parse, ErrorCtor = Error, TypeErrorCtor = TypeError, RangeErrorCtor = RangeError;\n"
    "    var MAX_OUTPUT_CHARS = 16777216, MAX_OUTPUT_ITEMS = 100000, MAX_STORE_VALUE_CHARS = 262144, MAX_STORE_TOTAL_CHARS = 1048576;\n"
    "    var catalog = parse(host(\"catalog\"));\n"
    "    var calls = [], outputItems = [], finished = false, collecting = null, EXIT = {};\n"
    "    var outputChars = 0, outputCount = 0, stored = {}, storedChars = 0;\n"
    "\n"
    "    function valueText(value) {\n"
    "        if (typeof value === \"string\") return value;\n"
    "        var json = stringify(value);\n"
    "        return json === undefined ? String(value) : json;\n"
    "    }\n"
    "    function errorHead(error) {\n"
    "        if (error.kind === \"script\") return error.stack || (error.name || \"Error\") + \": \" + error.message;\n"
    "        if (error.kind === \"timeout\") return \"Script timed out: \" + error.message;\n"
    "        if (error.kind === \"aborted\") return \"Script aborted: \" + error.message;\n"
    "        return \"Script sandbox failed: \" + error.message;\n"
    "    }\n"
    "    function callSummary() {\n"
    "        if (calls.length === 0) return \"No tool calls were made.\";\n"
    "        return \"Tool calls made before the failure (they are not undone): \" +\n"
    "            calls.map(function (c) { return c.name + \" (\" + c.status + \")\"; }).join(\", \");\n"
    "    }\n"
    "    // The result: text items in order (with several, each starts \"==> text N/M <==\"), console lines in\n"
    "    // one block after them, the error, and the images, each named where it was shown.\n"
    "    function result(ok, value, error) {\n"
    "        var items = outputItems.slice(), total = 0, parts = [], consoleLines = [], images = [], index = 0, body = \"\", i;\n"
    "        if (ok && value !== undefined) items.push({ type: \"text\", text: valueText(value) });\n"
    "        for (i = 0; i < items.length; i++) if (items[i].type === \"text\" && !items[i].console) total++;\n"
    "        for (i = 0; i < items.length; i++) {\n"
    "            var item = items[i];\n"
    "            if (item.type === \"image\") {\n"
    "                images.push({ data: item.data, mimeType: item.mimeType });\n"
    "                parts.push(\"[image \" + images.length + \": \" + item.mimeType + \", \" + Math.floor(item.data.length * 3 / 4) + \" bytes]\");\n"
    "            } else if (item.console) {\n"
    "                consoleLines.push(item.text);\n"
    "            } else {\n"
    "                index++;\n"
    "                parts.push(total > 1 ? \"==> text \" + index + \"/\" + total + \" <==\\n\" + item.text : item.text);\n"
    "            }\n"
    "        }\n"
    "        if (consoleLines.length > 0) parts.push(\"<console_output>\\n\" + consoleLines.join(\"\\n\") + \"\\n</console_output>\");\n"
    "        if (!ok) parts.push(\"Script error:\\n\" + errorHead(error) + \"\\n\\n\" + callSummary());\n"
    "        for (i = 0; i < parts.length; i++) {\n"
    "            if (body !== \"\" && body.charAt(body.length - 1) !== \"\\n\") body += \"\\n\";\n"
    "            body += parts[i];\n"
    "        }\n"
    "        return { ok: ok, body: body, images: images };\n"
    "    }\n"
    "    function done(ok, value, error) {\n"
    "        if (finished) return;\n"
    "        finished = true;\n"
    "        for (var i = 0; i < calls.length; i++) if (calls[i].status === \"running\") calls[i].status = \"cancelled\";\n"
    "        host(\"done\", stringify(result(ok, value, error)));\n"
    "    }\n"
    "    function errorText(error) {\n"
    "        var head = error.message ? error.name + \": \" + error.message : String(error.name);\n"
    "        var frames = typeof error.stack === \"string\" ? error.stack.split(\"\\n\").filter(function (l) {\n",
    "            return l.replace(/\\s+/g, \"\") !== \"\" && l.indexOf(\"codemode-\") < 0 && l.indexOf(\"(native)\") < 0;\n"
    "        }).map(function (l) { return l.replace(\"<input>\", \"codemode.js\").replace(\"at  (\", \"at <anonymous> (\"); }) : [];\n"
    "        if (frames.length > 20) frames = frames.slice(0, 20).concat([\"    ... \" + (frames.length - 20) + \" more frames\"]);\n"
    "        return [head].concat(frames).join(\"\\n\");\n"
    "    }\n"
    "    function format(value) {\n"
    "        if (typeof value === \"string\") return value;\n"
    "        if (value instanceof ErrorCtor) return errorText(value);\n"
    "        if (typeof value === \"number\") return String(value);\n"
    "        try {\n"
    "            var json = stringify(value);\n"
    "            return json === undefined ? String(value) : json;\n"
    "        } catch (e) {\n"
    "            return String(value);\n"
    "        }\n"
    "    }\n"
    "    function describeError(error) {\n"
    "        // The host cut the script off (its deadline, or Ctrl-C): the engine's uncatchable error.\n"
    "        if (error instanceof ErrorCtor && error.message === \"interrupted\") {\n"
    "            var why = host(\"why\");\n"
    "            if (why) return parse(why);\n"
    "        }\n"
    "        try {\n"
    "            if (error instanceof ErrorCtor) return { kind: \"script\", name: String(error.name), message: String(error.message), stack: errorText(error) };\n"
    "            return { kind: \"script\", message: String(format(error)) };\n"
    "        } catch (e) {\n"
    "            return { kind: \"script\", message: \"The script threw a value that cannot be described\" };\n"
    "        }\n"
    "    }\n"
    "\n"
    "    // Calls go to pic, which runs them as calls nested in this one and answers each in order:\n"
    "    // {ok, value} or {ok: false, error}. Several at once run together (parallel()).\n"
    "    function invoke(list) {\n"
    "        var lines = [], records = [], i, answers;\n"
    "        for (i = 0; i < list.length; i++) {\n"
    "            lines.push(list[i].name + \"\\t\" + list[i].args);\n"
    "            records.push({ name: list[i].name, status: \"running\" });\n"
    "            calls.push(records[i]);\n"
    "        }\n"
    "        answers = parse(host(\"call\", lines.join(\"\\n\")));\n"
    "        for (i = 0; i < records.length; i++) records[i].status = answers[i] && answers[i].ok ? \"ok\" : \"error\";\n"
    "        return answers;\n"
    "    }\n"
    "    function argsJson(args) {\n"
    "        var json = args === undefined ? \"{}\" : stringify(args);\n"
    "        return json === undefined ? \"{}\" : json;\n"
    "    }\n"
    "    function caller(name) {\n"
    "        return function (args) {\n"
    "            var json = argsJson(args), answer;\n"
    "            if (collecting) { // inside parallel(): describe the call, run it with the others\n"
    "                collecting.push({ name: name, args: json });\n"
    "                return { __picCall: collecting.length - 1 };\n"
    "            }\n"
    "            answer = invoke([{ name: name, args: json }])[0];\n"
    "            if (!answer.ok) throw new ErrorCtor(answer.error);\n"
    "            return answer.value;\n"
    "        };\n"
    "    }\n"
    "    var tools = {}, allTools = [], i;\n"
    "    for (i = 0; i < catalog.length; i++) {\n"
    "        var entry = catalog[i], fn = caller(entry.name);\n"
    "        if (!tools.hasOwnProperty(entry.jsName)) {\n"
    "            tools[entry.jsName] = fn;\n"
    "            allTools.push({ name: entry.jsName, description: entry.description });\n"
    "        }\n"
    "        if (!tools.hasOwnProperty(entry.name)) tools[entry.name] = fn;\n"
    "    }\n"
    "    var toolsView = tools;\n"
    "    if (typeof Proxy === \"function\" && typeof Reflect === \"object\") {\n"
    "        var names = allTools.map(function (t) { return t.name; });\n"
    "        toolsView = new Proxy(tools, {\n"
    "            get: function (object, property, receiver) {\n",
    "                if (typeof property !== \"string\" || property in object || property in Object.prototype || property === \"then\" || property === \"toJSON\") {\n"
    "                    return Reflect.get(object, property, receiver);\n"
    "                }\n"
    "                var wanted = property.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n"
    "                var close = names.filter(function (n) {\n"
    "                    var c = n.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n"
    "                    return wanted && (c === wanted || c.indexOf(wanted) >= 0 || wanted.indexOf(c) >= 0);\n"
    "                });\n"
    "                var message = \"tools.\" + property + \" does not exist.\";\n"
    "                if (close.length > 0) message += \" Did you mean \" + close.slice(0, 5).map(function (n) { return \"tools.\" + n; }).join(\", \") + \"?\";\n"
    "                else if (names.length <= 20) message += \" Available: \" + names.join(\", \") + \".\";\n"
    "                throw new TypeErrorCtor(message + \" ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.\");\n"
    "            }\n"
    "        });\n"
    "    }\n"
    "\n"
    "    // parallel([...]): tool calls run at once, their results in order. Each item is a function that\n"
    "    // makes one tool call (() => tools.read({...})) or a descriptor {tool, args}. A failure throws\n"
    "    // its Error once all have run; with {settled: true} each is {status, value} or {status, reason}.\n"
    "    function parallel(list, options) {\n"
    "        var descs = [], i, answers, out = [], firstError = null;\n"
    "        if (!Array.isArray(list)) throw new TypeErrorCtor(\"parallel() expects an array of tool calls\");\n"
    "        for (i = 0; i < list.length; i++) {\n"
    "            var item = list[i];\n"
    "            if (typeof item === \"function\") {\n"
    "                var before = collecting, mark;\n"
    "                collecting = [];\n"
    "                try {\n"
    "                    mark = item();\n"
    "                } finally {\n"
    "                    var made = collecting;\n"
    "                    collecting = before;\n"
    "                }\n"
    "                if (made.length !== 1 || !mark || mark.__picCall !== 0) {\n"
    "                    throw new TypeErrorCtor(\"parallel() item \" + i + \" must make exactly one tool call and return it, as () => tools.read({...})\");\n"
    "                }\n"
    "                descs.push(made[0]);\n"
    "            } else if (item && typeof item === \"object\" && typeof item.tool === \"string\") {\n"
    "                if (!tools.hasOwnProperty(item.tool)) throw new TypeErrorCtor(\"parallel() item \" + i + \": tools.\" + item.tool + \" does not exist\");\n"
    "                descs.push({ name: catalogName(item.tool), args: argsJson(item.args) });\n"
    "            } else {\n"
    "                throw new TypeErrorCtor(\"parallel() item \" + i + \" must be () => tools.NAME(args) or { tool, args }\");\n"
    "            }\n"
    "        }\n"
    "        answers = descs.length ? invoke(descs) : [];\n"
    "        for (i = 0; i < answers.length; i++) {\n"
    "            var a = answers[i];\n"
    "            if (options && options.settled) out.push(a.ok ? { status: \"fulfilled\", value: a.value } : { status: \"rejected\", reason: new ErrorCtor(a.error) });\n"
    "            else if (a.ok) out.push(a.value);\n"
    "            else if (!firstError) firstError = new ErrorCtor(a.error);\n"
    "        }\n"
    "        if (firstError && !(options && options.settled)) throw firstError;\n"
    "        return out;\n"
    "    }\n"
    "    function catalogName(name) {\n"
    "        for (var k = 0; k < catalog.length; k++) if (catalog[k].name === name || catalog[k].jsName === name) return catalog[k].name;\n"
    "        return name;\n"
    "    }\n"
    "\n",
    "    // searchTools(): BM25 over each tool's name, namespace and description.\n"
    "    function words(text) { return String(text).toLowerCase().match(/[a-z0-9]+/g) || []; }\n"
    "    function namespaceMatches(entry, query) {\n"
    "        if (!entry.namespace) return false;\n"
    "        var id = function (n) { return n.replace(/[^A-Za-z0-9_$]/g, \"_\"); };\n"
    "        return entry.namespace === query || id(entry.namespace) === id(query);\n"
    "    }\n"
    "    function searchTools(query, options) {\n"
    "        if (typeof query !== \"string\") throw new TypeErrorCtor(\"searchTools() expects a query string\");\n"
    "        var limit = options && options.limit !== undefined ? options.limit : 8;\n"
    "        if (typeof limit !== \"number\" || limit !== Math.floor(limit) || limit <= 0) throw new TypeErrorCtor(\"searchTools() limit must be a positive integer\");\n"
    "        var namespace = options ? options.namespace : undefined;\n"
    "        var docs = catalog.filter(function (e) { return !namespace || namespaceMatches(e, namespace); }).map(function (e) {\n"
    "            return { entry: e, terms: words(e.name.replace(/_/g, \" \") + \" \" + (e.namespace || \"\") + \" \" + e.description) };\n"
    "        });\n"
    "        var terms = words(query), n = docs.length, avg = 0, j;\n"
    "        for (j = 0; j < n; j++) avg += docs[j].terms.length;\n"
    "        avg = n ? avg / n : 1;\n"
    "        var scored = docs.map(function (doc) {\n"
    "            var score = 0;\n"
    "            terms.forEach(function (term) {\n"
    "                var tf = doc.terms.filter(function (t) { return t === term; }).length;\n"
    "                if (!tf) return;\n"
    "                var df = docs.filter(function (o) { return o.terms.indexOf(term) >= 0; }).length;\n"
    "                var idf = Math.log(1 + (n - df + 0.5) / (df + 0.5));\n"
    "                score += idf * ((tf * 2.2) / (tf + 1.2 * (0.25 + 0.75 * (doc.terms.length / (avg || 1)))));\n"
    "            });\n"
    "            return { doc: doc, score: score };\n"
    "        });\n"
    "        return scored.filter(function (s) { return s.score > 0; }).sort(function (a, b) { return b.score - a.score; })\n"
    "            .slice(0, limit).map(function (s) { return { name: s.doc.entry.jsName, description: s.doc.entry.description }; });\n"
    "    }\n"
    "    function describeTool(name) {\n"
    "        if (typeof name !== \"string\") throw new TypeErrorCtor(\"describeTool() expects a tool name\");\n"
    "        for (var k = 0; k < catalog.length; k++) if (catalog[k].name === name || catalog[k].jsName === name) return catalog[k].description;\n"
    "        return undefined;\n"
    "    }\n"
    "    function describeNamespace(name) {\n"
    "        if (typeof name !== \"string\") throw new TypeErrorCtor(\"describeNamespace() expects a namespace name\");\n"
    "        var members = catalog.filter(function (e) { return namespaceMatches(e, name); });\n"
    "        if (members.length === 0) return undefined;\n"
    "        return { name: members[0].namespace, tools: members.map(function (e) { return e.jsName; }) };\n"
    "    }\n"
    "\n"
    "    var STORE_HINT = \"store() is for small state such as IDs or summaries. Keep large data in variables, or write it to a file with a tool.\";\n"
    "    function store(key, value) {\n"
    "        if (typeof key !== \"string\") throw new TypeErrorCtor(\"store() key must be a string\");\n"
    "        var previous = stored.hasOwnProperty(key) ? key.length + stored[key].length : 0, json;\n"
    "        if (value === undefined) {\n"
    "            delete stored[key];\n"
    "            storedChars -= previous;\n"
    "            return;\n"
    "        }\n"
    "        json = stringify(value);\n"
    "        if (json === undefined) throw new TypeErrorCtor(\"store(\" + stringify(key) + \") value is not JSON-serializable\");\n",
    "        if (json.length > MAX_STORE_VALUE_CHARS) throw new RangeErrorCtor(\"store(\" + stringify(key) + \") value has \" + json.length + \" characters of JSON, more than the limit of \" + MAX_STORE_VALUE_CHARS + \". \" + STORE_HINT);\n"
    "        if (storedChars - previous + key.length + json.length > MAX_STORE_TOTAL_CHARS) throw new RangeErrorCtor(\"store is full: stored values would exceed \" + MAX_STORE_TOTAL_CHARS + \" characters of JSON. \" + STORE_HINT);\n"
    "        stored[key] = json;\n"
    "        storedChars += key.length + json.length - previous;\n"
    "    }\n"
    "    function load(key) {\n"
    "        if (typeof key !== \"string\") throw new TypeErrorCtor(\"load() key must be a string\");\n"
    "        return stored.hasOwnProperty(key) ? parse(stored[key]) : undefined;\n"
    "    }\n"
    "\n"
    "    function output(item, size) {\n"
    "        if (finished) return;\n"
    "        outputChars += size;\n"
    "        outputCount++;\n"
    "        if (outputChars > MAX_OUTPUT_CHARS || outputCount > MAX_OUTPUT_ITEMS) {\n"
    "            var error = new RangeErrorCtor(\"script output exceeded the limit of \" + MAX_OUTPUT_CHARS + \" characters or \" + MAX_OUTPUT_ITEMS + \" text(), image(), and console calls. Print a summary instead, or write large data to a file with a tool.\");\n"
    "            done(false, undefined, describeError(error));\n"
    "            throw error;\n"
    "        }\n"
    "        outputItems.push(item);\n"
    "    }\n"
    "    function outputText(value) {\n"
    "        if (value === undefined || value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return String(value);\n"
    "        var json = stringify(value);\n"
    "        return json === undefined ? String(value) : json;\n"
    "    }\n"
    "    function text(value) {\n"
    "        var rendered = outputText(value);\n"
    "        output({ type: \"text\", text: rendered }, rendered.length);\n"
    "    }\n"
    "    var IMAGE_EXPECTS = 'image expects a non-empty image URL string, an object with image_url, or an image block { type: \"image\", data, mimeType }';\n"
    "    function image(value) {\n"
    "        var url;\n"
    "        if (typeof value === \"string\") url = value;\n"
    "        else if (value && typeof value === \"object\" && typeof value.image_url === \"string\") url = value.image_url;\n"
    "        else if (value && typeof value === \"object\" && value.type === \"image\" && typeof value.data === \"string\" && value.data !== \"\") {\n"
    "            url = value.data.toLowerCase().indexOf(\"data:\") === 0 ? value.data : \"data:;base64,\" + value.data;\n"
    "        } else throw new TypeErrorCtor(IMAGE_EXPECTS);\n"
    "        var colon = url.indexOf(\":\"), scheme = colon < 0 ? \"\" : url.slice(0, colon).toLowerCase(), comma = url.indexOf(\",\");\n"
    "        if (scheme === \"http\" || scheme === \"https\") throw new TypeErrorCtor(\"remote image URLs are not supported in tool outputs. Pass a base64 data URI instead\");\n"
    "        if (scheme !== \"data\" || comma < 0 || url.slice(colon + 1, comma).toLowerCase().indexOf(\"base64\") < 0) throw new TypeErrorCtor(\"invalid image output. Pass a base64 data URI instead\");\n"
    "        var data = url.slice(comma + 1).replace(/\\s+/g, \"\");\n"
    "        if (data.length % 4 !== 0 || !/^[A-Za-z0-9+\\/]+={0,2}$/.test(data)) throw new TypeErrorCtor(\"invalid image output. The image data is not valid base64 (truncated or corrupted?)\");\n"
    "        var head = data.slice(0, 16), mime = /^iVBORw0KGg/.test(head) ? \"image/png\" : /^\\/9j\\//.test(head) ? \"image/jpeg\" : /^R0lGOD[dl]h/.test(head) ? \"image/gif\" : /^UklG.{8}RUJQ/.test(head) ? \"image/webp\" : null;\n"
    "        if (!mime) throw new TypeErrorCtor(\"invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image\");\n",
    "        output({ type: \"image\", data: data, mimeType: mime }, data.length);\n"
    "    }\n"
    "    function exit() {\n"
    "        done(true, undefined);\n"
    "        throw EXIT;\n"
    "    }\n"
    "    var console = {};\n"
    "    [\"log\", \"info\", \"warn\", \"error\", \"debug\"].forEach(function (level) {\n"
    "        console[level] = function () {\n"
    "            var line = Array.prototype.slice.call(arguments).map(format).join(\" \");\n"
    "            output({ type: \"text\", text: line, console: true }, line.length);\n"
    "        };\n"
    "    });\n"
    "    var globals = { tools: toolsView, ALL_TOOLS: allTools, console: console, text: text, image: image, exit: exit, store: store,\n"
    "        load: load, parallel: parallel, searchTools: searchTools, describeTool: describeTool, describeNamespace: describeNamespace };\n"
    "    Object.keys(globals).forEach(function (k) { globalThis[k] = globals[k]; });\n"
    "\n"
    "    function finish(value) {\n"
    "        var json;\n"
    "        try {\n"
    "            json = value === undefined ? undefined : stringify(value);\n"
    "        } catch (e) {\n"
    "            done(false, undefined, describeError(e));\n"
    "            return;\n"
    "        }\n"
    "        done(true, json === undefined ? undefined : value);\n"
    "    }\n"
    "    return {\n"
    "        // The input and its options line; the script compiled. Every refusal ends the call.\n"
    "        start: function () {\n"
    "            var src = parseSource(host(\"input\"));\n"
    "            if (src.error) {\n"
    "                finished = true;\n"
    "                host(\"done\", stringify({ invalid: src.error }));\n"
    "                return null;\n"
    "            }\n"
    "            host(\"options\", String(src.timeoutMs || -1), String(src.maxOutputTokens === undefined ? -1 : src.maxOutputTokens));\n"
    "            try {\n"
    "                return (0, eval)(\"(\" + (asyncOk ? \"async \" : \"\") + \"function (tools, console) {\" + src.code + \"\\n})\");\n"
    "            } catch (e) {\n"
    "                done(false, undefined, describeError(e));\n"
    "                return null;\n"
    "            }\n"
    "        },\n"
    "        run: function (fn) {\n"
    "            var value;\n"
    "            try {\n"
    "                value = fn(toolsView, console);\n"
    "            } catch (e) {\n"
    "                if (e !== EXIT) done(false, undefined, describeError(e));\n"
    "                return;\n"
    "            }\n"
    "            if (asyncOk && value && typeof value.then === \"function\") {\n"
    "                value.then(finish, function (e) { if (e !== EXIT) done(false, undefined, describeError(e)); });\n"
    "            } else finish(value);\n"
    "        },\n"
    "        // Ended by the host (its deadline, Ctrl-C, a VM failure): KIND timeout, aborted or sandbox.\n"
    "        cut: function (kind, message) { done(false, undefined, { kind: kind, message: message }); },\n"
    "        stalled: function () {\n"
    "            if (finished) return;\n"
    "            done(false, undefined, { kind: \"script\", name: \"Error\", message: \"The script is waiting on a promise that can never settle: tool calls return their values, and timers do not exist here.\" });\n"
    "        },\n"
    "        finished: function () { return finished; }\n"
    "    };\n"
    "})\n",
    NULL};