| 1 | // codewhale built-in host module harness — generated by crates/engine/extension-host/build.mjs; do not edit. |
| 2 | |
| 3 | // src/dsh/upstream/hooks/hook-protocol/src/matcher.ts |
| 4 | function isMatchAll(matcher) { |
| 5 | return matcher === void 0 || matcher === "" || matcher === "*"; |
| 6 | } |
| 7 | var CLAUDE_LITERAL = /^[A-Za-z0-9_|]+$/; |
| 8 | function compileRegex(pattern) { |
| 9 | try { |
| 10 | return new RegExp(pattern); |
| 11 | } catch (_syntaxError) { |
| 12 | return void 0; |
| 13 | } |
| 14 | } |
| 15 | function matchesMatcher(matcher, query, mode) { |
| 16 | if (isMatchAll(matcher)) return true; |
| 17 | const pattern = matcher; |
| 18 | if (mode === "claude-code" && CLAUDE_LITERAL.test(pattern)) { |
| 19 | return pattern.split("|").includes(query); |
| 20 | } |
| 21 | return compileRegex(pattern)?.test(query) ?? false; |
| 22 | } |
| 23 | |
| 24 | // src/dsh/upstream/hooks/hook-protocol/src/codec.ts |
| 25 | var BLOCKING_EXIT_CODE = 2; |
| 26 | function str(obj2, key) { |
| 27 | const v = obj2[key]; |
| 28 | return typeof v === "string" ? v : void 0; |
| 29 | } |
| 30 | function bool(obj2, key) { |
| 31 | const v = obj2[key]; |
| 32 | return typeof v === "boolean" ? v : void 0; |
| 33 | } |
| 34 | function obj(value) { |
| 35 | return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0; |
| 36 | } |
| 37 | function topLevelDecisionOf(value) { |
| 38 | return value === "approve" || value === "block" ? value : void 0; |
| 39 | } |
| 40 | function permissionDecisionOf(value) { |
| 41 | return value === "allow" || value === "deny" || value === "ask" ? value : void 0; |
| 42 | } |
| 43 | function parseHookOutput(exitCode, stdout, stderr, expectedEventName) { |
| 44 | const trimmedErr = stderr.trim(); |
| 45 | const trimmedOut = stdout.trim(); |
| 46 | const output = { exitCode, stderr: trimmedErr, stdout: trimmedOut }; |
| 47 | if (exitCode === BLOCKING_EXIT_CODE) { |
| 48 | output.decision = "block"; |
| 49 | if (trimmedErr.length > 0) output.reason = trimmedErr; |
| 50 | } |
| 51 | if (exitCode === 0) { |
| 52 | if (trimmedOut.startsWith("{")) { |
| 53 | let parsed; |
| 54 | try { |
| 55 | parsed = obj(JSON.parse(trimmedOut)); |
| 56 | } catch { |
| 57 | parsed = void 0; |
| 58 | } |
| 59 | if (parsed) applyStructured(output, parsed, expectedEventName); |
| 60 | } |
| 61 | } |
| 62 | return output; |
| 63 | } |
| 64 | function applyStructured(output, parsed, expectedEventName) { |
| 65 | const cont = bool(parsed, "continue"); |
| 66 | if (cont !== void 0) output.continue = cont; |
| 67 | const stopReason = str(parsed, "stopReason"); |
| 68 | if (stopReason !== void 0) output.stopReason = stopReason; |
| 69 | const sysMsg = str(parsed, "systemMessage"); |
| 70 | if (sysMsg !== void 0) output.systemMessage = sysMsg; |
| 71 | const topDecision = topLevelDecisionOf(str(parsed, "decision")); |
| 72 | if (topDecision !== void 0) output.decision = topDecision; |
| 73 | const topReason = str(parsed, "reason"); |
| 74 | if (topReason !== void 0) output.reason = topReason; |
| 75 | const hso = obj(parsed.hookSpecificOutput); |
| 76 | if (hso) { |
| 77 | const eventName = str(hso, "hookEventName"); |
| 78 | if (eventName !== void 0) output.hookEventName = eventName; |
| 79 | if (expectedEventName !== void 0 && eventName !== expectedEventName) { |
| 80 | return; |
| 81 | } |
| 82 | const permission = permissionDecisionOf(str(hso, "permissionDecision")); |
| 83 | if (permission !== void 0) output.decision = permission; |
| 84 | const permissionReason = str(hso, "permissionDecisionReason"); |
| 85 | if (permissionReason !== void 0) output.reason = permissionReason; |
| 86 | const addCtx = str(hso, "additionalContext"); |
| 87 | if (addCtx !== void 0) output.additionalContext = addCtx; |
| 88 | const updated = obj(hso.updatedInput); |
| 89 | if (updated !== void 0) output.updatedInput = updated; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // src/dsh/upstream/hooks/hook-protocol/src/merge.ts |
| 94 | function rank(decision) { |
| 95 | switch (decision) { |
| 96 | case "deny": |
| 97 | case "block": |
| 98 | return 3; |
| 99 | case "ask": |
| 100 | return 2; |
| 101 | case "approve": |
| 102 | case "allow": |
| 103 | return 1; |
| 104 | default: |
| 105 | return 0; |
| 106 | } |
| 107 | } |
| 108 | function decisionForRank(maxRank) { |
| 109 | switch (maxRank) { |
| 110 | case 3: |
| 111 | return "deny"; |
| 112 | case 2: |
| 113 | return "ask"; |
| 114 | case 1: |
| 115 | return "allow"; |
| 116 | default: |
| 117 | return "none"; |
| 118 | } |
| 119 | } |
| 120 | function mergeHookOutputs(outputs) { |
| 121 | let maxRank = 0; |
| 122 | const reasonsByRank = /* @__PURE__ */ new Map(); |
| 123 | let stop = false; |
| 124 | let stopReason; |
| 125 | const additionalContext = []; |
| 126 | const systemMessages = []; |
| 127 | for (const out of outputs) { |
| 128 | const r = rank(out.decision); |
| 129 | if (r > maxRank) maxRank = r; |
| 130 | if ((r === 3 || r === 2) && out.reason !== void 0 && out.reason.length > 0) { |
| 131 | const list2 = reasonsByRank.get(r) ?? []; |
| 132 | list2.push(out.reason); |
| 133 | reasonsByRank.set(r, list2); |
| 134 | } |
| 135 | if (out.continue === false && !stop) { |
| 136 | stop = true; |
| 137 | if (out.stopReason !== void 0) stopReason = out.stopReason; |
| 138 | } |
| 139 | if (out.additionalContext !== void 0 && out.additionalContext.length > 0) { |
| 140 | additionalContext.push(out.additionalContext); |
| 141 | } |
| 142 | if (out.systemMessage !== void 0 && out.systemMessage.length > 0) { |
| 143 | systemMessages.push(out.systemMessage); |
| 144 | } |
| 145 | } |
| 146 | const reasons = reasonsByRank.get(maxRank) ?? []; |
| 147 | return { |
| 148 | decision: decisionForRank(maxRank), |
| 149 | ...reasons.length > 0 ? { reason: reasons.join("\n\n") } : {}, |
| 150 | stop, |
| 151 | ...stopReason !== void 0 ? { stopReason } : {}, |
| 152 | additionalContext, |
| 153 | systemMessages |
| 154 | }; |
| 155 | } |
| 156 | |
| 157 | // src/json.ts |
| 158 | function isJson(value, depth = 0) { |
| 159 | if (depth > 64) return false; |
| 160 | if (value === null) return true; |
| 161 | switch (typeof value) { |
| 162 | case "boolean": |
| 163 | case "string": |
| 164 | return true; |
| 165 | case "number": |
| 166 | return Number.isFinite(value); |
| 167 | case "object": { |
| 168 | const array2 = Array.isArray(value); |
| 169 | if (!array2 && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false; |
| 170 | const keys = Reflect.ownKeys(value); |
| 171 | if (array2 && keys.length !== value.length + 1) return false; |
| 172 | for (const key of keys) { |
| 173 | if (array2 && key === "length") continue; |
| 174 | if (typeof key !== "string") return false; |
| 175 | if (array2 && (!/^(0|[1-9]\d*)$/u.test(key) || Number(key) >= value.length)) return false; |
| 176 | const descriptor = Object.getOwnPropertyDescriptor(value, key); |
| 177 | if (!descriptor.enumerable || !("value" in descriptor) || !isJson(descriptor.value, depth + 1)) return false; |
| 178 | } |
| 179 | return true; |
| 180 | } |
| 181 | default: |
| 182 | return false; |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // src/builtin/shared/web-adapters.ts |
| 187 | var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key); |
| 188 | function row(value) { |
| 189 | if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid captured web record"); |
| 190 | return value; |
| 191 | } |
| 192 | function text(value) { |
| 193 | if (typeof value !== "string") throw new Error("invalid captured web text"); |
| 194 | return value; |
| 195 | } |
| 196 | function string(value) { |
| 197 | return typeof value === "string" ? value : void 0; |
| 198 | } |
| 199 | function array(value) { |
| 200 | return Array.isArray(value) ? value : []; |
| 201 | } |
| 202 | function count(value, max = 10) { |
| 203 | if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new Error("invalid captured web count"); |
| 204 | return value; |
| 205 | } |
| 206 | function rustTrim(value) { |
| 207 | return value.replace(/^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, ""); |
| 208 | } |
| 209 | function firstPresent(value, keys) { |
| 210 | for (const key of keys) if (own(value, key)) return value[key]; |
| 211 | return void 0; |
| 212 | } |
| 213 | function firstText(value, keys) { |
| 214 | for (const key of keys) { |
| 215 | const found = string(value[key]); |
| 216 | if (found !== void 0) { |
| 217 | const trimmed = rustTrim(found); |
| 218 | if (trimmed) return trimmed; |
| 219 | } |
| 220 | } |
| 221 | return void 0; |
| 222 | } |
| 223 | function integer(facts, path) { |
| 224 | const value = facts[path]; |
| 225 | if (value === void 0) return void 0; |
| 226 | const number2 = row(value); |
| 227 | if (number2.i64 === null || number2.i64 === void 0) return void 0; |
| 228 | const result3 = text(number2.i64); |
| 229 | if (!/^-?\d{1,19}$/.test(result3) || BigInt(result3) < -9223372036854775808n || BigInt(result3) > 9223372036854775807n) throw new Error("invalid captured web integer"); |
| 230 | return result3; |
| 231 | } |
| 232 | function number(facts, path) { |
| 233 | const value = facts[path]; |
| 234 | if (value === void 0) return 0; |
| 235 | const result3 = Number(text(row(value).score)); |
| 236 | if (!Number.isFinite(result3)) throw new Error("invalid captured web score"); |
| 237 | return result3; |
| 238 | } |
| 239 | function result(metadata) { |
| 240 | return { ok: true, result: { success: true, content: "", metadata } }; |
| 241 | } |
| 242 | function filters(input) { |
| 243 | const recency = input.recency_days === null || input.recency_days === void 0 ? void 0 : count(input.recency_days, 3650); |
| 244 | const locale = input.locale === null || input.locale === void 0 ? void 0 : rustTrim(text(input.locale)); |
| 245 | const parts = locale?.split(/[-_]/); |
| 246 | const language = parts?.[0] !== void 0 && /^[A-Za-z]{2,3}$/.test(parts[0]) ? parts[0].toLowerCase() : null; |
| 247 | const region = parts?.[1] !== void 0 && /^[A-Za-z]{2}$/.test(parts[1]) ? parts[1].toUpperCase() : null; |
| 248 | const window = recency === void 0 ? null : recency <= 1 ? "day" : recency <= 7 ? "week" : recency <= 31 ? "month" : "year"; |
| 249 | return { kind: "web_filters", window, language, region }; |
| 250 | } |
| 251 | function validJson(value) { |
| 252 | const pending = [{ value, depth: 0 }]; |
| 253 | while (pending.length) { |
| 254 | const item = pending.pop(); |
| 255 | if (typeof item.value === "number" && !Number.isFinite(item.value)) return false; |
| 256 | if (typeof item.value === "string" && [...item.value].some((ch) => ch.length === 1 && ch.charCodeAt(0) >= 55296 && ch.charCodeAt(0) <= 57343)) return false; |
| 257 | if (item.value && typeof item.value === "object") { |
| 258 | if (item.depth >= 128) return false; |
| 259 | for (const child of Object.values(item.value)) pending.push({ value: child, depth: item.depth + 1 }); |
| 260 | } |
| 261 | } |
| 262 | return true; |
| 263 | } |
| 264 | function provider(input) { |
| 265 | const backend = text(input.backend), limit = count(input.max_results), parsed = row(input.parsed), facts = row(input.number_facts); |
| 266 | let entries2 = [], error = null; |
| 267 | let items = [], titleKeys = ["title"], urlKeys = ["url"], snippetKeys = ["content", "snippet"], trim2 = true, capSnippet = false, scorePath; |
| 268 | switch (backend) { |
| 269 | case "tavily": |
| 270 | items = array(parsed.results); |
| 271 | break; |
| 272 | case "firecrawl": { |
| 273 | const data2 = parsed.data; |
| 274 | items = array(data2 && typeof data2 === "object" && !Array.isArray(data2) && own(row(data2), "web") ? row(data2).web : data2); |
| 275 | snippetKeys = ["description", "markdown", "content"]; |
| 276 | capSnippet = true; |
| 277 | if (parsed.success === false) error = `Firecrawl search failed: ${firstText(parsed, ["error", "message"]) ?? "unknown API error"}`; |
| 278 | break; |
| 279 | } |
| 280 | case "metaso": { |
| 281 | items = array(parsed.webpages); |
| 282 | urlKeys = ["link"]; |
| 283 | snippetKeys = ["snippet", "summary"]; |
| 284 | const code = integer(facts, "/code"); |
| 285 | if (code !== void 0 && code !== "0") error = code === "3003" ? "Metaso: daily search limit reached — set METASO_API_KEY or get one at https://metaso.cn/search-api/playground" : code === "2005" ? "Metaso API key rejected — check METASO_API_KEY or set `[search] api_key` in config.toml" : `Metaso API error (code ${code}: ${string(parsed.message) ?? "unknown error"})`; |
| 286 | break; |
| 287 | } |
| 288 | case "bocha": { |
| 289 | const data2 = parsed.data && typeof parsed.data === "object" && !Array.isArray(parsed.data) ? row(parsed.data) : void 0; |
| 290 | let pages; |
| 291 | if (data2) { |
| 292 | const web = data2.webPages && typeof data2.webPages === "object" && !Array.isArray(data2.webPages) ? row(data2.webPages) : void 0; |
| 293 | pages = web && own(web, "value") ? web.value : data2.pages; |
| 294 | } |
| 295 | if (pages === void 0) pages = parsed.pages; |
| 296 | items = array(pages); |
| 297 | titleKeys = ["name", "title"]; |
| 298 | urlKeys = ["url", "link"]; |
| 299 | snippetKeys = ["summary", "snippet", "description"]; |
| 300 | const code = integer(facts, "/code"); |
| 301 | if (code !== void 0 && code !== "0" && code !== "200") error = `Bocha search API error (code ${code}: ${string(firstPresent(parsed, ["msg", "message"])) ?? "unknown error"})`; |
| 302 | break; |
| 303 | } |
| 304 | case "baidu": { |
| 305 | items = array(parsed.references); |
| 306 | titleKeys = ["title", "name"]; |
| 307 | urlKeys = ["url", "link"]; |
| 308 | snippetKeys = ["content", "snippet", "summary"]; |
| 309 | const key = own(parsed, "error_code") ? "error_code" : "code", code = integer(facts, `/${key}`); |
| 310 | if (code !== void 0 && code !== "0") error = `Baidu search API error (code ${code}: ${string(firstPresent(parsed, ["error_msg", "message"])) ?? "unknown error"})`; |
| 311 | break; |
| 312 | } |
| 313 | case "searxng": |
| 314 | items = array(parsed.results); |
| 315 | scorePath = "/results"; |
| 316 | break; |
| 317 | case "sofya": |
| 318 | items = array(parsed.results); |
| 319 | snippetKeys = ["content", "description"]; |
| 320 | trim2 = false; |
| 321 | break; |
| 322 | case "serply": |
| 323 | items = array(parsed.results); |
| 324 | urlKeys = ["link"]; |
| 325 | snippetKeys = ["description", "snippet"]; |
| 326 | trim2 = false; |
| 327 | break; |
| 328 | case "searchapi": |
| 329 | items = array(parsed.organic_results); |
| 330 | urlKeys = ["link"]; |
| 331 | snippetKeys = ["snippet"]; |
| 332 | trim2 = false; |
| 333 | break; |
| 334 | case "volcengine": { |
| 335 | if (own(parsed, "error")) { |
| 336 | const value = parsed.error && typeof parsed.error === "object" && !Array.isArray(parsed.error) ? row(parsed.error) : {}; |
| 337 | error = `Volcengine API error (code ${string(value.code) ?? "unknown"}: ${string(value.message) ?? "no details"})`; |
| 338 | } |
| 339 | let response; |
| 340 | const message = array(parsed.output).slice().reverse().find((value) => value && typeof value === "object" && !Array.isArray(value) && row(value).type === "message"); |
| 341 | if (message) { |
| 342 | const content = array(row(message).content).find((value) => value && typeof value === "object" && !Array.isArray(value) && typeof row(value).text === "string"); |
| 343 | if (content) response = text(row(content).text); |
| 344 | } |
| 345 | if (response === void 0 && error === null) error = "Volcengine response contains no output text"; |
| 346 | if (response !== void 0) { |
| 347 | let body = response; |
| 348 | const fence2 = response.indexOf("```json"); |
| 349 | if (fence2 >= 0) { |
| 350 | const rest = response.slice(fence2 + 7), end = rest.indexOf("```"); |
| 351 | if (end >= 0) body = rustTrim(rest.slice(0, end)); |
| 352 | else { |
| 353 | const first = response.indexOf("{"), last = response.lastIndexOf("}"); |
| 354 | if (first >= 0 && last >= first) body = response.slice(first, last + 1); |
| 355 | } |
| 356 | } else { |
| 357 | const first = response.indexOf("{"), last = response.lastIndexOf("}"); |
| 358 | if (first >= 0 && last >= first) body = response.slice(first, last + 1); |
| 359 | } |
| 360 | try { |
| 361 | const value = JSON.parse(body); |
| 362 | if (!validJson(value)) throw new Error("model JSON failed Core-compatible scalar/depth guard"); |
| 363 | if (value && typeof value === "object" && !Array.isArray(value)) items = array(row(value).results); |
| 364 | } catch { |
| 365 | items = []; |
| 366 | } |
| 367 | } |
| 368 | snippetKeys = ["snippet"]; |
| 369 | break; |
| 370 | } |
| 371 | default: |
| 372 | throw new Error("unadmitted web provider"); |
| 373 | } |
| 374 | const scored = []; |
| 375 | for (const [index, value] of items.entries()) { |
| 376 | if (!value || typeof value !== "object" || Array.isArray(value)) continue; |
| 377 | const item = row(value), rawTitle = string(firstPresent(item, titleKeys)), rawUrl = string(firstPresent(item, urlKeys)); |
| 378 | if (rawTitle === void 0 || rawUrl === void 0) continue; |
| 379 | const title = trim2 ? rustTrim(rawTitle) : rawTitle, url = trim2 ? rustTrim(rawUrl) : rawUrl; |
| 380 | if (trim2 && (!title || !url)) continue; |
| 381 | const presentSnippet = ["bocha", "baidu", "volcengine"].includes(backend); |
| 382 | const selected = presentSnippet ? string(firstPresent(item, snippetKeys)) : void 0; |
| 383 | const snippet = presentSnippet ? selected === void 0 ? void 0 : rustTrim(selected) || void 0 : firstText(item, snippetKeys); |
| 384 | const entry = { title, url, ...snippet === void 0 ? {} : { snippet: capSnippet ? [...snippet].slice(0, 1e3).join("") : snippet } }; |
| 385 | scored.push({ entry, score: scorePath === void 0 ? 0 : number(facts, `${scorePath}/${index}/score`) }); |
| 386 | if (scorePath === void 0 && scored.length === limit) break; |
| 387 | } |
| 388 | if (scorePath !== void 0) scored.sort((a, b) => a.score === b.score ? Object.is(a.score, -0) === Object.is(b.score, -0) ? 0 : Object.is(a.score, -0) ? 1 : -1 : a.score > b.score ? -1 : 1); |
| 389 | entries2 = scored.slice(0, limit).map((value) => value.entry); |
| 390 | return { kind: "web_provider", entries: entries2, error }; |
| 391 | } |
| 392 | function extraction(input) { |
| 393 | if (!Array.isArray(input.candidates) || input.candidates.length > 3) throw new Error("invalid captured web regions"); |
| 394 | const facts = []; |
| 395 | let previous = -1; |
| 396 | for (const value of input.candidates) { |
| 397 | const candidate = row(value), id = count(candidate.id, 2); |
| 398 | if (Object.keys(candidate).some((key) => !["id", "non_whitespace", "words"].includes(key)) || id <= previous) throw new Error("invalid ordered captured web region"); |
| 399 | previous = id; |
| 400 | facts.push({ id, chars: count(candidate.non_whitespace, 1e8), words: count(candidate.words, 1e8) }); |
| 401 | } |
| 402 | return { kind: "web_extract", candidate: facts.find((value) => value.chars >= 32 && value.words >= 5)?.id ?? null }; |
| 403 | } |
| 404 | function images(input) { |
| 405 | const limit = count(input.max_results), parsed = row(input.parsed); |
| 406 | if (!Array.isArray(parsed.results)) throw new Error("invalid captured image results"); |
| 407 | const entries2 = []; |
| 408 | for (const value of parsed.results) { |
| 409 | const entry = row(value), image = text(entry.image); |
| 410 | for (const key of ["thumbnail", "title", "url", "source"]) if (entry[key] !== null && entry[key] !== void 0) text(entry[key]); |
| 411 | for (const key of ["width", "height"]) if (entry[key] !== null && entry[key] !== void 0) count(entry[key], 4294967295); |
| 412 | if (!rustTrim(image)) continue; |
| 413 | entries2.push({ image, ...Object.fromEntries(["thumbnail", "title", "url", "source", "width", "height"].filter((key) => entry[key] !== null && entry[key] !== void 0).map((key) => [key, entry[key]])) }); |
| 414 | } |
| 415 | return { kind: "web_images", entries: entries2, max_results: limit }; |
| 416 | } |
| 417 | function request(input) { |
| 418 | const backend = text(input.backend), query = text(input.query), max = count(input.max_results); |
| 419 | const f = row(input.filters), window = f.window === null ? void 0 : text(f.window), region = f.region === null ? void 0 : text(f.region), language = f.language === null ? void 0 : text(f.language); |
| 420 | const locale = input.locale === null || input.locale === void 0 ? void 0 : text(input.locale); |
| 421 | let payload = null, pairs = []; |
| 422 | switch (backend) { |
| 423 | case "firecrawl": |
| 424 | payload = { query, limit: max, sources: [{ type: "web" }], ...window === void 0 ? {} : { tbs: `qdr:${window[0]}` }, ...region === void 0 ? {} : { country: region } }; |
| 425 | break; |
| 426 | case "tavily": |
| 427 | payload = { query, search_depth: "basic", max_results: max, ...window === void 0 ? {} : { time_range: window } }; |
| 428 | break; |
| 429 | case "bocha": |
| 430 | payload = { query, freshness: "noLimit", count: max }; |
| 431 | break; |
| 432 | case "metaso": |
| 433 | payload = { q: query, scope: "webpage", size: Math.max(1, Math.min(100, max)) }; |
| 434 | break; |
| 435 | case "sofya": |
| 436 | payload = { query, max_results: max }; |
| 437 | break; |
| 438 | case "baidu": |
| 439 | payload = { messages: [{ role: "user", content: query }], search_source: "baidu_search_v2", resource_type_filter: [{ type: "web", top_k: max }] }; |
| 440 | break; |
| 441 | case "volcengine": |
| 442 | payload = { input: [{ role: "user", content: [{ type: "input_text", text: `Search the web for: ${query} |
| 443 | |
| 444 | CRITICAL: Respond ONLY with a valid JSON object. No markdown, no explanation. |
| 445 | Schema: {"results":[{"title":"...","url":"https://...","snippet":"..."}]} |
| 446 | - results: 1-${max} most relevant pages |
| 447 | - title: page title (required) |
| 448 | - url: full URL starting with https:// (required) |
| 449 | - snippet: 1-2 sentence factual summary (required) |
| 450 | - If zero results: {"results":[]} |
| 451 | - Your entire response must be valid, parseable JSON.` }] }] }; |
| 452 | break; |
| 453 | case "serply": |
| 454 | pairs = [["q", query], ["num", String(max)], ...language === void 0 ? [] : [["hl", language]], ...region === void 0 ? [] : [["gl", region.toLowerCase()]]]; |
| 455 | break; |
| 456 | case "searchapi": |
| 457 | pairs = [["q", query], ["engine", "google"], ["num", String(max)], ...window === void 0 ? [] : [["time_period", `last_${window}`]], ...language === void 0 ? [] : [["hl", language]], ...region === void 0 ? [] : [["gl", region.toLowerCase()]]]; |
| 458 | break; |
| 459 | case "searxng": |
| 460 | pairs = [["q", query], ["format", "json"], ...window === void 0 ? [] : [["time_range", window]], ...locale === void 0 ? [] : [["language", locale]]]; |
| 461 | break; |
| 462 | case "bing": |
| 463 | case "duckduckgo": |
| 464 | pairs = [["q", query]]; |
| 465 | break; |
| 466 | default: |
| 467 | throw new Error("unadmitted web request provider"); |
| 468 | } |
| 469 | return { kind: "web_request", payload, pairs }; |
| 470 | } |
| 471 | function entries(input) { |
| 472 | if (!Array.isArray(input.entries)) throw new Error("invalid captured web candidates"); |
| 473 | const values = input.entries.map((value) => { |
| 474 | const item = row(value); |
| 475 | return { title: text(item.title), url: text(item.url), ...item.snippet === null || item.snippet === void 0 ? {} : { snippet: text(item.snippet) }, ...item.published === null || item.published === void 0 ? {} : { published: text(item.published) } }; |
| 476 | }); |
| 477 | return { kind: "web_entries", entries: values }; |
| 478 | } |
| 479 | function finalization(input) { |
| 480 | const requested = row(input.requested), capabilities = row(input.capabilities), counted = count(input.count); |
| 481 | if (!Array.isArray(input.degraded)) throw new Error("invalid captured web receipt"); |
| 482 | const degraded = input.degraded.map((value) => row(value)); |
| 483 | const ignored = (knob) => degraded.some((value) => row(value).kind === "knob_ignored" && row(value).knob === knob); |
| 484 | const honored = { max_results: capabilities.max_results === "supported", recency: false, domains: requested.domains === true, locale: false }; |
| 485 | for (const knob of ["recency", "locale"]) { |
| 486 | if (knob === "locale") { |
| 487 | if (!Array.isArray(input.domain_extra)) throw new Error("invalid captured domain receipt"); |
| 488 | degraded.push(...input.domain_extra.map((value) => row(value))); |
| 489 | } |
| 490 | if (requested[knob] === true && !ignored(knob)) { |
| 491 | if (capabilities[knob] === "supported") honored[knob] = true; |
| 492 | else degraded.push({ kind: "knob_ignored", knob }); |
| 493 | } |
| 494 | } |
| 495 | const hasNote = input.has_note === true; |
| 496 | const prefix = counted === 0 ? hasNote ? "No results found. " : "No results found" : `Found ${counted} result(s)${hasNote ? ". " : ""}`; |
| 497 | const suffix = degraded.some((value) => row(value).kind === "answer_cut_by_provider") ? "\n[the provider stopped the search answer at its output limit; the answer is incomplete]" : ""; |
| 498 | return { kind: "web_finalize", honored, degraded, prefix, suffix }; |
| 499 | } |
| 500 | function transformWebSnapshot(operation, value) { |
| 501 | const input = row(value); |
| 502 | switch (operation) { |
| 503 | case "web_request": |
| 504 | return result(request(input)); |
| 505 | case "web_entries": |
| 506 | return result(entries(input)); |
| 507 | case "web_finalize": |
| 508 | return result(finalization(input)); |
| 509 | case "web_filters": |
| 510 | return result(filters(input)); |
| 511 | case "web_provider": |
| 512 | return result(provider(input)); |
| 513 | case "web_extract": |
| 514 | return result(extraction(input)); |
| 515 | case "web_images": |
| 516 | return result(images(input)); |
| 517 | default: |
| 518 | throw new Error("unadmitted web adapter operation"); |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | // src/builtin/shared/github-adapter.ts |
| 523 | var REPOSITORY = "codewhale-hq/CodeWhale"; |
| 524 | function row2(value) { |
| 525 | if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid GitHub snapshot"); |
| 526 | return value; |
| 527 | } |
| 528 | function text2(value) { |
| 529 | if (typeof value !== "string") throw new Error("invalid GitHub text"); |
| 530 | return value; |
| 531 | } |
| 532 | function strings(value) { |
| 533 | if (!Array.isArray(value)) throw new Error("invalid GitHub list"); |
| 534 | return value.map(text2); |
| 535 | } |
| 536 | function githubSummary(value, limit) { |
| 537 | let out = "", index = 0; |
| 538 | for (const char of value) { |
| 539 | if (index++ >= Math.max(0, limit - 3)) return `${out}...`; |
| 540 | const code = char.codePointAt(0); |
| 541 | if ((code <= 31 || code >= 127 && code <= 159) && char !== "\n" && char !== " ") continue; |
| 542 | out += char; |
| 543 | } |
| 544 | return out; |
| 545 | } |
| 546 | function renderIssueReview(value) { |
| 547 | const report2 = row2(value), fields = row2(report2.fields), id = text2(report2.id); |
| 548 | let out = `# ${text2(fields.title)} |
| 549 | |
| 550 | Draft: ${id} |
| 551 | Status: ready for review |
| 552 | Publication: unavailable |
| 553 | Duplicate search: not performed |
| 554 | Destination: ${REPOSITORY} |
| 555 | |
| 556 | Review the contents before sharing. Redaction does not guarantee privacy. |
| 557 | `; |
| 558 | if (report2.revises !== null) out += `Revises: ${text2(report2.revises)} |
| 559 | `; |
| 560 | for (const [heading, key] of [["Expected behavior", "expected"], ["Actual behavior", "actual"], ["Impact", "impact"]]) out += ` |
| 561 | ## ${heading} |
| 562 | |
| 563 | ${text2(fields[key])} |
| 564 | `; |
| 565 | for (const [heading, key] of [["Steps to reproduce (agent reported)", "steps"], ["Observed by the agent", "observed"], ["Inferences (not verified)", "inferred"]]) { |
| 566 | const items = strings(fields[key]); |
| 567 | out += ` |
| 568 | ## ${heading} |
| 569 | |
| 570 | `; |
| 571 | out += items.length ? items.map((item) => `- ${item} |
| 572 | `).join("") : "None recorded.\n"; |
| 573 | } |
| 574 | out += ` |
| 575 | ## Runtime context |
| 576 | |
| 577 | - Codewhale: ${text2(report2.version)} |
| 578 | - Platform: ${text2(report2.platform)} |
| 579 | - Active model: ${text2(report2.model)} |
| 580 | `; |
| 581 | for (const [label, key] of [["Provider", "reported_provider"], ["Tool", "reported_tool"], ["Terminal", "reported_terminal"]]) out += `- ${label} (agent reported): ${fields[key] === null ? "unknown" : text2(fields[key])} |
| 582 | `; |
| 583 | if (!Array.isArray(fields.related_issues) || fields.related_issues.some((value2) => !Number.isInteger(value2) || Number(value2) < 1 || Number(value2) > 4294967295)) throw new Error("invalid related issue"); |
| 584 | if (fields.related_issues.length) out += "\n## Related issues (agent supplied; not verified or searched)\n\n" + fields.related_issues.map((number2) => `- [#${number2}](https://github.com/${REPOSITORY}/issues/${number2}) |
| 585 | `).join(""); |
| 586 | const redactions = strings(report2.redactions); |
| 587 | if (redactions.length) out += ` |
| 588 | Redacted categories: ${redactions.join(", ")} |
| 589 | `; |
| 590 | return out + ` |
| 591 | Review: \`/feedback review ${id}\` |
| 592 | Revise: \`/feedback edit ${id} <change>\` |
| 593 | `; |
| 594 | } |
| 595 | function transformGithubSnapshot(value) { |
| 596 | const snapshot = row2(value), action = text2(snapshot.action); |
| 597 | if (action === "report_draft" || action === "report_read" || action === "report_review") { |
| 598 | const report2 = row2(snapshot.report), id = text2(report2.id); |
| 599 | const review = renderIssueReview(report2); |
| 600 | const content2 = action === "report_review" ? review : JSON.stringify({ report_id: id, revises: report2.revises, state: "ready_for_review", publication: "unavailable", duplicate_search: "not_performed", review, artifact: `artifacts/issue-reports/${id}.json` }); |
| 601 | return { ok: true, result: { success: true, content: content2, metadata: null } }; |
| 602 | } |
| 603 | const number2 = text2(snapshot.number); |
| 604 | if (!/^[0-9]{1,20}$/.test(number2)) throw new Error("invalid captured issue number"); |
| 605 | if (action === "issue_context" || action === "pr_context") { |
| 606 | const raw = structuredClone(row2(snapshot.raw)), kind = action === "issue_context" ? "issue" : "pr"; |
| 607 | if (snapshot.large_body === true) { |
| 608 | const body = text2(raw.body); |
| 609 | raw.body_summary = githubSummary(body, 900); |
| 610 | raw.body_artifact = snapshot.body_artifact; |
| 611 | raw.body = githubSummary(body, 1200); |
| 612 | } |
| 613 | if (action === "pr_context" && snapshot.diff !== null) { |
| 614 | raw.diff_summary = githubSummary(text2(snapshot.diff), 900); |
| 615 | raw.diff_artifact = snapshot.diff_artifact; |
| 616 | } |
| 617 | const subject2 = kind === "issue" ? "Issue" : "PR"; |
| 618 | return { ok: true, result: { success: true, metadata: null, content: JSON.stringify({ summary: `${subject2} #${number2}: ${typeof raw.title === "string" ? raw.title : ""}`, [kind]: raw }) } }; |
| 619 | } |
| 620 | const target = text2(snapshot.target); |
| 621 | if (!["issue", "pr"].includes(target)) throw new Error("invalid captured GitHub target"); |
| 622 | const subject = target === "issue" ? "issue" : "PR"; |
| 623 | let content; |
| 624 | if (snapshot.dirty === true) content = `Refusing to close ${subject}: worktree is dirty and allow_dirty was false.`; |
| 625 | else if (action === "comment") content = snapshot.dry_run === true ? `Dry run: would comment on ${target} #${number2}.` : `Commented on ${target} #${number2}.`; |
| 626 | else if (action === "close_issue" || action === "close_pr") content = snapshot.dry_run === true ? `Dry run: would close ${subject} #${number2}.` : `Closed ${subject} #${number2}.`; |
| 627 | else throw new Error("unknown captured GitHub operation"); |
| 628 | return { ok: true, result: { success: snapshot.dirty !== true, content, metadata: null } }; |
| 629 | } |
| 630 | |
| 631 | // src/builtin/shared/review-adapter.ts |
| 632 | var REVIEW_LIMIT = 16 * 1024 * 1024; |
| 633 | var OPERATIONS = ["review_source_prompt", "review_pass_prompt", "review_interactive_pr", "review_report"]; |
| 634 | function isReviewOperation(value) { |
| 635 | return typeof value === "string" && OPERATIONS.includes(value); |
| 636 | } |
| 637 | function reviewEnvelopeBytes(value) { |
| 638 | return 8 + Buffer.byteLength(`{"jsonrpc":"2.0","id":18446744073709551615,"result":${JSON.stringify(value)}}`); |
| 639 | } |
| 640 | function row3(value) { |
| 641 | if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid Core review snapshot"); |
| 642 | return value; |
| 643 | } |
| 644 | function text3(value) { |
| 645 | if (typeof value !== "string") throw new Error("invalid Core review text"); |
| 646 | return value; |
| 647 | } |
| 648 | function bool2(value) { |
| 649 | if (typeof value !== "boolean") throw new Error("invalid Core review flag"); |
| 650 | return value; |
| 651 | } |
| 652 | function integer2(value) { |
| 653 | if (!Number.isSafeInteger(value) || value < 0) throw new Error("invalid Core review count"); |
| 654 | return value; |
| 655 | } |
| 656 | function list(value) { |
| 657 | if (!Array.isArray(value)) throw new Error("invalid Core review list"); |
| 658 | return value; |
| 659 | } |
| 660 | function optional(value) { |
| 661 | return value === null || value === void 0 ? void 0 : text3(value); |
| 662 | } |
| 663 | function trim(value) { |
| 664 | return value.replace(/^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, ""); |
| 665 | } |
| 666 | function lines(value) { |
| 667 | if (!value.length) return []; |
| 668 | const out = value.split("\n"); |
| 669 | if (value.endsWith("\n")) out.pop(); |
| 670 | return out.map((line, i) => (i < out.length - 1 || value.endsWith("\n")) && line.endsWith("\r") ? line.slice(0, -1) : line); |
| 671 | } |
| 672 | function skipped(value) { |
| 673 | return list(value).map((value2) => { |
| 674 | const skip = row3(value2); |
| 675 | return `${text3(skip.file)} (${integer2(skip.chars)} chars; ${text3(skip.reason)})`; |
| 676 | }).join(", "); |
| 677 | } |
| 678 | function ordered(value) { |
| 679 | if (Array.isArray(value)) return value.map(ordered); |
| 680 | if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value2]) => [key, ordered(value2)])); |
| 681 | return value; |
| 682 | } |
| 683 | function intent(value) { |
| 684 | const commits = value === void 0 ? "" : text3(value); |
| 685 | return commits.trim() ? `The author's commit messages for this range follow. They state what the change is meant to do; check them against the diff rather than trusting them. |
| 686 | |
| 687 | ${commits} |
| 688 | |
| 689 | End of commit messages. |
| 690 | |
| 691 | ` : ""; |
| 692 | } |
| 693 | function source(input) { |
| 694 | const kind = text3(input.kind); |
| 695 | if (kind === "file") { |
| 696 | const content = lines(text3(input.content)).map((line, i) => `${String(i + 1).padStart(4)} | ${line}`).join("\n"); |
| 697 | return `Review the following file and provide feedback. |
| 698 | Path: ${text3(input.display)} |
| 699 | |
| 700 | ${content} |
| 701 | |
| 702 | End of file.`; |
| 703 | } |
| 704 | if (kind === "diff") return `Review the following ${text3(input.label)} and provide feedback. |
| 705 | |
| 706 | ${text3(input.diff)} |
| 707 | |
| 708 | End of diff.`; |
| 709 | if (kind === "cli_diff") return `${intent(input.commits)}Review the following diff and provide feedback: |
| 710 | |
| 711 | ${text3(input.diff)} |
| 712 | |
| 713 | End of diff.`; |
| 714 | if (kind === "pr") return `Review the complete pull request diff (${text3(input.label)}) at head ${text3(input.head_sha)} and base ${text3(input.base_sha)}. Binary changes are represented by metadata; their contents are not semantically inspected. Exact binary object IDs remain in the review evidence. |
| 715 | |
| 716 | ${text3(input.diff)} |
| 717 | |
| 718 | End of diff.`; |
| 719 | throw new Error("unadmitted review source"); |
| 720 | } |
| 721 | function pass(input) { |
| 722 | const manifest = row3(input.manifest), part = row3(input.pass), view = row3(input.view); |
| 723 | const scope = list(manifest.skipped_files).length === 0 ? "Review only defects introduced in this pass." : `Review only defects introduced in this pass. This is a partial review (pass ${integer2(part.number)} of ${list(manifest.passes).length}): the gate did not read ${skipped(manifest.skipped_files)}. Do not claim full coverage.`; |
| 724 | const task = `${scope} Use supplementary source to check surrounding guards and declarations. If the prompt omits relevant caller bodies and read-only tools are offered, inspect those callers with the tools. Anchor findings to the commentable diff and scope coverage claims to the pass manifest. Binary changes are represented by metadata. No build or tests have been run.`; |
| 725 | if (!isJson(input.context)) throw new Error("invalid Core review context"); |
| 726 | const prompt = { |
| 727 | task, |
| 728 | untrusted_repository_data: true, |
| 729 | pull_request: { number: integer2(input.number), title: text3(view.title), description: text3(view.body) }, |
| 730 | manifest, |
| 731 | pass: part, |
| 732 | diff: text3(input.diff), |
| 733 | repository_context: input.context, |
| 734 | context_limit: "Context is bounded supplementary excerpts from the exact head. Null means no source context could fit. Missing files or omitted lines are not evidence of a defect." |
| 735 | }; |
| 736 | return JSON.stringify(bool2(input.sort_keys) ? ordered(prompt) : prompt); |
| 737 | } |
| 738 | function interactive(input) { |
| 739 | const view = row3(input.view), number2 = integer2(input.number); |
| 740 | const base = text3(view.base), head = text3(view.head); |
| 741 | const branches = base && head ? `${base} ← ${head}` : base || head || "(unknown)"; |
| 742 | return `Review PR #${number2} — ${trim(text3(view.title)) || `(PR #${number2})`} |
| 743 | |
| 744 | URL: ${text3(view.url) || "(unavailable)"} |
| 745 | Branches: ${branches} |
| 746 | Revision: ${text3(view.head_sha)} (base ${text3(view.base_sha)}); ${integer2(view.changed_files)} file patches. |
| 747 | Binary changes are represented by metadata; their contents are not semantically inspected. Exact binary object IDs remain in the review evidence. |
| 748 | |
| 749 | ## Description |
| 750 | |
| 751 | ${trim(text3(view.body)) || "(no description)"} |
| 752 | |
| 753 | ## Diff |
| 754 | |
| 755 | \`\`\`diff |
| 756 | ${text3(input.diff)} |
| 757 | \`\`\` |
| 758 | `; |
| 759 | } |
| 760 | function fence(value) { |
| 761 | let longest = 0, run = 0; |
| 762 | for (const char of value) { |
| 763 | run = char === "`" ? run + 1 : 0; |
| 764 | longest = Math.max(longest, run); |
| 765 | } |
| 766 | return "`".repeat(Math.max(3, longest + 1)); |
| 767 | } |
| 768 | function location(value) { |
| 769 | const path = optional(value.path); |
| 770 | return path === void 0 ? "" : value.line === null || value.line === void 0 ? `\`${trim(path)}\`` : `\`${trim(path)}:${integer2(value.line)}\``; |
| 771 | } |
| 772 | function report(input) { |
| 773 | if (input.review === null) return text3(input.output); |
| 774 | const review = row3(input.review), posted = bool2(input.posted); |
| 775 | let out = "## Codewhale review\n\n"; |
| 776 | const summary2 = text3(review.summary), assessment = text3(review.overall_assessment); |
| 777 | if (summary2.length) out += trim(summary2) + "\n\n"; |
| 778 | const issues = list(review.issues), suggestions = list(review.suggestions); |
| 779 | if (issues.length) { |
| 780 | out += "### Findings\n\n"; |
| 781 | for (const item of issues) { |
| 782 | const issue = row3(item), at = location(issue); |
| 783 | out += `- **[${text3(issue.severity).toUpperCase()}] ${text3(issue.title)}**${at ? ` (${at})` : ""} |
| 784 | `; |
| 785 | const description = text3(issue.description); |
| 786 | if (description.length) out += ` ${description} |
| 787 | `; |
| 788 | } |
| 789 | out += "\n"; |
| 790 | } |
| 791 | if (suggestions.length) { |
| 792 | out += "### Suggestions\n\n"; |
| 793 | for (const item of suggestions) { |
| 794 | const suggestion = row3(item), at = location(suggestion); |
| 795 | out += `- ${at ? `${at} — ` : ""}${text3(suggestion.suggestion)} |
| 796 | `; |
| 797 | const replacement = optional(suggestion.replacement); |
| 798 | if (replacement !== void 0 && trim(replacement).length) { |
| 799 | const codeFence = fence(replacement); |
| 800 | out += ` |
| 801 | ${codeFence}${posted ? "diff" : "suggestion"} |
| 802 | `; |
| 803 | for (const line of replacement.split("\n")) out += ` ${line} |
| 804 | `; |
| 805 | out += ` ${codeFence} |
| 806 | `; |
| 807 | } |
| 808 | } |
| 809 | out += "\n"; |
| 810 | } |
| 811 | if (assessment.length) out += "### Assessment\n\n" + trim(assessment) + "\n\n"; |
| 812 | const tally = { blocker: 0, concern: 0, nit: 0, introduced: 0, preexisting: 0 }; |
| 813 | for (const item of issues) { |
| 814 | const issue = row3(item), severity = text3(issue.severity); |
| 815 | if (severity === "blocker") tally.blocker += 1; |
| 816 | else if (severity === "concern") tally.concern += 1; |
| 817 | else if (severity === "nit") tally.nit += 1; |
| 818 | if (optional(issue.authorship) === "preexisting") tally.preexisting += 1; |
| 819 | else tally.introduced += 1; |
| 820 | } |
| 821 | out += `<!-- codewhale-review: {"blocker":${tally.blocker},"concern":${tally.concern},"nit":${tally.nit},"introduced":${tally.introduced},"preexisting":${tally.preexisting}} --> |
| 822 | `; |
| 823 | return out; |
| 824 | } |
| 825 | function transformReviewSnapshot(operation, value) { |
| 826 | if (!isReviewOperation(operation)) throw new Error("unadmitted review operation"); |
| 827 | const input = row3(value); |
| 828 | const content = operation === "review_source_prompt" ? source(input) : operation === "review_pass_prompt" ? pass(input) : operation === "review_interactive_pr" ? interactive(input) : report(input); |
| 829 | const result3 = { ok: true, result: { content, success: true, metadata: null } }; |
| 830 | if (reviewEnvelopeBytes(result3) > REVIEW_LIMIT) throw new Error("serialized review result exceeds 16 MiB"); |
| 831 | return result3; |
| 832 | } |
| 833 | |
| 834 | // src/builtin/shared/stock-adapters.ts |
| 835 | var MAX_SNAPSHOT = 1024 * 1024; |
| 836 | function row4(value) { |
| 837 | if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid adapter snapshot"); |
| 838 | return value; |
| 839 | } |
| 840 | function text4(value) { |
| 841 | if (typeof value !== "string") throw new Error("invalid adapter text"); |
| 842 | return value; |
| 843 | } |
| 844 | function optionalText(value) { |
| 845 | return value === null || value === void 0 ? void 0 : text4(value); |
| 846 | } |
| 847 | function result2(success, metadata, content = "") { |
| 848 | return { ok: true, result: { success, content, metadata } }; |
| 849 | } |
| 850 | function asciiLower(value) { |
| 851 | return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase()); |
| 852 | } |
| 853 | function summary(value, format) { |
| 854 | const descriptor = row4(value); |
| 855 | const kind = text4(descriptor.kind); |
| 856 | const accepted = format === "json" ? ["object", "array", "string", "number", "boolean", "null"] : ["table", "array", "string", "integer", "float", "boolean", "datetime"]; |
| 857 | if (!accepted.includes(kind)) throw new Error("invalid captured parser kind"); |
| 858 | if (kind === "object" || kind === "table") { |
| 859 | if (!Array.isArray(descriptor.keys) || descriptor.keys.some((key) => typeof key !== "string")) throw new Error("invalid captured parser keys"); |
| 860 | const keys = descriptor.keys; |
| 861 | if (new Set(keys).size !== keys.length) throw new Error("duplicate captured parser keys"); |
| 862 | return { top_level: kind, entries: keys.length, keys_preview: keys.slice(0, 10) }; |
| 863 | } |
| 864 | if (kind === "array") { |
| 865 | if (!Number.isSafeInteger(descriptor.entries) || descriptor.entries < 0) throw new Error("invalid captured array count"); |
| 866 | return { top_level: kind, entries: descriptor.entries }; |
| 867 | } |
| 868 | return { top_level: kind }; |
| 869 | } |
| 870 | function data(input) { |
| 871 | const format = text4(input.format); |
| 872 | if (!["auto", "json", "toml"].includes(format)) throw new Error("invalid captured data format"); |
| 873 | const source2 = text4(input.source); |
| 874 | const extension = optionalText(input.extension); |
| 875 | const requested = format === "auto" && (extension === "json" || extension === "toml") ? extension : format; |
| 876 | const json = row4(input.json); |
| 877 | const toml = row4(input.toml); |
| 878 | if (typeof json.ok !== "boolean" || typeof toml.ok !== "boolean") throw new Error("invalid captured parser result"); |
| 879 | const use = (parser, selected) => { |
| 880 | if (parser.ok) return result2(true, { valid: true, format: selected, source: source2, summary: summary(parser.value, selected) }); |
| 881 | const error = text4(parser.error); |
| 882 | return result2(false, { valid: false, format: selected, source: source2, error }, `Invalid ${selected.toUpperCase()}: ${error}`); |
| 883 | }; |
| 884 | if (requested === "json") return use(json, "json"); |
| 885 | if (requested === "toml") return use(toml, "toml"); |
| 886 | if (json.ok) return use(json, "json"); |
| 887 | if (toml.ok) return use(toml, "toml"); |
| 888 | return result2(false, { valid: false, format: "auto", source: source2, json_error: text4(json.error), toml_error: text4(toml.error) }, "Validation failed in auto mode: content is neither valid JSON nor TOML."); |
| 889 | } |
| 890 | function rustTrim2(value) { |
| 891 | return value.replace(/^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, ""); |
| 892 | } |
| 893 | function bool3(value) { |
| 894 | if (typeof value !== "boolean") throw new Error("invalid captured boolean"); |
| 895 | return value; |
| 896 | } |
| 897 | function speech(operation, input) { |
| 898 | const surface = text4(input.surface); |
| 899 | if (surface !== "tool" && surface !== "cli") throw new Error("invalid speech surface"); |
| 900 | const tool = surface === "tool"; |
| 901 | const invalid = (error) => result2(false, { error }); |
| 902 | if (operation === "speech_format") { |
| 903 | const raw = text4(input.format); |
| 904 | const format = asciiLower(rustTrim2(raw)); |
| 905 | if (input.minimax === true) { |
| 906 | const wire = format === "pcm16" ? "pcm" : format; |
| 907 | return ["mp3", "wav", "flac", "pcm"].includes(wire) ? result2(true, { format: wire }) : invalid("unsupported MiniMax speech format"); |
| 908 | } |
| 909 | if (format === "wav" || format === "mp3" || format === "pcm16" || format === "pcm") return result2(true, { format: format === "pcm" ? "pcm16" : format }); |
| 910 | return invalid(tool ? `unsupported speech format '${raw}' (allowed: wav, mp3, pcm16)` : `Unsupported speech format '${raw}' (allowed: wav, mp3, pcm16)`); |
| 911 | } |
| 912 | const modelHint = optionalText(input.model); |
| 913 | const hasClone = bool3(input.has_clone_path); |
| 914 | const hasVoice = bool3(input.has_voice); |
| 915 | const nonemptyVoice = bool3(input.voice_nonempty); |
| 916 | const dataUri = bool3(input.voice_is_data_uri); |
| 917 | if ((nonemptyVoice || dataUri) && !hasVoice) throw new Error("inconsistent captured voice presence"); |
| 918 | const instructionInput = optionalText(input.instruction); |
| 919 | const promptInput = optionalText(input.voice_prompt); |
| 920 | if (input.minimax === true) { |
| 921 | if (!modelHint || hasClone || dataUri || instructionInput !== void 0 || promptInput !== void 0) return invalid("MiniMax speech accepts spoken text and a voice ID"); |
| 922 | return result2(true, { model: modelHint, instruction: null, voice: nonemptyVoice ? "raw" : "default" }); |
| 923 | } |
| 924 | if (hasClone && hasVoice) return invalid(tool ? "use either clone_voice or voice for cloned voice data, not both" : "Use either --clone-voice or --voice for cloned voice data, not both"); |
| 925 | const model = modelHint ?? (hasClone || dataUri ? "mimo-v2.5-tts-voiceclone" : promptInput !== void 0 ? "mimo-v2.5-tts-voicedesign" : "mimo-v2.5-tts"); |
| 926 | const lower = asciiLower(model); |
| 927 | if (!lower.includes("tts")) { |
| 928 | const examples = "mimo-v2.5-tts, mimo-v2.5-tts-voicedesign, mimo-v2.5-tts-voiceclone, mimo-v2-tts"; |
| 929 | return invalid(tool ? `speech tool requires a TTS model (examples: ${examples}), got '${model}'` : `speech requires a TTS model (examples: ${examples}); got ${model}`); |
| 930 | } |
| 931 | const parts = [promptInput, instructionInput].map((value) => value === void 0 ? void 0 : rustTrim2(value)).filter((value) => value !== void 0 && value !== ""); |
| 932 | const instruction = parts.length ? parts.join("\n\n") : null; |
| 933 | if (lower.includes("voicedesign") && instruction === null) return invalid(tool ? "mimo-v2.5-tts-voicedesign requires voice_prompt or instruction" : "mimo-v2.5-tts-voicedesign requires --voice-prompt or --instruction to describe the voice"); |
| 934 | let voice; |
| 935 | if (hasClone) voice = "clone"; |
| 936 | else if (lower.includes("voicedesign")) voice = "omit"; |
| 937 | else if (nonemptyVoice) voice = "raw"; |
| 938 | else if (lower.includes("voiceclone")) return invalid(tool ? "mimo-v2.5-tts-voiceclone requires clone_voice <mp3|wav> or voice <data-uri>" : "mimo-v2.5-tts-voiceclone requires --clone-voice <mp3|wav> or --voice <data-uri>"); |
| 939 | else voice = "default"; |
| 940 | return result2(true, { model, instruction, voice }); |
| 941 | } |
| 942 | function pdfProjection(input) { |
| 943 | const state = text4(input.state); |
| 944 | const decision = (code2, message) => result2(true, { kind: "pdf_decision", code: code2, ...message === void 0 ? {} : { message } }); |
| 945 | if (state !== "complete") { |
| 946 | if (!["binary_unavailable", "cancelled", "timed_out", "execution"].includes(state)) throw new Error("invalid PDF process state"); |
| 947 | return decision(state, text4(input.message)); |
| 948 | } |
| 949 | const success = bool3(input.success); |
| 950 | const stdoutOverflow = bool3(input.stdout_truncated); |
| 951 | const stderrOverflow = bool3(input.stderr_truncated); |
| 952 | const stderr = text4(input.stderr); |
| 953 | const code = input.exit_code; |
| 954 | if (code !== null && (!Number.isInteger(code) || code < -2147483648 || code > 2147483647)) throw new Error("invalid PDF exit code"); |
| 955 | if (stdoutOverflow) return decision("execution", "pdftotext output exceeded the 16777216 byte safety limit"); |
| 956 | if (!success) return decision("execution", `pdftotext failed (exit ${code === null ? "None" : `Some(${code})`}): ${stderr || "no diagnostic output"}${stderrOverflow ? " [truncated]" : ""}`); |
| 957 | return decision("success"); |
| 958 | } |
| 959 | function ocrProjection(input) { |
| 960 | const decision = (code2, trim_end = false, message) => result2(true, { kind: "ocr_decision", code: code2, trim_end, ...message === void 0 ? {} : { message } }); |
| 961 | const state = text4(input.state), status = text4(input.status); |
| 962 | if (state === "native") { |
| 963 | if (Object.keys(input).some((key) => !["kind", "state", "status", "can_fallback", "next_ticket"].includes(key)) || !["success", "error", "unavailable"].includes(status)) throw new Error("invalid OCR Native projection"); |
| 964 | const fallback = bool3(input.can_fallback); |
| 965 | if (status === "success") { |
| 966 | if (fallback || input.next_ticket !== void 0) throw new Error("successful OCR Native step cannot launch fallback"); |
| 967 | return decision("native_success"); |
| 968 | } |
| 969 | if (fallback) { |
| 970 | if (typeof input.next_ticket !== "string" || input.next_ticket.length < 1 || input.next_ticket.length > 256) throw new Error("OCR fallback has no exact continuation grant"); |
| 971 | return decision("fallback"); |
| 972 | } |
| 973 | if (input.next_ticket !== void 0) throw new Error("OCR fallback is not admitted"); |
| 974 | if (status === "error") return decision("native_error"); |
| 975 | return decision("no_backend", false, "image_ocr: no local OCR backend is available. On macOS, update to a version with the Vision framework; on Linux/Windows install tesseract and restart codewhale."); |
| 976 | } |
| 977 | if (state !== "tesseract") throw new Error("invalid OCR process stage"); |
| 978 | if (status === "fault") { |
| 979 | if (Object.keys(input).some((key) => !["kind", "state", "status"].includes(key))) throw new Error("invalid OCR fault projection"); |
| 980 | return decision("fault"); |
| 981 | } |
| 982 | if (status !== "complete" || Object.keys(input).some((key) => !["kind", "state", "status", "success", "exit_code"].includes(key))) throw new Error("invalid OCR Tesseract projection"); |
| 983 | const success = bool3(input.success), code = input.exit_code; |
| 984 | if (code !== null && (!Number.isInteger(code) || code < -2147483648 || code > 2147483647)) throw new Error("invalid OCR exit code"); |
| 985 | return success ? decision("tesseract_success", true) : decision("execution", false, `tesseract failed (exit ${code === null ? "None" : `Some(${code})`}): `); |
| 986 | } |
| 987 | function transformStockSnapshot(value) { |
| 988 | const snapshot = row4(value); |
| 989 | const review = snapshot.kind === "stock_adapter" && isReviewOperation(snapshot.operation); |
| 990 | if (review ? reviewEnvelopeBytes(snapshot) > REVIEW_LIMIT : Buffer.byteLength(JSON.stringify(value)) > MAX_SNAPSHOT) throw new Error(review ? "serialized review snapshot/envelope exceeds 16 MiB" : "adapter snapshot exceeds 1 MiB"); |
| 991 | if (snapshot.kind === "ocr_process") return ocrProjection(snapshot); |
| 992 | if (snapshot.kind === "pdf_process") return pdfProjection(snapshot); |
| 993 | if (snapshot.kind !== "stock_adapter") throw new Error("invalid adapter projection"); |
| 994 | const input = row4(snapshot.input); |
| 995 | if (review) return transformReviewSnapshot(snapshot.operation, input); |
| 996 | switch (snapshot.operation) { |
| 997 | case "web_filters": |
| 998 | case "web_request": |
| 999 | case "web_provider": |
| 1000 | case "web_entries": |
| 1001 | case "web_finalize": |
| 1002 | case "web_extract": |
| 1003 | case "web_images": |
| 1004 | return transformWebSnapshot(snapshot.operation, input); |
| 1005 | case "github_result": |
| 1006 | return transformGithubSnapshot(input); |
| 1007 | case "validate_data": |
| 1008 | return data(input); |
| 1009 | case "speech_options": |
| 1010 | case "speech_format": |
| 1011 | return speech(snapshot.operation, input); |
| 1012 | default: |
| 1013 | throw new Error("unadmitted adapter operation"); |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | // src/builtin/harness.ts |
| 1018 | var MAX_PENDING = 32; |
| 1019 | var MAX_STDOUT = 1024 * 1024; |
| 1020 | var MAX_STDERR = 64 * 1024; |
| 1021 | function normalizeOutput(value) { |
| 1022 | const out = value; |
| 1023 | if (!out || typeof out.success !== "boolean" || typeof out.stdout !== "string" || typeof out.stderr !== "string" || Buffer.byteLength(out.stdout) > MAX_STDOUT || Buffer.byteLength(out.stderr) > MAX_STDERR) throw new Error("invalid or oversized execution output"); |
| 1024 | if (!out.success) return { ok: false, error: out.stderr ? out.stdout ? `${out.stdout} |
| 1025 | ${out.stderr}` : out.stderr : out.stdout }; |
| 1026 | try { |
| 1027 | const result3 = JSON.parse(out.stdout); |
| 1028 | if (result3 && typeof result3.content === "string" && typeof result3.success === "boolean" && (result3.metadata === void 0 || isJson(result3.metadata))) { |
| 1029 | return { ok: true, result: { content: result3.content, success: result3.success, ...result3.metadata === void 0 ? {} : { metadata: result3.metadata } } }; |
| 1030 | } |
| 1031 | } catch { |
| 1032 | } |
| 1033 | return { ok: true, result: { content: out.stdout, success: true } }; |
| 1034 | } |
| 1035 | function createHarnessModule(rpc, reference) { |
| 1036 | if (reference.plugin_id !== "host:harness") throw new Error("execution runner requires its builtin owner"); |
| 1037 | const owner = Object.freeze(structuredClone(reference)); |
| 1038 | const stop = new AbortController(); |
| 1039 | const pending = /* @__PURE__ */ new Map(); |
| 1040 | let disposed = false; |
| 1041 | return { |
| 1042 | async run(params, signal) { |
| 1043 | if (disposed || signal.aborted || params.owner.plugin_id !== owner.plugin_id || params.owner.generation !== owner.generation || params.owner.owner_token !== owner.owner_token) throw new Error("execution runner owner is stale or cancelled"); |
| 1044 | if (!params.execution_id || !params.ticket || !Number.isSafeInteger(params.deadline_ms) || params.deadline_ms < 1 || params.deadline_ms > (params.hook ? 2147483647 : 12e4) || pending.size >= MAX_PENDING || pending.has(params.execution_id)) throw new Error("execution is not admitted"); |
| 1045 | if (params.hook) { |
| 1046 | const { event, dialect, point, matcher, query } = params.hook; |
| 1047 | if (typeof event !== "string" || typeof point !== "string" || typeof query !== "string" || query.length > 1024 || matcher !== void 0 && (typeof matcher !== "string" || matcher.length > 1024) || !["codewhale", "claude-code", "codex"].includes(dialect)) throw new Error("invalid hook projection"); |
| 1048 | if (dialect !== "codewhale" && !matchesMatcher(matcher, query, dialect)) return { ok: true, hook_skipped: true }; |
| 1049 | } |
| 1050 | const abort = new AbortController(); |
| 1051 | const cancel = () => abort.abort(); |
| 1052 | signal.addEventListener("abort", cancel, { once: true }); |
| 1053 | stop.signal.addEventListener("abort", cancel, { once: true }); |
| 1054 | const timer = setTimeout(cancel, params.deadline_ms); |
| 1055 | const done = (async () => { |
| 1056 | const cancelled = new Promise((_, reject) => { |
| 1057 | abort.signal.addEventListener("abort", () => reject(new Error("execution cancelled")), { once: true }); |
| 1058 | }); |
| 1059 | let value = await Promise.race([rpc.request("exec/redeem", { owner, execution_id: params.execution_id, ticket: params.ticket }, abort.signal), cancelled]); |
| 1060 | if (disposed || abort.signal.aborted) throw new Error("execution cancelled"); |
| 1061 | if (params.hook) { |
| 1062 | const out = value; |
| 1063 | if (!out || out.kind !== "hook" || out.event !== params.hook.event || typeof out.success !== "boolean" || out.exit_code !== null && !Number.isInteger(out.exit_code)) throw new Error("invalid hook completion projection"); |
| 1064 | if (params.hook.event === "shell_env") { |
| 1065 | if ("stdout" in out || "stderr" in out || Object.keys(out).some((key) => !["kind", "event", "success", "exit_code", "keys"].includes(key))) throw new Error("ShellEnv projection contains private process data"); |
| 1066 | return { ok: true, hook_completed: true }; |
| 1067 | } |
| 1068 | if (params.hook.dialect === "codewhale") return { ok: true, hook_completed: true }; |
| 1069 | if (typeof out.stdout !== "string" || typeof out.stderr !== "string" || Buffer.byteLength(out.stdout) > 65536 || Buffer.byteLength(out.stderr) > 65536) throw new Error("invalid dialect hook output"); |
| 1070 | const decoded = parseHookOutput(out.exit_code === null ? void 0 : out.exit_code, out.stdout, out.stderr, params.hook.point); |
| 1071 | const merged = mergeHookOutputs([decoded]); |
| 1072 | if (params.hook.event === "tool_call_before") return { ok: true, hook_completed: true, proposal: JSON.stringify({ ...merged.decision === "deny" ? { decision: "deny", reason: merged.reason ?? "Blocked by hook" } : merged.decision === "ask" && params.hook.dialect !== "codex" ? { decision: "ask", reason: merged.reason } : {}, ...merged.additionalContext.length ? { additional_context: merged.additionalContext.join("\n\n") } : {} }) }; |
| 1073 | if (params.hook.event === "message_submit" && (merged.stop || decoded.updatedInput !== void 0 || merged.additionalContext.length)) throw new Error("hook requested unsupported prompt steering"); |
| 1074 | if (params.hook.event === "message_submit") return { ok: true, hook_completed: true, proposal: JSON.stringify(merged.decision === "deny" ? { block: true, reason: merged.reason ?? "Blocked by hook" } : {}) }; |
| 1075 | if (merged.stop || merged.decision === "deny" || decoded.updatedInput !== void 0 || merged.additionalContext.length) throw new Error("hook requested steering unavailable at this observer boundary"); |
| 1076 | return { ok: true, hook_completed: true }; |
| 1077 | } |
| 1078 | if (value && typeof value === "object" && value.kind === "ocr_process") { |
| 1079 | if (value.state !== "native") throw new Error("OCR must begin with its admitted Native step"); |
| 1080 | const first = transformStockSnapshot(value); |
| 1081 | if (first.result.metadata.code !== "fallback") return first; |
| 1082 | const next = value.next_ticket; |
| 1083 | value = await Promise.race([rpc.request("exec/redeem", { owner, execution_id: params.execution_id, ticket: next }, abort.signal), cancelled]); |
| 1084 | if (disposed || abort.signal.aborted) throw new Error("execution cancelled"); |
| 1085 | if (!value || typeof value !== "object" || value.kind !== "ocr_process" || value.state !== "tesseract") throw new Error("OCR continuation returned the wrong stage"); |
| 1086 | return transformStockSnapshot(value); |
| 1087 | } |
| 1088 | if (value && typeof value === "object" && ["stock_adapter", "pdf_process"].includes(String(value.kind))) return transformStockSnapshot(value); |
| 1089 | return normalizeOutput(value); |
| 1090 | })(); |
| 1091 | pending.set(params.execution_id, { abort, done }); |
| 1092 | try { |
| 1093 | return await done; |
| 1094 | } finally { |
| 1095 | clearTimeout(timer); |
| 1096 | signal.removeEventListener("abort", cancel); |
| 1097 | stop.signal.removeEventListener("abort", cancel); |
| 1098 | pending.delete(params.execution_id); |
| 1099 | } |
| 1100 | }, |
| 1101 | async dispose() { |
| 1102 | if (disposed) return; |
| 1103 | disposed = true; |
| 1104 | stop.abort(); |
| 1105 | await Promise.allSettled([...pending.values()].map((row5) => row5.done)); |
| 1106 | } |
| 1107 | }; |
| 1108 | } |
| 1109 | export { |
| 1110 | createHarnessModule, |
| 1111 | normalizeOutput |
| 1112 | }; |
| 1113 |