|
| 1 | +/** Sandboxed guest globals and host bridge for Code Mode QuickJS cells. */ |
| 2 | +import { CODE_MODE_SWARM_CONTROLLER_SOURCE } from "./code-mode-swarm-controller-source.js"; |
| 3 | + |
| 4 | +export const CODE_MODE_CONTROLLER_SOURCE = String.raw` |
| 5 | +(() => { |
| 6 | + const output = []; |
| 7 | + const pending = new Map(); |
| 8 | + const catalog = Array.isArray(globalThis.__openclawCatalog) ? globalThis.__openclawCatalog : []; |
| 9 | + const apiFiles = Array.isArray(globalThis.__openclawApiFiles) ? globalThis.__openclawApiFiles : []; |
| 10 | + const namespaceDescriptors = Array.isArray(globalThis.__openclawNamespaces) ? globalThis.__openclawNamespaces : []; |
| 11 | + const hostRequest = globalThis.__openclawHostRequest; |
| 12 | + delete globalThis.__openclawHostRequest; |
| 13 | + const bridgeSequences = new Map(); |
| 14 | +
|
| 15 | + function safe(value) { |
| 16 | + if (value === undefined) return null; |
| 17 | + try { |
| 18 | + return JSON.parse(JSON.stringify(value)); |
| 19 | + } catch { |
| 20 | + if (value instanceof Error) { |
| 21 | + return { name: value.name, message: value.message }; |
| 22 | + } |
| 23 | + if (value === null) return null; |
| 24 | + const type = typeof value; |
| 25 | + if (type === "string" || type === "number" || type === "boolean") return value; |
| 26 | + return String(value); |
| 27 | + } |
| 28 | + } |
| 29 | +
|
| 30 | + function asText(value) { |
| 31 | + if (typeof value === "string") return value; |
| 32 | + const encoded = JSON.stringify(safe(value)); |
| 33 | + return typeof encoded === "string" ? encoded : String(value); |
| 34 | + } |
| 35 | +
|
| 36 | + function request(method, args) { |
| 37 | + const methodName = String(method); |
| 38 | + const sequence = (bridgeSequences.get(methodName) ?? 0) + 1; |
| 39 | + bridgeSequences.set(methodName, sequence); |
| 40 | + const bridgeId = "bridge:" + methodName + ":" + String(sequence); |
| 41 | + const id = String(hostRequest(methodName, JSON.stringify(safe(args ?? [])), bridgeId)); |
| 42 | + return new Promise((resolve, reject) => { |
| 43 | + pending.set(id, { resolve, reject }); |
| 44 | + }); |
| 45 | + } |
| 46 | +
|
| 47 | + ${CODE_MODE_SWARM_CONTROLLER_SOURCE} |
| 48 | +
|
| 49 | + function namespaceFunction(namespaceId, path) { |
| 50 | + const callablePath = Object.freeze((Array.isArray(path) ? path : []).map((entry) => String(entry))); |
| 51 | + return (...args) => request("namespace", [namespaceId, callablePath, args]); |
| 52 | + } |
| 53 | +
|
| 54 | + function deserializeNamespaceValue(namespaceId, value) { |
| 55 | + if (!value || typeof value !== "object") return null; |
| 56 | + if (value.kind === "function") { |
| 57 | + return namespaceFunction(namespaceId, Array.isArray(value.path) ? value.path.slice() : []); |
| 58 | + } |
| 59 | + if (value.kind === "array") { |
| 60 | + return Object.freeze((Array.isArray(value.items) ? value.items : []).map((item) => deserializeNamespaceValue(namespaceId, item))); |
| 61 | + } |
| 62 | + if (value.kind === "object") { |
| 63 | + const object = Object.create(null); |
| 64 | + for (const entry of Array.isArray(value.entries) ? value.entries : []) { |
| 65 | + const key = Array.isArray(entry) && typeof entry[0] === "string" ? entry[0] : ""; |
| 66 | + if (!key) continue; |
| 67 | + Object.defineProperty(object, key, { |
| 68 | + value: deserializeNamespaceValue(namespaceId, entry[1]), |
| 69 | + enumerable: true, |
| 70 | + }); |
| 71 | + } |
| 72 | + return Object.freeze(object); |
| 73 | + } |
| 74 | + return safe(value.value); |
| 75 | + } |
| 76 | +
|
| 77 | + function settle(id, ok, payload) { |
| 78 | + const entry = pending.get(String(id)); |
| 79 | + if (!entry) return false; |
| 80 | + pending.delete(String(id)); |
| 81 | + let parsed = null; |
| 82 | + try { |
| 83 | + parsed = JSON.parse(String(payload)); |
| 84 | + } catch { |
| 85 | + parsed = String(payload); |
| 86 | + } |
| 87 | + if (ok) { |
| 88 | + entry.resolve(parsed); |
| 89 | + } else { |
| 90 | + const error = new Error(typeof parsed === "string" ? parsed : parsed?.message ?? "nested tool failed"); |
| 91 | + entry.reject(error); |
| 92 | + } |
| 93 | + return true; |
| 94 | + } |
| 95 | +
|
| 96 | + function nodeHandle(descriptor) { |
| 97 | + const handle = Object.create(null); |
| 98 | + Object.defineProperties(handle, { |
| 99 | + id: { value: descriptor.id, enumerable: true }, |
| 100 | + name: { value: descriptor.name, enumerable: true }, |
| 101 | + invoke: { |
| 102 | + value: (command, params) => request("nodes", ["invoke", descriptor.id, command, params]), |
| 103 | + enumerable: true, |
| 104 | + }, |
| 105 | + }); |
| 106 | + if (typeof descriptor.listDirCommand === "string") { |
| 107 | + Object.defineProperty(handle, "listDir", { |
| 108 | + value: (path) => request("nodes", ["invoke", descriptor.id, descriptor.listDirCommand, { path }]), |
| 109 | + enumerable: true, |
| 110 | + }); |
| 111 | + } |
| 112 | + return Object.freeze(handle); |
| 113 | + } |
| 114 | +
|
| 115 | + const nodes = Object.freeze({ |
| 116 | + list: () => request("nodes", ["list"]), |
| 117 | + get: async (idOrName) => nodeHandle(await request("nodes", ["get", idOrName])), |
| 118 | + }); |
| 119 | +
|
| 120 | + const baseTools = Object.create(null); |
| 121 | + Object.defineProperties(baseTools, { |
| 122 | + search: { value: (query, options) => request("search", [query, options]), enumerable: true }, |
| 123 | + describe: { value: (id) => request("describe", [id]), enumerable: true }, |
| 124 | + call: { value: (id, input) => request("call", [id, input]), enumerable: true }, |
| 125 | + callValue: { value: (id, input) => request("callValue", [id, input]), enumerable: true }, |
| 126 | + }); |
| 127 | + const skills = Object.freeze({ |
| 128 | + list: () => request("skillsList", []), |
| 129 | + read: (name) => request("skillsRead", [name]), |
| 130 | + }); |
| 131 | +
|
| 132 | + if (globalThis.__openclawSwarmEnabled === true) { |
| 133 | + Object.defineProperties(globalThis, { |
| 134 | + agents: { |
| 135 | + value: Object.freeze({ run: runAgent }), |
| 136 | + enumerable: true, |
| 137 | + }, |
| 138 | + phase: { value: (title) => swarmNote("phase", title), enumerable: true }, |
| 139 | + log: { value: (message) => swarmNote("log", message), enumerable: true }, |
| 140 | + }); |
| 141 | + } |
| 142 | +
|
| 143 | + function normalizeApiPath(value) { |
| 144 | + const text = String(value ?? "").trim().replace(/^\/+/, ""); |
| 145 | + if (!text || text.split("/").some((segment) => !segment || segment === "." || segment === "..")) { |
| 146 | + throw new Error("invalid API file path"); |
| 147 | + } |
| 148 | + return text; |
| 149 | + } |
| 150 | +
|
| 151 | + const apiFileMap = new Map(); |
| 152 | + for (const file of apiFiles) { |
| 153 | + if (!file || typeof file !== "object") continue; |
| 154 | + const path = typeof file.path === "string" ? file.path : ""; |
| 155 | + const content = typeof file.content === "string" ? file.content : ""; |
| 156 | + if (!path || !content) continue; |
| 157 | + apiFileMap.set(path, Object.freeze({ |
| 158 | + path, |
| 159 | + content, |
| 160 | + description: typeof file.description === "string" ? file.description : undefined, |
| 161 | + bytes: file.bytes, |
| 162 | + })); |
| 163 | + } |
| 164 | + const api = Object.freeze({ |
| 165 | + list: async (prefix = "") => { |
| 166 | + // list takes a directory prefix, so tolerate a trailing slash (API.list("mcp/")) |
| 167 | + // that read's exact-path normalizer would otherwise reject as an empty segment. |
| 168 | + const rawPrefix = prefix == null ? "" : String(prefix).trim().replace(/\/+$/, ""); |
| 169 | + const normalizedPrefix = rawPrefix === "" ? "" : normalizeApiPath(rawPrefix); |
| 170 | + const files = [...apiFileMap.values()] |
| 171 | + .filter((file) => !normalizedPrefix || file.path === normalizedPrefix || file.path.startsWith(normalizedPrefix.replace(/\/?$/, "/"))) |
| 172 | + .map((file) => Object.freeze({ |
| 173 | + path: file.path, |
| 174 | + description: file.description, |
| 175 | + bytes: file.bytes, |
| 176 | + })); |
| 177 | + return { files }; |
| 178 | + }, |
| 179 | + read: async (path) => { |
| 180 | + const normalizedPath = normalizeApiPath(path); |
| 181 | + const file = apiFileMap.get(normalizedPath); |
| 182 | + if (!file) throw new Error("Unknown API file: " + normalizedPath); |
| 183 | + return file; |
| 184 | + }, |
| 185 | + }); |
| 186 | +
|
| 187 | + const safeNameCounts = new Map(); |
| 188 | + for (const tool of catalog) { |
| 189 | + const name = typeof tool?.name === "string" ? tool.name : ""; |
| 190 | + if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) continue; |
| 191 | + safeNameCounts.set(name, (safeNameCounts.get(name) ?? 0) + 1); |
| 192 | + } |
| 193 | + for (const tool of catalog) { |
| 194 | + const name = typeof tool?.name === "string" ? tool.name : ""; |
| 195 | + const id = typeof tool?.id === "string" ? tool.id : ""; |
| 196 | + if (!id || safeNameCounts.get(name) !== 1 || Object.prototype.hasOwnProperty.call(baseTools, name)) { |
| 197 | + continue; |
| 198 | + } |
| 199 | + Object.defineProperty(baseTools, name, { |
| 200 | + value: (input) => request("callValue", [id, input]), |
| 201 | + enumerable: true, |
| 202 | + }); |
| 203 | + } |
| 204 | +
|
| 205 | + const namespaceGlobals = Object.create(null); |
| 206 | + for (const descriptor of namespaceDescriptors) { |
| 207 | + const id = typeof descriptor?.id === "string" ? descriptor.id : ""; |
| 208 | + const globalName = typeof descriptor?.globalName === "string" ? descriptor.globalName : ""; |
| 209 | + if (!id || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(globalName)) continue; |
| 210 | + const scope = deserializeNamespaceValue(id, descriptor.scope); |
| 211 | + Object.defineProperty(namespaceGlobals, globalName, { |
| 212 | + value: scope, |
| 213 | + enumerable: true, |
| 214 | + }); |
| 215 | + const existingGlobal = Object.getOwnPropertyDescriptor(globalThis, globalName); |
| 216 | + if (existingGlobal && existingGlobal.configurable === false) continue; |
| 217 | + Object.defineProperty(globalThis, globalName, { |
| 218 | + value: scope, |
| 219 | + enumerable: true, |
| 220 | + configurable: true, |
| 221 | + }); |
| 222 | + } |
| 223 | +
|
| 224 | + Object.defineProperties(globalThis, { |
| 225 | + ALL_TOOLS: { value: Object.freeze(catalog.slice()), enumerable: true }, |
| 226 | + API: { value: api, enumerable: true }, |
| 227 | + nodes: { value: nodes, enumerable: true }, |
| 228 | + namespaces: { value: Object.freeze(namespaceGlobals), enumerable: true }, |
| 229 | + skills: { value: skills, enumerable: true }, |
| 230 | + tools: { value: Object.freeze(baseTools), enumerable: true }, |
| 231 | + text: { value: (value) => output.push({ type: "text", text: asText(value) }), enumerable: true }, |
| 232 | + json: { value: (value) => output.push({ type: "json", value: safe(value) }), enumerable: true }, |
| 233 | + yield_control: { value: (reason) => request("yield", [reason]), enumerable: true }, |
| 234 | + __openclawSettleBridge: { value: settle }, |
| 235 | + __openclawTakeOutput: { value: () => output.splice(0) }, |
| 236 | + }); |
| 237 | +})(); |
| 238 | +`; |
0 commit comments