返回 CodeWhale
stock-adapters.mjs
根目录 / crates / engine / extension-host / dist / stock-adapters.mjs
1 // src/builtin/shared/web-adapters.ts
2 var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
3 function row(value) {
4 if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid captured web record");
5 return value;
6 }
7 function text(value) {
8 if (typeof value !== "string") throw new Error("invalid captured web text");
9 return value;
10 }
11 function string(value) {
12 return typeof value === "string" ? value : void 0;
13 }
14 function array(value) {
15 return Array.isArray(value) ? value : [];
16 }
17 function count(value, max = 10) {
18 if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new Error("invalid captured web count");
19 return value;
20 }
21 function rustTrim(value) {
22 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, "");
23 }
24 function firstPresent(value, keys) {
25 for (const key of keys) if (own(value, key)) return value[key];
26 return void 0;
27 }
28 function firstText(value, keys) {
29 for (const key of keys) {
30 const found = string(value[key]);
31 if (found !== void 0) {
32 const trimmed = rustTrim(found);
33 if (trimmed) return trimmed;
34 }
35 }
36 return void 0;
37 }
38 function integer(facts, path) {
39 const value = facts[path];
40 if (value === void 0) return void 0;
41 const number2 = row(value);
42 if (number2.i64 === null || number2.i64 === void 0) return void 0;
43 const result3 = text(number2.i64);
44 if (!/^-?\d{1,19}$/.test(result3) || BigInt(result3) < -9223372036854775808n || BigInt(result3) > 9223372036854775807n) throw new Error("invalid captured web integer");
45 return result3;
46 }
47 function number(facts, path) {
48 const value = facts[path];
49 if (value === void 0) return 0;
50 const result3 = Number(text(row(value).score));
51 if (!Number.isFinite(result3)) throw new Error("invalid captured web score");
52 return result3;
53 }
54 function result(metadata) {
55 return { ok: true, result: { success: true, content: "", metadata } };
56 }
57 function filters(input) {
58 const recency = input.recency_days === null || input.recency_days === void 0 ? void 0 : count(input.recency_days, 3650);
59 const locale = input.locale === null || input.locale === void 0 ? void 0 : rustTrim(text(input.locale));
60 const parts = locale?.split(/[-_]/);
61 const language = parts?.[0] !== void 0 && /^[A-Za-z]{2,3}$/.test(parts[0]) ? parts[0].toLowerCase() : null;
62 const region = parts?.[1] !== void 0 && /^[A-Za-z]{2}$/.test(parts[1]) ? parts[1].toUpperCase() : null;
63 const window = recency === void 0 ? null : recency <= 1 ? "day" : recency <= 7 ? "week" : recency <= 31 ? "month" : "year";
64 return { kind: "web_filters", window, language, region };
65 }
66 function validJson(value) {
67 const pending = [{ value, depth: 0 }];
68 while (pending.length) {
69 const item = pending.pop();
70 if (typeof item.value === "number" && !Number.isFinite(item.value)) return false;
71 if (typeof item.value === "string" && [...item.value].some((ch) => ch.length === 1 && ch.charCodeAt(0) >= 55296 && ch.charCodeAt(0) <= 57343)) return false;
72 if (item.value && typeof item.value === "object") {
73 if (item.depth >= 128) return false;
74 for (const child of Object.values(item.value)) pending.push({ value: child, depth: item.depth + 1 });
75 }
76 }
77 return true;
78 }
79 function provider(input) {
80 const backend = text(input.backend), limit = count(input.max_results), parsed = row(input.parsed), facts = row(input.number_facts);
81 let entries2 = [], error = null;
82 let items = [], titleKeys = ["title"], urlKeys = ["url"], snippetKeys = ["content", "snippet"], trim2 = true, capSnippet = false, scorePath;
83 switch (backend) {
84 case "tavily":
85 items = array(parsed.results);
86 break;
87 case "firecrawl": {
88 const data2 = parsed.data;
89 items = array(data2 && typeof data2 === "object" && !Array.isArray(data2) && own(row(data2), "web") ? row(data2).web : data2);
90 snippetKeys = ["description", "markdown", "content"];
91 capSnippet = true;
92 if (parsed.success === false) error = `Firecrawl search failed: ${firstText(parsed, ["error", "message"]) ?? "unknown API error"}`;
93 break;
94 }
95 case "metaso": {
96 items = array(parsed.webpages);
97 urlKeys = ["link"];
98 snippetKeys = ["snippet", "summary"];
99 const code = integer(facts, "/code");
100 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"})`;
101 break;
102 }
103 case "bocha": {
104 const data2 = parsed.data && typeof parsed.data === "object" && !Array.isArray(parsed.data) ? row(parsed.data) : void 0;
105 let pages;
106 if (data2) {
107 const web = data2.webPages && typeof data2.webPages === "object" && !Array.isArray(data2.webPages) ? row(data2.webPages) : void 0;
108 pages = web && own(web, "value") ? web.value : data2.pages;
109 }
110 if (pages === void 0) pages = parsed.pages;
111 items = array(pages);
112 titleKeys = ["name", "title"];
113 urlKeys = ["url", "link"];
114 snippetKeys = ["summary", "snippet", "description"];
115 const code = integer(facts, "/code");
116 if (code !== void 0 && code !== "0" && code !== "200") error = `Bocha search API error (code ${code}: ${string(firstPresent(parsed, ["msg", "message"])) ?? "unknown error"})`;
117 break;
118 }
119 case "baidu": {
120 items = array(parsed.references);
121 titleKeys = ["title", "name"];
122 urlKeys = ["url", "link"];
123 snippetKeys = ["content", "snippet", "summary"];
124 const key = own(parsed, "error_code") ? "error_code" : "code", code = integer(facts, `/${key}`);
125 if (code !== void 0 && code !== "0") error = `Baidu search API error (code ${code}: ${string(firstPresent(parsed, ["error_msg", "message"])) ?? "unknown error"})`;
126 break;
127 }
128 case "searxng":
129 items = array(parsed.results);
130 scorePath = "/results";
131 break;
132 case "sofya":
133 items = array(parsed.results);
134 snippetKeys = ["content", "description"];
135 trim2 = false;
136 break;
137 case "serply":
138 items = array(parsed.results);
139 urlKeys = ["link"];
140 snippetKeys = ["description", "snippet"];
141 trim2 = false;
142 break;
143 case "searchapi":
144 items = array(parsed.organic_results);
145 urlKeys = ["link"];
146 snippetKeys = ["snippet"];
147 trim2 = false;
148 break;
149 case "volcengine": {
150 if (own(parsed, "error")) {
151 const value = parsed.error && typeof parsed.error === "object" && !Array.isArray(parsed.error) ? row(parsed.error) : {};
152 error = `Volcengine API error (code ${string(value.code) ?? "unknown"}: ${string(value.message) ?? "no details"})`;
153 }
154 let response;
155 const message = array(parsed.output).slice().reverse().find((value) => value && typeof value === "object" && !Array.isArray(value) && row(value).type === "message");
156 if (message) {
157 const content = array(row(message).content).find((value) => value && typeof value === "object" && !Array.isArray(value) && typeof row(value).text === "string");
158 if (content) response = text(row(content).text);
159 }
160 if (response === void 0 && error === null) error = "Volcengine response contains no output text";
161 if (response !== void 0) {
162 let body = response;
163 const fence2 = response.indexOf("```json");
164 if (fence2 >= 0) {
165 const rest = response.slice(fence2 + 7), end = rest.indexOf("```");
166 if (end >= 0) body = rustTrim(rest.slice(0, end));
167 else {
168 const first = response.indexOf("{"), last = response.lastIndexOf("}");
169 if (first >= 0 && last >= first) body = response.slice(first, last + 1);
170 }
171 } else {
172 const first = response.indexOf("{"), last = response.lastIndexOf("}");
173 if (first >= 0 && last >= first) body = response.slice(first, last + 1);
174 }
175 try {
176 const value = JSON.parse(body);
177 if (!validJson(value)) throw new Error("model JSON failed Core-compatible scalar/depth guard");
178 if (value && typeof value === "object" && !Array.isArray(value)) items = array(row(value).results);
179 } catch {
180 items = [];
181 }
182 }
183 snippetKeys = ["snippet"];
184 break;
185 }
186 default:
187 throw new Error("unadmitted web provider");
188 }
189 const scored = [];
190 for (const [index, value] of items.entries()) {
191 if (!value || typeof value !== "object" || Array.isArray(value)) continue;
192 const item = row(value), rawTitle = string(firstPresent(item, titleKeys)), rawUrl = string(firstPresent(item, urlKeys));
193 if (rawTitle === void 0 || rawUrl === void 0) continue;
194 const title = trim2 ? rustTrim(rawTitle) : rawTitle, url = trim2 ? rustTrim(rawUrl) : rawUrl;
195 if (trim2 && (!title || !url)) continue;
196 const presentSnippet = ["bocha", "baidu", "volcengine"].includes(backend);
197 const selected = presentSnippet ? string(firstPresent(item, snippetKeys)) : void 0;
198 const snippet = presentSnippet ? selected === void 0 ? void 0 : rustTrim(selected) || void 0 : firstText(item, snippetKeys);
199 const entry = { title, url, ...snippet === void 0 ? {} : { snippet: capSnippet ? [...snippet].slice(0, 1e3).join("") : snippet } };
200 scored.push({ entry, score: scorePath === void 0 ? 0 : number(facts, `${scorePath}/${index}/score`) });
201 if (scorePath === void 0 && scored.length === limit) break;
202 }
203 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);
204 entries2 = scored.slice(0, limit).map((value) => value.entry);
205 return { kind: "web_provider", entries: entries2, error };
206 }
207 function extraction(input) {
208 if (!Array.isArray(input.candidates) || input.candidates.length > 3) throw new Error("invalid captured web regions");
209 const facts = [];
210 let previous = -1;
211 for (const value of input.candidates) {
212 const candidate = row(value), id = count(candidate.id, 2);
213 if (Object.keys(candidate).some((key) => !["id", "non_whitespace", "words"].includes(key)) || id <= previous) throw new Error("invalid ordered captured web region");
214 previous = id;
215 facts.push({ id, chars: count(candidate.non_whitespace, 1e8), words: count(candidate.words, 1e8) });
216 }
217 return { kind: "web_extract", candidate: facts.find((value) => value.chars >= 32 && value.words >= 5)?.id ?? null };
218 }
219 function images(input) {
220 const limit = count(input.max_results), parsed = row(input.parsed);
221 if (!Array.isArray(parsed.results)) throw new Error("invalid captured image results");
222 const entries2 = [];
223 for (const value of parsed.results) {
224 const entry = row(value), image = text(entry.image);
225 for (const key of ["thumbnail", "title", "url", "source"]) if (entry[key] !== null && entry[key] !== void 0) text(entry[key]);
226 for (const key of ["width", "height"]) if (entry[key] !== null && entry[key] !== void 0) count(entry[key], 4294967295);
227 if (!rustTrim(image)) continue;
228 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]])) });
229 }
230 return { kind: "web_images", entries: entries2, max_results: limit };
231 }
232 function request(input) {
233 const backend = text(input.backend), query = text(input.query), max = count(input.max_results);
234 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);
235 const locale = input.locale === null || input.locale === void 0 ? void 0 : text(input.locale);
236 let payload = null, pairs = [];
237 switch (backend) {
238 case "firecrawl":
239 payload = { query, limit: max, sources: [{ type: "web" }], ...window === void 0 ? {} : { tbs: `qdr:${window[0]}` }, ...region === void 0 ? {} : { country: region } };
240 break;
241 case "tavily":
242 payload = { query, search_depth: "basic", max_results: max, ...window === void 0 ? {} : { time_range: window } };
243 break;
244 case "bocha":
245 payload = { query, freshness: "noLimit", count: max };
246 break;
247 case "metaso":
248 payload = { q: query, scope: "webpage", size: Math.max(1, Math.min(100, max)) };
249 break;
250 case "sofya":
251 payload = { query, max_results: max };
252 break;
253 case "baidu":
254 payload = { messages: [{ role: "user", content: query }], search_source: "baidu_search_v2", resource_type_filter: [{ type: "web", top_k: max }] };
255 break;
256 case "volcengine":
257 payload = { input: [{ role: "user", content: [{ type: "input_text", text: `Search the web for: ${query}
258
259 CRITICAL: Respond ONLY with a valid JSON object. No markdown, no explanation.
260 Schema: {"results":[{"title":"...","url":"https://...","snippet":"..."}]}
261 - results: 1-${max} most relevant pages
262 - title: page title (required)
263 - url: full URL starting with https:// (required)
264 - snippet: 1-2 sentence factual summary (required)
265 - If zero results: {"results":[]}
266 - Your entire response must be valid, parseable JSON.` }] }] };
267 break;
268 case "serply":
269 pairs = [["q", query], ["num", String(max)], ...language === void 0 ? [] : [["hl", language]], ...region === void 0 ? [] : [["gl", region.toLowerCase()]]];
270 break;
271 case "searchapi":
272 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()]]];
273 break;
274 case "searxng":
275 pairs = [["q", query], ["format", "json"], ...window === void 0 ? [] : [["time_range", window]], ...locale === void 0 ? [] : [["language", locale]]];
276 break;
277 case "bing":
278 case "duckduckgo":
279 pairs = [["q", query]];
280 break;
281 default:
282 throw new Error("unadmitted web request provider");
283 }
284 return { kind: "web_request", payload, pairs };
285 }
286 function entries(input) {
287 if (!Array.isArray(input.entries)) throw new Error("invalid captured web candidates");
288 const values = input.entries.map((value) => {
289 const item = row(value);
290 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) } };
291 });
292 return { kind: "web_entries", entries: values };
293 }
294 function finalization(input) {
295 const requested = row(input.requested), capabilities = row(input.capabilities), counted = count(input.count);
296 if (!Array.isArray(input.degraded)) throw new Error("invalid captured web receipt");
297 const degraded = input.degraded.map((value) => row(value));
298 const ignored = (knob) => degraded.some((value) => row(value).kind === "knob_ignored" && row(value).knob === knob);
299 const honored = { max_results: capabilities.max_results === "supported", recency: false, domains: requested.domains === true, locale: false };
300 for (const knob of ["recency", "locale"]) {
301 if (knob === "locale") {
302 if (!Array.isArray(input.domain_extra)) throw new Error("invalid captured domain receipt");
303 degraded.push(...input.domain_extra.map((value) => row(value)));
304 }
305 if (requested[knob] === true && !ignored(knob)) {
306 if (capabilities[knob] === "supported") honored[knob] = true;
307 else degraded.push({ kind: "knob_ignored", knob });
308 }
309 }
310 const hasNote = input.has_note === true;
311 const prefix = counted === 0 ? hasNote ? "No results found. " : "No results found" : `Found ${counted} result(s)${hasNote ? ". " : ""}`;
312 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]" : "";
313 return { kind: "web_finalize", honored, degraded, prefix, suffix };
314 }
315 function transformWebSnapshot(operation, value) {
316 const input = row(value);
317 switch (operation) {
318 case "web_request":
319 return result(request(input));
320 case "web_entries":
321 return result(entries(input));
322 case "web_finalize":
323 return result(finalization(input));
324 case "web_filters":
325 return result(filters(input));
326 case "web_provider":
327 return result(provider(input));
328 case "web_extract":
329 return result(extraction(input));
330 case "web_images":
331 return result(images(input));
332 default:
333 throw new Error("unadmitted web adapter operation");
334 }
335 }
336
337 // src/builtin/shared/github-adapter.ts
338 var REPOSITORY = "codewhale-hq/CodeWhale";
339 function row2(value) {
340 if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid GitHub snapshot");
341 return value;
342 }
343 function text2(value) {
344 if (typeof value !== "string") throw new Error("invalid GitHub text");
345 return value;
346 }
347 function strings(value) {
348 if (!Array.isArray(value)) throw new Error("invalid GitHub list");
349 return value.map(text2);
350 }
351 function githubSummary(value, limit) {
352 let out = "", index = 0;
353 for (const char of value) {
354 if (index++ >= Math.max(0, limit - 3)) return `${out}...`;
355 const code = char.codePointAt(0);
356 if ((code <= 31 || code >= 127 && code <= 159) && char !== "\n" && char !== " ") continue;
357 out += char;
358 }
359 return out;
360 }
361 function renderIssueReview(value) {
362 const report2 = row2(value), fields = row2(report2.fields), id = text2(report2.id);
363 let out = `# ${text2(fields.title)}
364
365 Draft: ${id}
366 Status: ready for review
367 Publication: unavailable
368 Duplicate search: not performed
369 Destination: ${REPOSITORY}
370
371 Review the contents before sharing. Redaction does not guarantee privacy.
372 `;
373 if (report2.revises !== null) out += `Revises: ${text2(report2.revises)}
374 `;
375 for (const [heading, key] of [["Expected behavior", "expected"], ["Actual behavior", "actual"], ["Impact", "impact"]]) out += `
376 ## ${heading}
377
378 ${text2(fields[key])}
379 `;
380 for (const [heading, key] of [["Steps to reproduce (agent reported)", "steps"], ["Observed by the agent", "observed"], ["Inferences (not verified)", "inferred"]]) {
381 const items = strings(fields[key]);
382 out += `
383 ## ${heading}
384
385 `;
386 out += items.length ? items.map((item) => `- ${item}
387 `).join("") : "None recorded.\n";
388 }
389 out += `
390 ## Runtime context
391
392 - Codewhale: ${text2(report2.version)}
393 - Platform: ${text2(report2.platform)}
394 - Active model: ${text2(report2.model)}
395 `;
396 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])}
397 `;
398 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");
399 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})
400 `).join("");
401 const redactions = strings(report2.redactions);
402 if (redactions.length) out += `
403 Redacted categories: ${redactions.join(", ")}
404 `;
405 return out + `
406 Review: \`/feedback review ${id}\`
407 Revise: \`/feedback edit ${id} <change>\`
408 `;
409 }
410 function transformGithubSnapshot(value) {
411 const snapshot = row2(value), action = text2(snapshot.action);
412 if (action === "report_draft" || action === "report_read" || action === "report_review") {
413 const report2 = row2(snapshot.report), id = text2(report2.id);
414 const review = renderIssueReview(report2);
415 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` });
416 return { ok: true, result: { success: true, content: content2, metadata: null } };
417 }
418 const number2 = text2(snapshot.number);
419 if (!/^[0-9]{1,20}$/.test(number2)) throw new Error("invalid captured issue number");
420 if (action === "issue_context" || action === "pr_context") {
421 const raw = structuredClone(row2(snapshot.raw)), kind = action === "issue_context" ? "issue" : "pr";
422 if (snapshot.large_body === true) {
423 const body = text2(raw.body);
424 raw.body_summary = githubSummary(body, 900);
425 raw.body_artifact = snapshot.body_artifact;
426 raw.body = githubSummary(body, 1200);
427 }
428 if (action === "pr_context" && snapshot.diff !== null) {
429 raw.diff_summary = githubSummary(text2(snapshot.diff), 900);
430 raw.diff_artifact = snapshot.diff_artifact;
431 }
432 const subject2 = kind === "issue" ? "Issue" : "PR";
433 return { ok: true, result: { success: true, metadata: null, content: JSON.stringify({ summary: `${subject2} #${number2}: ${typeof raw.title === "string" ? raw.title : ""}`, [kind]: raw }) } };
434 }
435 const target = text2(snapshot.target);
436 if (!["issue", "pr"].includes(target)) throw new Error("invalid captured GitHub target");
437 const subject = target === "issue" ? "issue" : "PR";
438 let content;
439 if (snapshot.dirty === true) content = `Refusing to close ${subject}: worktree is dirty and allow_dirty was false.`;
440 else if (action === "comment") content = snapshot.dry_run === true ? `Dry run: would comment on ${target} #${number2}.` : `Commented on ${target} #${number2}.`;
441 else if (action === "close_issue" || action === "close_pr") content = snapshot.dry_run === true ? `Dry run: would close ${subject} #${number2}.` : `Closed ${subject} #${number2}.`;
442 else throw new Error("unknown captured GitHub operation");
443 return { ok: true, result: { success: snapshot.dirty !== true, content, metadata: null } };
444 }
445
446 // src/json.ts
447 function isJson(value, depth = 0) {
448 if (depth > 64) return false;
449 if (value === null) return true;
450 switch (typeof value) {
451 case "boolean":
452 case "string":
453 return true;
454 case "number":
455 return Number.isFinite(value);
456 case "object": {
457 const array2 = Array.isArray(value);
458 if (!array2 && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
459 const keys = Reflect.ownKeys(value);
460 if (array2 && keys.length !== value.length + 1) return false;
461 for (const key of keys) {
462 if (array2 && key === "length") continue;
463 if (typeof key !== "string") return false;
464 if (array2 && (!/^(0|[1-9]\d*)$/u.test(key) || Number(key) >= value.length)) return false;
465 const descriptor = Object.getOwnPropertyDescriptor(value, key);
466 if (!descriptor.enumerable || !("value" in descriptor) || !isJson(descriptor.value, depth + 1)) return false;
467 }
468 return true;
469 }
470 default:
471 return false;
472 }
473 }
474
475 // src/builtin/shared/review-adapter.ts
476 var REVIEW_LIMIT = 16 * 1024 * 1024;
477 var OPERATIONS = ["review_source_prompt", "review_pass_prompt", "review_interactive_pr", "review_report"];
478 function isReviewOperation(value) {
479 return typeof value === "string" && OPERATIONS.includes(value);
480 }
481 function reviewEnvelopeBytes(value) {
482 return 8 + Buffer.byteLength(`{"jsonrpc":"2.0","id":18446744073709551615,"result":${JSON.stringify(value)}}`);
483 }
484 function row3(value) {
485 if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid Core review snapshot");
486 return value;
487 }
488 function text3(value) {
489 if (typeof value !== "string") throw new Error("invalid Core review text");
490 return value;
491 }
492 function bool(value) {
493 if (typeof value !== "boolean") throw new Error("invalid Core review flag");
494 return value;
495 }
496 function integer2(value) {
497 if (!Number.isSafeInteger(value) || value < 0) throw new Error("invalid Core review count");
498 return value;
499 }
500 function list(value) {
501 if (!Array.isArray(value)) throw new Error("invalid Core review list");
502 return value;
503 }
504 function optional(value) {
505 return value === null || value === void 0 ? void 0 : text3(value);
506 }
507 function trim(value) {
508 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, "");
509 }
510 function lines(value) {
511 if (!value.length) return [];
512 const out = value.split("\n");
513 if (value.endsWith("\n")) out.pop();
514 return out.map((line, i) => (i < out.length - 1 || value.endsWith("\n")) && line.endsWith("\r") ? line.slice(0, -1) : line);
515 }
516 function skipped(value) {
517 return list(value).map((value2) => {
518 const skip = row3(value2);
519 return `${text3(skip.file)} (${integer2(skip.chars)} chars; ${text3(skip.reason)})`;
520 }).join(", ");
521 }
522 function ordered(value) {
523 if (Array.isArray(value)) return value.map(ordered);
524 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)]));
525 return value;
526 }
527 function intent(value) {
528 const commits = value === void 0 ? "" : text3(value);
529 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.
530
531 ${commits}
532
533 End of commit messages.
534
535 ` : "";
536 }
537 function source(input) {
538 const kind = text3(input.kind);
539 if (kind === "file") {
540 const content = lines(text3(input.content)).map((line, i) => `${String(i + 1).padStart(4)} | ${line}`).join("\n");
541 return `Review the following file and provide feedback.
542 Path: ${text3(input.display)}
543
544 ${content}
545
546 End of file.`;
547 }
548 if (kind === "diff") return `Review the following ${text3(input.label)} and provide feedback.
549
550 ${text3(input.diff)}
551
552 End of diff.`;
553 if (kind === "cli_diff") return `${intent(input.commits)}Review the following diff and provide feedback:
554
555 ${text3(input.diff)}
556
557 End of diff.`;
558 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.
559
560 ${text3(input.diff)}
561
562 End of diff.`;
563 throw new Error("unadmitted review source");
564 }
565 function pass(input) {
566 const manifest = row3(input.manifest), part = row3(input.pass), view = row3(input.view);
567 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.`;
568 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.`;
569 if (!isJson(input.context)) throw new Error("invalid Core review context");
570 const prompt = {
571 task,
572 untrusted_repository_data: true,
573 pull_request: { number: integer2(input.number), title: text3(view.title), description: text3(view.body) },
574 manifest,
575 pass: part,
576 diff: text3(input.diff),
577 repository_context: input.context,
578 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."
579 };
580 return JSON.stringify(bool(input.sort_keys) ? ordered(prompt) : prompt);
581 }
582 function interactive(input) {
583 const view = row3(input.view), number2 = integer2(input.number);
584 const base = text3(view.base), head = text3(view.head);
585 const branches = base && head ? `${base} ← ${head}` : base || head || "(unknown)";
586 return `Review PR #${number2} — ${trim(text3(view.title)) || `(PR #${number2})`}
587
588 URL: ${text3(view.url) || "(unavailable)"}
589 Branches: ${branches}
590 Revision: ${text3(view.head_sha)} (base ${text3(view.base_sha)}); ${integer2(view.changed_files)} file patches.
591 Binary changes are represented by metadata; their contents are not semantically inspected. Exact binary object IDs remain in the review evidence.
592
593 ## Description
594
595 ${trim(text3(view.body)) || "(no description)"}
596
597 ## Diff
598
599 \`\`\`diff
600 ${text3(input.diff)}
601 \`\`\`
602 `;
603 }
604 function fence(value) {
605 let longest = 0, run = 0;
606 for (const char of value) {
607 run = char === "`" ? run + 1 : 0;
608 longest = Math.max(longest, run);
609 }
610 return "`".repeat(Math.max(3, longest + 1));
611 }
612 function location(value) {
613 const path = optional(value.path);
614 return path === void 0 ? "" : value.line === null || value.line === void 0 ? `\`${trim(path)}\`` : `\`${trim(path)}:${integer2(value.line)}\``;
615 }
616 function report(input) {
617 if (input.review === null) return text3(input.output);
618 const review = row3(input.review), posted = bool(input.posted);
619 let out = "## Codewhale review\n\n";
620 const summary2 = text3(review.summary), assessment = text3(review.overall_assessment);
621 if (summary2.length) out += trim(summary2) + "\n\n";
622 const issues = list(review.issues), suggestions = list(review.suggestions);
623 if (issues.length) {
624 out += "### Findings\n\n";
625 for (const item of issues) {
626 const issue = row3(item), at = location(issue);
627 out += `- **[${text3(issue.severity).toUpperCase()}] ${text3(issue.title)}**${at ? ` (${at})` : ""}
628 `;
629 const description = text3(issue.description);
630 if (description.length) out += ` ${description}
631 `;
632 }
633 out += "\n";
634 }
635 if (suggestions.length) {
636 out += "### Suggestions\n\n";
637 for (const item of suggestions) {
638 const suggestion = row3(item), at = location(suggestion);
639 out += `- ${at ? `${at} — ` : ""}${text3(suggestion.suggestion)}
640 `;
641 const replacement = optional(suggestion.replacement);
642 if (replacement !== void 0 && trim(replacement).length) {
643 const codeFence = fence(replacement);
644 out += `
645 ${codeFence}${posted ? "diff" : "suggestion"}
646 `;
647 for (const line of replacement.split("\n")) out += ` ${line}
648 `;
649 out += ` ${codeFence}
650 `;
651 }
652 }
653 out += "\n";
654 }
655 if (assessment.length) out += "### Assessment\n\n" + trim(assessment) + "\n\n";
656 const tally = { blocker: 0, concern: 0, nit: 0, introduced: 0, preexisting: 0 };
657 for (const item of issues) {
658 const issue = row3(item), severity = text3(issue.severity);
659 if (severity === "blocker") tally.blocker += 1;
660 else if (severity === "concern") tally.concern += 1;
661 else if (severity === "nit") tally.nit += 1;
662 if (optional(issue.authorship) === "preexisting") tally.preexisting += 1;
663 else tally.introduced += 1;
664 }
665 out += `<!-- codewhale-review: {"blocker":${tally.blocker},"concern":${tally.concern},"nit":${tally.nit},"introduced":${tally.introduced},"preexisting":${tally.preexisting}} -->
666 `;
667 return out;
668 }
669 function transformReviewSnapshot(operation, value) {
670 if (!isReviewOperation(operation)) throw new Error("unadmitted review operation");
671 const input = row3(value);
672 const content = operation === "review_source_prompt" ? source(input) : operation === "review_pass_prompt" ? pass(input) : operation === "review_interactive_pr" ? interactive(input) : report(input);
673 const result3 = { ok: true, result: { content, success: true, metadata: null } };
674 if (reviewEnvelopeBytes(result3) > REVIEW_LIMIT) throw new Error("serialized review result exceeds 16 MiB");
675 return result3;
676 }
677
678 // src/builtin/shared/stock-adapters.ts
679 var MAX_SNAPSHOT = 1024 * 1024;
680 function row4(value) {
681 if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid adapter snapshot");
682 return value;
683 }
684 function text4(value) {
685 if (typeof value !== "string") throw new Error("invalid adapter text");
686 return value;
687 }
688 function optionalText(value) {
689 return value === null || value === void 0 ? void 0 : text4(value);
690 }
691 function result2(success, metadata, content = "") {
692 return { ok: true, result: { success, content, metadata } };
693 }
694 function asciiLower(value) {
695 return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
696 }
697 function summary(value, format) {
698 const descriptor = row4(value);
699 const kind = text4(descriptor.kind);
700 const accepted = format === "json" ? ["object", "array", "string", "number", "boolean", "null"] : ["table", "array", "string", "integer", "float", "boolean", "datetime"];
701 if (!accepted.includes(kind)) throw new Error("invalid captured parser kind");
702 if (kind === "object" || kind === "table") {
703 if (!Array.isArray(descriptor.keys) || descriptor.keys.some((key) => typeof key !== "string")) throw new Error("invalid captured parser keys");
704 const keys = descriptor.keys;
705 if (new Set(keys).size !== keys.length) throw new Error("duplicate captured parser keys");
706 return { top_level: kind, entries: keys.length, keys_preview: keys.slice(0, 10) };
707 }
708 if (kind === "array") {
709 if (!Number.isSafeInteger(descriptor.entries) || descriptor.entries < 0) throw new Error("invalid captured array count");
710 return { top_level: kind, entries: descriptor.entries };
711 }
712 return { top_level: kind };
713 }
714 function data(input) {
715 const format = text4(input.format);
716 if (!["auto", "json", "toml"].includes(format)) throw new Error("invalid captured data format");
717 const source2 = text4(input.source);
718 const extension = optionalText(input.extension);
719 const requested = format === "auto" && (extension === "json" || extension === "toml") ? extension : format;
720 const json = row4(input.json);
721 const toml = row4(input.toml);
722 if (typeof json.ok !== "boolean" || typeof toml.ok !== "boolean") throw new Error("invalid captured parser result");
723 const use = (parser, selected) => {
724 if (parser.ok) return result2(true, { valid: true, format: selected, source: source2, summary: summary(parser.value, selected) });
725 const error = text4(parser.error);
726 return result2(false, { valid: false, format: selected, source: source2, error }, `Invalid ${selected.toUpperCase()}: ${error}`);
727 };
728 if (requested === "json") return use(json, "json");
729 if (requested === "toml") return use(toml, "toml");
730 if (json.ok) return use(json, "json");
731 if (toml.ok) return use(toml, "toml");
732 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.");
733 }
734 function rustTrim2(value) {
735 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, "");
736 }
737 function bool2(value) {
738 if (typeof value !== "boolean") throw new Error("invalid captured boolean");
739 return value;
740 }
741 function speech(operation, input) {
742 const surface = text4(input.surface);
743 if (surface !== "tool" && surface !== "cli") throw new Error("invalid speech surface");
744 const tool = surface === "tool";
745 const invalid = (error) => result2(false, { error });
746 if (operation === "speech_format") {
747 const raw = text4(input.format);
748 const format = asciiLower(rustTrim2(raw));
749 if (input.minimax === true) {
750 const wire = format === "pcm16" ? "pcm" : format;
751 return ["mp3", "wav", "flac", "pcm"].includes(wire) ? result2(true, { format: wire }) : invalid("unsupported MiniMax speech format");
752 }
753 if (format === "wav" || format === "mp3" || format === "pcm16" || format === "pcm") return result2(true, { format: format === "pcm" ? "pcm16" : format });
754 return invalid(tool ? `unsupported speech format '${raw}' (allowed: wav, mp3, pcm16)` : `Unsupported speech format '${raw}' (allowed: wav, mp3, pcm16)`);
755 }
756 const modelHint = optionalText(input.model);
757 const hasClone = bool2(input.has_clone_path);
758 const hasVoice = bool2(input.has_voice);
759 const nonemptyVoice = bool2(input.voice_nonempty);
760 const dataUri = bool2(input.voice_is_data_uri);
761 if ((nonemptyVoice || dataUri) && !hasVoice) throw new Error("inconsistent captured voice presence");
762 const instructionInput = optionalText(input.instruction);
763 const promptInput = optionalText(input.voice_prompt);
764 if (input.minimax === true) {
765 if (!modelHint || hasClone || dataUri || instructionInput !== void 0 || promptInput !== void 0) return invalid("MiniMax speech accepts spoken text and a voice ID");
766 return result2(true, { model: modelHint, instruction: null, voice: nonemptyVoice ? "raw" : "default" });
767 }
768 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");
769 const model = modelHint ?? (hasClone || dataUri ? "mimo-v2.5-tts-voiceclone" : promptInput !== void 0 ? "mimo-v2.5-tts-voicedesign" : "mimo-v2.5-tts");
770 const lower = asciiLower(model);
771 if (!lower.includes("tts")) {
772 const examples = "mimo-v2.5-tts, mimo-v2.5-tts-voicedesign, mimo-v2.5-tts-voiceclone, mimo-v2-tts";
773 return invalid(tool ? `speech tool requires a TTS model (examples: ${examples}), got '${model}'` : `speech requires a TTS model (examples: ${examples}); got ${model}`);
774 }
775 const parts = [promptInput, instructionInput].map((value) => value === void 0 ? void 0 : rustTrim2(value)).filter((value) => value !== void 0 && value !== "");
776 const instruction = parts.length ? parts.join("\n\n") : null;
777 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");
778 let voice;
779 if (hasClone) voice = "clone";
780 else if (lower.includes("voicedesign")) voice = "omit";
781 else if (nonemptyVoice) voice = "raw";
782 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>");
783 else voice = "default";
784 return result2(true, { model, instruction, voice });
785 }
786 function pdfProjection(input) {
787 const state = text4(input.state);
788 const decision = (code2, message) => result2(true, { kind: "pdf_decision", code: code2, ...message === void 0 ? {} : { message } });
789 if (state !== "complete") {
790 if (!["binary_unavailable", "cancelled", "timed_out", "execution"].includes(state)) throw new Error("invalid PDF process state");
791 return decision(state, text4(input.message));
792 }
793 const success = bool2(input.success);
794 const stdoutOverflow = bool2(input.stdout_truncated);
795 const stderrOverflow = bool2(input.stderr_truncated);
796 const stderr = text4(input.stderr);
797 const code = input.exit_code;
798 if (code !== null && (!Number.isInteger(code) || code < -2147483648 || code > 2147483647)) throw new Error("invalid PDF exit code");
799 if (stdoutOverflow) return decision("execution", "pdftotext output exceeded the 16777216 byte safety limit");
800 if (!success) return decision("execution", `pdftotext failed (exit ${code === null ? "None" : `Some(${code})`}): ${stderr || "no diagnostic output"}${stderrOverflow ? " [truncated]" : ""}`);
801 return decision("success");
802 }
803 function ocrProjection(input) {
804 const decision = (code2, trim_end = false, message) => result2(true, { kind: "ocr_decision", code: code2, trim_end, ...message === void 0 ? {} : { message } });
805 const state = text4(input.state), status = text4(input.status);
806 if (state === "native") {
807 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");
808 const fallback = bool2(input.can_fallback);
809 if (status === "success") {
810 if (fallback || input.next_ticket !== void 0) throw new Error("successful OCR Native step cannot launch fallback");
811 return decision("native_success");
812 }
813 if (fallback) {
814 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");
815 return decision("fallback");
816 }
817 if (input.next_ticket !== void 0) throw new Error("OCR fallback is not admitted");
818 if (status === "error") return decision("native_error");
819 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.");
820 }
821 if (state !== "tesseract") throw new Error("invalid OCR process stage");
822 if (status === "fault") {
823 if (Object.keys(input).some((key) => !["kind", "state", "status"].includes(key))) throw new Error("invalid OCR fault projection");
824 return decision("fault");
825 }
826 if (status !== "complete" || Object.keys(input).some((key) => !["kind", "state", "status", "success", "exit_code"].includes(key))) throw new Error("invalid OCR Tesseract projection");
827 const success = bool2(input.success), code = input.exit_code;
828 if (code !== null && (!Number.isInteger(code) || code < -2147483648 || code > 2147483647)) throw new Error("invalid OCR exit code");
829 return success ? decision("tesseract_success", true) : decision("execution", false, `tesseract failed (exit ${code === null ? "None" : `Some(${code})`}): `);
830 }
831 function transformStockSnapshot(value) {
832 const snapshot = row4(value);
833 const review = snapshot.kind === "stock_adapter" && isReviewOperation(snapshot.operation);
834 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");
835 if (snapshot.kind === "ocr_process") return ocrProjection(snapshot);
836 if (snapshot.kind === "pdf_process") return pdfProjection(snapshot);
837 if (snapshot.kind !== "stock_adapter") throw new Error("invalid adapter projection");
838 const input = row4(snapshot.input);
839 if (review) return transformReviewSnapshot(snapshot.operation, input);
840 switch (snapshot.operation) {
841 case "web_filters":
842 case "web_request":
843 case "web_provider":
844 case "web_entries":
845 case "web_finalize":
846 case "web_extract":
847 case "web_images":
848 return transformWebSnapshot(snapshot.operation, input);
849 case "github_result":
850 return transformGithubSnapshot(input);
851 case "validate_data":
852 return data(input);
853 case "speech_options":
854 case "speech_format":
855 return speech(snapshot.operation, input);
856 default:
857 throw new Error("unadmitted adapter operation");
858 }
859 }
860 export {
861 transformStockSnapshot
862 };
863
863 lines Plain Text