Skip to content
pi-c Artifact [9ef1b105d9]
Login

Artifact [9ef1b105d9]

Artifact 9ef1b105d92677e2770cec1ddb342f1b8a9831419611a6cada008ffd0bf4e769:


/* The JavaScript codemode's worker runs in QuickJS (codemode.c), as C strings in chunks of at most
 * 3500 bytes (C11 promises 4095 per literal), joined when the worker starts. Ported from Pi's
 * prelude (packages/codemode/src/runtime/prelude-source.ts) and source format (source.ts): the
 * input is {"script": ...} JSON, the output is formatted here, and searchTools(), describeTool()
 * and describeNamespace() answer in the VM. Edit the JavaScript in place. */

/* (inputJson) => {code, timeoutMs?, maxOutputTokens?} or {error}. */
static const char *const cm_source_js[] = {
    "(function (inputJson) {\n"
    "    \"use strict\";\n"
    "    const PREFIX = \"// @options:\";\n"
    "    const FIELDS = \"`max_output_tokens` and `timeout_ms`\";\n"
    "    const MAX_TIMEOUT_MS = 2147483647;\n"
    "    const fail = (message) => ({ error: message });\n"
    "    let input;\n"
    "    try {\n"
    "        input = JSON.parse(inputJson);\n"
    "    } catch (error) {\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"
    "    const source = input.script;\n"
    "    if (source.trim() === \"\") {\n"
    "        return fail('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {\"max_output_tokens\": 1000}`.');\n"
    "    }\n"
    "    const lines = source.split(\"\\n\");\n"
    "    const misplaced = lines.findIndex((line, index) => index > 0 && line.trimStart().startsWith(PREFIX));\n"
    "    if (misplaced !== -1) {\n"
    "        return fail(\"The \" + PREFIX + \" line must be the first line of the input; found one on line \" + (misplaced + 1));\n"
    "    }\n"
    "    const first = lines[0].replace(/\\r$/, \"\").trimStart();\n"
    "    if (!first.startsWith(PREFIX)) return { code: source };\n"
    "    const newline = source.indexOf(\"\\n\");\n"
    "    const code = newline === -1 ? \"\" : source.slice(newline);\n"
    "    if (code.trim() === \"\") return fail(\"The @options line must be followed by JavaScript source on subsequent lines\");\n"
    "    const directive = first.slice(PREFIX.length).trim();\n"
    "    if (directive === \"\") return fail(\"@options must be a JSON object with supported fields \" + FIELDS);\n"
    "    let value;\n"
    "    try {\n"
    "        value = JSON.parse(directive);\n"
    "    } catch (error) {\n"
    "        return fail(\"@options must be valid JSON with supported fields \" + FIELDS + \": \" + error.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 (const key of Object.keys(value)) {\n"
    "        if (key !== \"max_output_tokens\" && key !== \"timeout_ms\") return fail(\"@options only supports \" + FIELDS + \"; got `\" + key + \"`\");\n"
    "    }\n"
    "    const safe = (n) => typeof n === \"number\" && Number.isSafeInteger(n) && n >= 0;\n"
    "    const out = { 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};

/* (bridge, toolsJson, storeJson) => {settle, run, fail, pending, stalled}; bridge("call", id, name,
 * argsJson) asks pic for a tool call, bridge("done", resultJson) ends the script. */
static const char *const cm_prelude_js[] = {
    "(function (bridge, toolsJson, storeJson) {\n"
    "    \"use strict\";\n"
    "\n"
    "    // Freeze every object reachable from the built-in globals, plus the intrinsics that are only\n"
    "    // reachable from instances (iterator and generator prototypes, %TypedArray%).\n"
    "    //\n"
    "    // Freezing alone breaks ordinary code through the \"override mistake\": a data property that is\n"
    "    // read-only on a prototype cannot be assigned on an instance either, so\n"
    "    // this.name = \"MyError\" in an Error subclass would throw. Commonly overridden properties\n"
    "    // become accessors whose setter defines an own property on the instance instead.\n"
    "    (function lockdown() {\n"
    "        const OVERRIDABLE = new Set([\"constructor\", \"name\", \"message\", \"toString\", \"toLocaleString\", \"valueOf\", \"toJSON\"]);\n"
    "        const seen = new Set([globalThis]);\n"
    "        const queue = [];\n"
    "        const add = (value) => {\n"
    "            if ((typeof value === \"object\" && value !== null) || typeof value === \"function\") {\n"
    "                if (!seen.has(value)) {\n"
    "                    seen.add(value);\n"
    "                    queue.push(value);\n"
    "                }\n"
    "            }\n"
    "        };\n"
    "\n"
    "        // Accessors from an object literal have no own prototype object, unlike function expressions,\n"
    "        // whose prototype.constructor would be converted again without end.\n"
    "        function allowOverride(object, key, value, enumerable) {\n"
    "            const { get, set } = Object.getOwnPropertyDescriptor(\n"
    "                {\n"
    "                    get accessor() {\n"
    "                        return value;\n"
    "                    },\n"
    "                    set accessor(next) {\n"
    "                        if (this === object) {\n"
    "                            throw new TypeError(\"Cannot assign to read only property '\" + String(key) + \"' of a built-in\");\n"
    "                        }\n"
    "                        if ((typeof this !== \"object\" || this === null) && typeof this !== \"function\") return;\n"
    "                        Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });\n"
    "                    },\n"
    "                },\n"
    "                \"accessor\",\n"
    "            );\n"
    "            Object.defineProperty(object, key, { get, set, enumerable, configurable: false });\n"
    "            add(get);\n"
    "            add(set);\n"
    "        }\n"
    "\n"
    "        for (const key of Reflect.ownKeys(globalThis)) {\n"
    "            const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);\n"
    "            add(descriptor.value);\n"
    "            add(descriptor.get);\n"
    "            add(descriptor.set);\n"
    "            if (\"value\" in descriptor && descriptor.configurable) {\n"
    "                Object.defineProperty(globalThis, key, { writable: false, configurable: false });\n"
    "            }\n"
    "        }\n"
    "        add(Object.getPrototypeOf(function* () {}));\n"
    "        add(Object.getPrototypeOf(async function () {}));\n"
    "        add(Object.getPrototypeOf(async function* () {}));\n"
    "        add(Object.getPrototypeOf(Int8Array));\n"
    "        add(Object.getPrototypeOf([][Symbol.iterator]()));\n"
    "        add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));\n"
    "        add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));\n"
    "        add(Object.getPrototypeOf(\"\"[Symbol.iterator]()));\n"
    "        add(Object.getPrototypeOf(/a/[Symbol.matchAll](\"\")));\n"
    "        if (typeof Iterator === \"function\") {\n"
    "            if (typeof Iterator.prototype.map === \"function\") add(Object.getPrototypeOf([].values().map((x) => x)));\n"
    "            if (typeof Iterator.from === \"function\") add(Object.getPrototypeOf(Iterator.from({ next() {} })));\n"
    "        }\n"
    "\n",
    "        while (queue.length > 0) {\n"
    "            const object = queue.pop();\n"
    "            add(Object.getPrototypeOf(object));\n"
    "            const descriptors = Object.getOwnPropertyDescriptors(object);\n"
    "            for (const key of Reflect.ownKeys(descriptors)) {\n"
    "                const descriptor = descriptors[key];\n"
    "                if (\"value\" in descriptor) {\n"
    "                    add(descriptor.value);\n"
    "                    if (\n"
    "                        descriptor.writable &&\n"
    "                        descriptor.configurable &&\n"
    "                        (object === Object.prototype || OVERRIDABLE.has(key))\n"
    "                    ) {\n"
    "                        allowOverride(object, key, descriptor.value, descriptor.enumerable);\n"
    "                    }\n"
    "                } else {\n"
    "                    add(descriptor.get);\n"
    "                    add(descriptor.set);\n"
    "                }\n"
    "            }\n"
    "            Object.freeze(object);\n"
    "        }\n"
    "    })();\n"
    "    const stringify = JSON.stringify;\n"
    "    const parse = JSON.parse;\n"
    "    const promiseThen = Promise.prototype.then;\n"
    "    const ErrorCtor = Error;\n"
    "    const TypeErrorCtor = TypeError;\n"
    "    const RangeErrorCtor = RangeError;\n"
    "    const pending = new Map();\n"
    "    const calls = [];\n"
    "    const outputItems = [];\n"
    "    let nextId = 1;\n"
    "    let finished = false;\n"
    "    // Thrown by exit() to unwind the script after it already reported success.\n"
    "    const EXIT = Object.freeze({});\n"
    "    const MAX_OUTPUT_CHARS = 16777216;\n"
    "    const MAX_OUTPUT_ITEMS = 100000;\n"
    "    const MAX_STORE_VALUE_CHARS = 262144;\n"
    "    const MAX_STORE_TOTAL_CHARS = 1048576;\n"
    "\n"
    "    // Like text(): strings as is, other values as compact JSON.\n"
    "    function valueText(value) {\n"
    "        if (typeof value === \"string\") return value;\n"
    "        const json = stringify(value);\n"
    "        return json === undefined ? String(value) : json;\n"
    "    }\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((call) => call.name + \" (\" + call.status + \")\").join(\", \");\n"
    "    }\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"
    "\n"
    "    // The result for the host: the text items in order (with several, each starts with\n"
    "    // \"==> text N/M <==\"), console lines in one block after them, the error, and the images, each\n"
    "    // with a label line where it was shown.\n"
    "    function result(ok, value, error) {\n"
    "        const items = outputItems.slice();\n"
    "        if (ok && value !== undefined) items.push({ type: \"text\", text: valueText(value) });\n"
    "        const total = items.filter((item) => item.type === \"text\" && !item.console).length;\n"
    "        const parts = [];\n"
    "        const consoleLines = [];\n"
    "        const images = [];\n"
    "        let index = 0;\n"
    "        for (const item of items) {\n"
    "            if (item.type === \"image\") {\n"
    "                images.push({ data: item.data, mimeType: item.mimeType });\n"
    "                parts.push(\"[image \" + images.length + \": \" + item.mimeType + \", \" +\n"
    "                    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"
    "        let body = \"\";\n"
    "        for (const part of parts) {\n"
    "            if (body !== \"\" && !body.endsWith(\"\\n\")) body += \"\\n\";\n"
    "            body += part;\n"
    "        }\n"
    "        return { ok, body, images, calls: calls.map((call) => call.name + \" \" + call.status) };\n"
    "    }\n"
    "\n"
    "    function done(ok, value, error) {\n"
    "        if (finished) return;\n"
    "        finished = true;\n"
    "        for (const call of calls) if (call.status === \"running\") call.status = \"cancelled\";\n"
    "        bridge(\"done\", stringify(result(ok, value, error)));\n"
    "    }\n"
    "\n"
    "    // QuickJS stacks list frames only. Prefix \"Name: message\" like V8, and drop the prelude's frames.\n"
    "    function errorText(error) {\n"
    "        const head = error.message ? error.name + \": \" + error.message : String(error.name);\n"
    "        let frames =\n"
    "            typeof error.stack === \"string\"\n"
    "                ? error.stack.split(\"\\n\").filter((line) => line.trim() && !line.includes(\"codemode-prelude.js\"))\n"
    "                : [];\n"
    "        if (frames.length > 20) frames = [...frames.slice(0, 20), \"    ... \" + (frames.length - 20) + \" more frames\"];\n"
    "        return [head, ...frames].join(\"\\n\");\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"
    "            const json = stringify(value);\n"
    "            return json === undefined ? String(value) : json;\n"
    "        } catch {\n"
    "            return String(value);\n"
    "        }\n"
    "    }\n"
    "\n"
    "    function describeError(error) {\n"
    "        // The host cut the script off (its deadline, or Ctrl-C): QuickJS's uncatchable \"interrupted\".\n"
    "        if (error instanceof InternalError && error.message === \"interrupted\") {\n"
    "            const why = bridge(\"why\");\n"
    "            if (why) return parse(why);\n"
    "        }\n"
    "        try {\n"
    "            if (error instanceof ErrorCtor) {\n"
    "                return { kind: \"script\", name: String(error.name), message: String(error.message), stack: errorText(error) };\n"
    "            }\n"
    "            return { kind: \"script\", message: String(format(error)) };\n"
    "        } catch {\n"
    "            return { kind: \"script\", message: \"The script threw a value that cannot be described\" };\n"
    "        }\n"
    "    }\n"
    "\n"
    "    // tools.<name>(args): the call goes to pic, which runs it as a call nested in this one.\n"
    "    function caller(name) {\n"
    "        return (...args) =>\n"
    "            new Promise((resolve, reject) => {\n"
    "                let json;\n"
    "                try {\n"
    "                    json = args[0] === undefined ? \"{}\" : stringify(args[0]);\n"
    "                } catch (error) {\n"
    "                    reject(error);\n"
    "                    return;\n"
    "                }\n"
    "                if (json === undefined) json = \"{}\";\n"
    "                const id = nextId++;\n"
    "                const record = { name, status: \"running\" };\n"
    "                calls.push(record);\n"
    "                pending.set(id, { resolve, reject, record });\n"
    "                bridge(\"call\", id, name, json);\n"
    "            });\n"
    "    }\n"
    "\n"
    "    const catalog = parse(toolsJson);\n"
    "    const tools = Object.create(null);\n"
    "    const allTools = [];\n"
    "    for (const { name, jsName, description } of catalog) {\n",
    "        const fn = caller(name);\n"
    "        if (!(jsName in tools)) {\n"
    "            tools[jsName] = fn;\n"
    "            allTools.push(Object.freeze({ name: jsName, description }));\n"
    "        }\n"
    "        if (!(name in tools)) tools[name] = fn;\n"
    "    }\n"
    "    Object.freeze(tools);\n"
    "    Object.freeze(allTools);\n"
    "\n"
    "    const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n"
    "    function guard(target, label, names, hint) {\n"
    "        return new Proxy(target, {\n"
    "            get(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"
    "                const wanted = comparable(property);\n"
    "                const exact = names.filter((name) => comparable(name) === wanted);\n"
    "                const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));\n"
    "                let message = label + \".\" + property + \" does not exist.\";\n"
    "                if (close.length > 0) message += \" Did you mean \" + close.slice(0, 5).map((name) => label + \".\" + name).join(\", \") + \"?\";\n"
    "                else if (names.length <= 20) message += \" Available: \" + names.join(\", \") + \".\";\n"
    "                if (hint) message += \" \" + hint;\n"
    "                message += ' Check for a member with \"' + property + '\" in ' + label + \".\";\n"
    "                throw new TypeErrorCtor(message);\n"
    "            },\n"
    "        });\n"
    "    }\n"
    "    const toolsProxy = guard(\n"
    "        tools,\n"
    "        \"tools\",\n"
    "        allTools.map((tool) => tool.name),\n"
    "        \"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.\",\n"
    "    );\n"
    "\n"
    "    // searchTools(): BM25 over each tool's name, namespace and description.\n"
    "    const words = (text) => (String(text).toLowerCase().match(/[a-z0-9]+/g) || []);\n"
    "    function namespaceMatches(entry, query) {\n"
    "        if (!entry.namespace) return false;\n"
    "        const id = (name) => name.replace(/[^A-Za-z0-9_$]/g, \"_\");\n"
    "        return entry.namespace === query || id(entry.namespace) === id(query);\n"
    "    }\n"
    "    async function searchTools(query, options) {\n"
    "        if (typeof query !== \"string\") throw new TypeErrorCtor(\"searchTools() expects a query string\");\n"
    "        const limit = options && options.limit !== undefined ? options.limit : 8;\n"
    "        if (typeof limit !== \"number\" || !Number.isInteger(limit) || limit <= 0) {\n"
    "            throw new TypeErrorCtor(\"searchTools() limit must be a positive integer\");\n"
    "        }\n"
    "        const namespace = options ? options.namespace : undefined;\n"
    "        if (namespace !== undefined && namespace !== null && typeof namespace !== \"string\") {\n"
    "            throw new TypeErrorCtor(\"searchTools() namespace must be a string\");\n"
    "        }\n"
    "        const docs = catalog\n"
    "            .filter((entry) => !namespace || namespaceMatches(entry, namespace))\n"
    "            .map((entry) => ({ entry, terms: words(entry.name.replace(/_/g, \" \") + \" \" + (entry.namespace || \"\") + \" \" + entry.description) }));\n"
    "        const terms = words(query);\n"
    "        const n = docs.length;\n"
    "        const avg = n ? docs.reduce((sum, doc) => sum + doc.terms.length, 0) / n : 0;\n"
    "        const scored = docs.map((doc) => {\n"
    "            let score = 0;\n"
    "            for (const term of terms) {\n"
    "                const tf = doc.terms.filter((t) => t === term).length;\n"
    "                if (!tf) continue;\n",
    "                const df = docs.filter((other) => other.terms.includes(term)).length;\n"
    "                const 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, score };\n"
    "        });\n"
    "        return scored\n"
    "            .filter((item) => item.score > 0)\n"
    "            .sort((a, b) => b.score - a.score)\n"
    "            .slice(0, limit)\n"
    "            .map((item) => ({ name: item.doc.entry.jsName, description: item.doc.entry.description }));\n"
    "    }\n"
    "    async function describeTool(name) {\n"
    "        if (typeof name !== \"string\") throw new TypeErrorCtor(\"describeTool() expects a tool name\");\n"
    "        const entry = catalog.find((candidate) => candidate.name === name || candidate.jsName === name);\n"
    "        return entry ? entry.description : undefined;\n"
    "    }\n"
    "    async function describeNamespace(name) {\n"
    "        if (typeof name !== \"string\") throw new TypeErrorCtor(\"describeNamespace() expects a namespace name\");\n"
    "        const members = catalog.filter((entry) => namespaceMatches(entry, name));\n"
    "        if (members.length === 0) return undefined;\n"
    "        return { name: members[0].namespace, tools: members.map((entry) => entry.jsName) };\n"
    "    }\n"
    "\n"
    "    // key -> JSON text. Sizes count key and JSON characters.\n"
    "    const stored = new Map(Object.entries(parse(storeJson)));\n"
    "    let storedChars = 0;\n"
    "    for (const [key, json] of stored) storedChars += key.length + json.length;\n"
    "    const STORE_HINT =\n"
    "        \"store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.\";\n"
    "    function checkKey(name, key) {\n"
    "        if (typeof key !== \"string\") throw new TypeErrorCtor(name + \"() key must be a string\");\n"
    "    }\n"
    "    function store(key, value) {\n"
    "        checkKey(\"store\", key);\n"
    "        const previous = stored.has(key) ? key.length + stored.get(key).length : 0;\n"
    "        if (value === undefined) {\n"
    "            stored.delete(key);\n"
    "            storedChars -= previous;\n"
    "            return;\n"
    "        }\n"
    "        let json;\n"
    "        try {\n"
    "            json = stringify(value);\n"
    "        } catch (error) {\n"
    "            throw new TypeErrorCtor(\"store(\" + stringify(key) + \") value is not JSON-serializable: \" + format(error));\n"
    "        }\n"
    "        if (json === undefined) throw new TypeErrorCtor(\"store(\" + stringify(key) + \") value is not JSON-serializable\");\n"
    "        if (json.length > MAX_STORE_VALUE_CHARS) {\n"
    "            throw new RangeErrorCtor(\"store(\" + stringify(key) + \") value has \" + json.length +\n"
    "                \" characters of JSON, more than the limit of \" + MAX_STORE_VALUE_CHARS + \". \" + STORE_HINT);\n"
    "        }\n"
    "        const next = storedChars - previous + key.length + json.length;\n"
    "        if (next > MAX_STORE_TOTAL_CHARS) {\n"
    "            throw new RangeErrorCtor(\"store is full: stored values would exceed \" + MAX_STORE_TOTAL_CHARS +\n"
    "                \" characters of JSON. Delete keys with store(key, undefined). \" + STORE_HINT);\n"
    "        }\n"
    "        stored.set(key, json);\n"
    "        storedChars = next;\n"
    "    }\n"
    "    function load(key) {\n"
    "        checkKey(\"load\", key);\n"
    "        const json = stored.get(key);\n"
    "        return json === undefined ? undefined : parse(json);\n"
    "    }\n"
    "\n"
    "    let outputChars = 0;\n"
    "    let outputCount = 0;\n"
    "    // Past the output limits the script fails: done() reports the error, so catching it does not\n"
    "    // resume output.\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"
    "            const error = new RangeErrorCtor(\n"
    "                \"script output exceeded the limit of \" + MAX_OUTPUT_CHARS + \" characters or \" + MAX_OUTPUT_ITEMS +\n"
    "                    \" text(), image(), and console calls. Print a summary instead, or write large data to a file with a tool.\",\n"
    "            );\n"
    "            done(false, undefined, describeError(error));\n"
    "            throw error;\n"
    "        }\n"
    "        outputItems.push(item);\n"
    "    }\n"
    "\n"
    "    function outputText(value) {\n"
    "        if (value === undefined || value === null || typeof value !== \"object\" && typeof value !== \"function\") {\n"
    "            return String(value);\n"
    "        }\n"
    "        const json = stringify(value);\n"
    "        return json === undefined ? String(value) : json;\n"
    "    }\n"
    "\n"
    "    function text(value) {\n"
    "        let rendered;\n"
    "        try {\n"
    "            rendered = outputText(value);\n"
    "        } catch (error) {\n"
    "            throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));\n"
    "        }\n"
    "        output({ type: \"text\", text: rendered }, rendered.length);\n"
    "    }\n"
    "\n"
    "    const IMAGE_EXPECTS =\n"
    "        'image expects a non-empty image URL string, an object with image_url, or an image block { type: \"image\", data, mimeType }';\n"
    "    function imageUrl(value) {\n"
    "        if (typeof value === \"string\") return value;\n"
    "        if (typeof value !== \"object\" || value === null || Array.isArray(value)) throw new TypeErrorCtor(IMAGE_EXPECTS);\n"
    "        if (value.image_url !== undefined) {\n"
    "            if (typeof value.image_url !== \"string\") throw new TypeErrorCtor(IMAGE_EXPECTS);\n"
    "            return value.image_url;\n"
    "        }\n"
    "        if (typeof value.type !== \"string\") throw new TypeErrorCtor(IMAGE_EXPECTS);\n"
    "        if (value.type !== \"image\") throw new TypeErrorCtor('image only accepts image blocks, got \"' + value.type + '\"');\n"
    "        if (typeof value.data !== \"string\" || value.data === \"\") throw new TypeErrorCtor(\"image expected image block data\");\n"
    "        if (value.data.toLowerCase().startsWith(\"data:\")) return value.data;\n"
    "        return \"data:;base64,\" + value.data;\n"
    "    }\n"
    "    const IMAGE_SIGNATURES = [\n"
    "        [\"image/png\", /^iVBORw0KGg/],\n"
    "        [\"image/jpeg\", /^[/]9j[/](?!9)/],\n"
    "        [\"image/gif\", /^R0lGOD[dl]h/],\n"
    "        [\"image/webp\", /^UklG.{8}RUJQ/],\n"
    "    ];\n"
    "    function image(value) {\n"
    "        const url = imageUrl(value);\n"
    "        if (url === \"\") throw new TypeErrorCtor(IMAGE_EXPECTS);\n"
    "        const colon = url.indexOf(\":\");\n"
    "        const scheme = colon === -1 ? \"\" : url.slice(0, colon).toLowerCase();\n"
    "        if (scheme === \"http\" || scheme === \"https\") {\n"
    "            throw new TypeErrorCtor(\"remote image URLs are not supported in tool outputs. Pass a base64 data URI instead\");\n"
    "        }\n"
    "        const comma = url.indexOf(\",\");\n"
    "        const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(\";\");\n"
    "        if (scheme !== \"data\" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== \"base64\")) {\n"
    "            throw new TypeErrorCtor(\"invalid image output. Pass a base64 data URI instead\");\n"
    "        }\n"
    "        const data = url.slice(comma + 1).replace(/\\s+/g, \"\");\n"
    "        if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {\n"
    "            throw new TypeErrorCtor(\"invalid image output. The image data is not valid base64 (truncated or corrupted?)\");\n"
    "        }\n",
    "        const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(data.slice(0, 16)));\n"
    "        if (!signature) throw new TypeErrorCtor(\"invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image\");\n"
    "        output({ type: \"image\", data, mimeType: signature[0] }, data.length);\n"
    "    }\n"
    "\n"
    "    function exit() {\n"
    "        done(true, undefined);\n"
    "        throw EXIT;\n"
    "    }\n"
    "\n"
    "    const console = {};\n"
    "    for (const level of [\"log\", \"info\", \"warn\", \"error\", \"debug\"]) {\n"
    "        console[level] = (...args) => {\n"
    "            const line = args.map(format).join(\" \");\n"
    "            output({ type: \"text\", text: line, console: true }, line.length);\n"
    "        };\n"
    "    }\n"
    "    Object.freeze(console);\n"
    "\n"
    "    for (const [name, value] of [[\"tools\", toolsProxy], [\"ALL_TOOLS\", allTools], [\"console\", console], [\"text\", text],\n"
    "        [\"image\", image], [\"exit\", exit], [\"store\", store], [\"load\", load], [\"searchTools\", searchTools],\n"
    "        [\"describeTool\", describeTool], [\"describeNamespace\", describeNamespace]]) {\n"
    "        Object.defineProperty(globalThis, name, { value, enumerable: true });\n"
    "    }\n"
    "\n"
    "    return {\n"
    "        settle(id, ok, payload) {\n"
    "            const entry = pending.get(id);\n"
    "            if (!entry) return;\n"
    "            pending.delete(id);\n"
    "            entry.record.status = ok ? \"ok\" : \"error\";\n"
    "            if (!ok) {\n"
    "                entry.reject(new ErrorCtor(payload));\n"
    "                return;\n"
    "            }\n"
    "            let value;\n"
    "            try {\n"
    "                value = parse(payload);\n"
    "            } catch (error) {\n"
    "                entry.reject(error);\n"
    "                return;\n"
    "            }\n"
    "            entry.resolve(value);\n"
    "        },\n"
    "        run(fn) {\n"
    "            let promise;\n"
    "            try {\n"
    "                promise = fn(toolsProxy, console);\n"
    "            } catch (error) {\n"
    "                done(false, undefined, describeError(error));\n"
    "                return;\n"
    "            }\n"
    "            promiseThen.call(\n"
    "                promise,\n"
    "                (value) => {\n"
    "                    let json;\n"
    "                    try {\n"
    "                        json = value === undefined ? undefined : stringify(value);\n"
    "                    } catch (error) {\n"
    "                        done(false, undefined, describeError(error));\n"
    "                        return;\n"
    "                    }\n"
    "                    done(true, json === undefined ? undefined : value);\n"
    "                },\n"
    "                (error) => {\n"
    "                    if (error === EXIT) return;\n"
    "                    done(false, undefined, describeError(error));\n"
    "                },\n"
    "            );\n"
    "        },\n"
    "        // The script threw before it ran (a syntax error), or the host ended it: KIND is script,\n"
    "        // timeout, aborted or sandbox.\n"
    "        fail(kind, error) {\n"
    "            if (kind === \"script\") done(false, undefined, describeError(error));\n"
    "            else done(false, undefined, { kind, message: String(error) });\n"
    "        },\n"
    "        pending() {\n"
    "            return pending.size;\n"
    "        },\n"
    "        stalled() {\n"
    "            if (finished || pending.size > 0) return false;\n"
    "            done(false, undefined, {\n"
    "                kind: \"script\",\n"
    "                name: \"Error\",\n"
    "                message: \"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.\",\n"
    "            });\n"
    "            return true;\n"
    "        },\n"
    "    };\n"
    "})\n",
    NULL};