@bendyline/gezel-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,911 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/tool-inventory.ts
4
+ var ALWAYS_REGISTERED_TOOLS = [
5
+ // Memory
6
+ "search_memory",
7
+ "save_memory",
8
+ "list_memories",
9
+ // Workspace (read-write project files)
10
+ "list_dir",
11
+ "read_file",
12
+ "read_files",
13
+ "stat",
14
+ "write_file",
15
+ "append_to_file",
16
+ "replace_in_file",
17
+ "replace_lines",
18
+ "apply_patch",
19
+ "insert_at_marker",
20
+ "delete_path",
21
+ "make_dir",
22
+ "rename",
23
+ "copy_artifact_to_workspace",
24
+ "validate",
25
+ // Execution (Node / npm / playwright)
26
+ "npm_install",
27
+ "list_package_scripts",
28
+ "run_package_script",
29
+ "run_npx",
30
+ "run_nodejs_script",
31
+ "derive_file",
32
+ "list_packages",
33
+ "run_playwright_script",
34
+ // Artifacts (project-scoped)
35
+ "list_artifacts",
36
+ "read_artifact",
37
+ "write_artifact",
38
+ "grep_artifact",
39
+ "browser_find_page_element",
40
+ // Documents (shared library)
41
+ "list_documents",
42
+ "read_document",
43
+ "write_document",
44
+ "delete_document",
45
+ "search_documents",
46
+ // Team / gezels
47
+ "list_gezels",
48
+ "create_gezel",
49
+ "list_gilde",
50
+ "list_project_types",
51
+ "apply_project_type",
52
+ "start_project_from_type",
53
+ "export_project_type",
54
+ "import_project_type",
55
+ "ensure_gezel",
56
+ "update_gezel",
57
+ "message_gezel",
58
+ "ask_gezel",
59
+ "ask_specialist",
60
+ // Role-typed delegation (always registered; surfaced per session only
61
+ // when the `tools.gezels-as-roles` behavior is active — see
62
+ // role-tool-filter.ts + builtin-toolsets.ts `role-delegation*` groups).
63
+ "delegate_developer",
64
+ "consult_developer",
65
+ "delegate_designer",
66
+ "consult_designer",
67
+ "delegate_reviewer",
68
+ "consult_reviewer",
69
+ "delegate_planner",
70
+ "consult_planner",
71
+ "delegate_researcher",
72
+ "consult_researcher",
73
+ "delegate_builder",
74
+ "consult_builder",
75
+ "delegate_writer",
76
+ "consult_writer",
77
+ "delegate_image_generator",
78
+ "consult_image_generator",
79
+ "delegate_voorman",
80
+ "consult_voorman",
81
+ "delegate_meester",
82
+ "consult_meester",
83
+ // User
84
+ "ask_user_question",
85
+ // Projects
86
+ "list_projects",
87
+ "start_project",
88
+ "fetch_repo",
89
+ "fetch_diff",
90
+ "update_project",
91
+ "list_project_gezels",
92
+ "add_gezel_to_project",
93
+ "remove_gezel_from_project",
94
+ "list_suggested_work",
95
+ "enable_suggested_work",
96
+ "disable_suggested_work",
97
+ // Tasks
98
+ "list_tasks",
99
+ "get_task",
100
+ "create_task",
101
+ "start_plan",
102
+ "update_task",
103
+ "set_outcomes",
104
+ "verify_outcome",
105
+ "add_verification_step",
106
+ "spawn_task_instances",
107
+ "list_task_children",
108
+ "set_task_status",
109
+ "activate_task",
110
+ "assign_task",
111
+ "add_task_step",
112
+ "advance_task_step",
113
+ "read_task_notes",
114
+ "write_task_note",
115
+ // History
116
+ "search_history",
117
+ "search_sessions",
118
+ // Handboek (built-in documentation)
119
+ "how_do_i",
120
+ // Images
121
+ "render_image",
122
+ "generate_image",
123
+ "describe_image",
124
+ "read_image_metadata",
125
+ // Video
126
+ "generate_video",
127
+ // Audio (whisper.cpp STT + Kokoro TTS)
128
+ "transcribe_audio",
129
+ "synthesize_speech",
130
+ // Web
131
+ "fetch_url",
132
+ "web_search",
133
+ "wikipedia_search",
134
+ // Search / files
135
+ "grep_files",
136
+ "find_files",
137
+ "diff_files",
138
+ "read_image_as_base64",
139
+ // Code intelligence (workspace content index)
140
+ "outline_file",
141
+ "find_symbol",
142
+ "read_symbol",
143
+ "find_references",
144
+ "map_repo",
145
+ "search_code",
146
+ "file_review",
147
+ "list_file_issues",
148
+ // Security intelligence (static security analysis over the index)
149
+ "security_scan",
150
+ "security_overview",
151
+ "scan_findings",
152
+ "map_attack_surface",
153
+ "list_dependencies",
154
+ "trace_taint",
155
+ // Document intelligence (converted office docs)
156
+ "search_docs",
157
+ "read_doc_as_markdown",
158
+ // Image intelligence (workspace image library)
159
+ "search_images",
160
+ "find_similar_images",
161
+ "describe_folder",
162
+ // Entity intelligence (meta-boekwachter: cross-file entities)
163
+ "find_entity",
164
+ "list_entity_mentions",
165
+ // Archives
166
+ "list_archive",
167
+ "extract_archive",
168
+ // Git
169
+ "run_git",
170
+ // Scripts
171
+ "list_scripts",
172
+ "run_installed_script",
173
+ "get_script_run",
174
+ // Craftbooks (procedures)
175
+ "list_craftbooks",
176
+ "suggest_craftbook",
177
+ "invoke_craftbook",
178
+ "import_skill",
179
+ // Craftbook editing (template authoring + step surgery)
180
+ "craftbook_read",
181
+ "craftbook_write",
182
+ "craftbook_add_step",
183
+ "set_step_deliverable",
184
+ "craftbook_remove_step",
185
+ "craftbook_reorder_steps",
186
+ "craftbook_set_entry",
187
+ "craftbook_update",
188
+ "export_task_craftbook",
189
+ // GitHub (PR + workflow operations)
190
+ "github_pr_list",
191
+ "github_pr_view",
192
+ "github_pr_files",
193
+ "github_pr_diff",
194
+ "github_pr_comments",
195
+ "github_pr_comment",
196
+ "github_pr_create",
197
+ "github_workflow_runs",
198
+ "github_check_status"
199
+ ];
200
+ var CONDITIONALLY_REGISTERED_TOOLS = {
201
+ // Compatibility aliases consolidated into smaller primary tools. Hidden
202
+ // from model sessions by default; direct MCP clients can opt in while they
203
+ // migrate by setting GEZEL_MCP_LEGACY_TOOLS=1.
204
+ create_gezel_from_gilde: {
205
+ envVar: "GEZEL_MCP_LEGACY_TOOLS",
206
+ envValue: "1",
207
+ modelFacing: false
208
+ },
209
+ start_job: { envVar: "GEZEL_MCP_LEGACY_TOOLS", envValue: "1", modelFacing: false },
210
+ list_project_local_gezels: {
211
+ envVar: "GEZEL_MCP_LEGACY_TOOLS",
212
+ envValue: "1",
213
+ modelFacing: false
214
+ },
215
+ craftbook_create: {
216
+ envVar: "GEZEL_MCP_LEGACY_TOOLS",
217
+ envValue: "1",
218
+ modelFacing: false
219
+ },
220
+ craftbook_replace: {
221
+ envVar: "GEZEL_MCP_LEGACY_TOOLS",
222
+ envValue: "1",
223
+ modelFacing: false
224
+ },
225
+ // The large surgical-step schema is useful in the explicit craftbook
226
+ // editor, but wasteful on every ordinary coordinator turn. `*` means any
227
+ // non-empty GEZEL_CRAFTBOOK_ID enables it.
228
+ craftbook_update_step: {
229
+ envVar: "GEZEL_CRAFTBOOK_ID",
230
+ envValue: "*",
231
+ modelFacing: true
232
+ },
233
+ request_tool_permission: {
234
+ envVar: "GEZEL_PERMISSION_PROMPT",
235
+ envValue: "1",
236
+ modelFacing: false
237
+ },
238
+ // Email write tools — registered only for mail-enabled projects (the chat
239
+ // manager sets GEZEL_MAIL_ENABLED when project.mail is configured).
240
+ draft_email: { envVar: "GEZEL_MAIL_ENABLED", envValue: "1", modelFacing: true },
241
+ queue_email: { envVar: "GEZEL_MAIL_ENABLED", envValue: "1", modelFacing: true },
242
+ send_email: { envVar: "GEZEL_MAIL_ENABLED", envValue: "1", modelFacing: true },
243
+ // Generic connector writes are draft-only and appear only for projects
244
+ // with at least one connector binding.
245
+ draft_connector_action: {
246
+ envVar: "GEZEL_CONNECTORS_ENABLED",
247
+ envValue: "1",
248
+ modelFacing: true
249
+ }
250
+ };
251
+ var RENAMED_TOOLS = {
252
+ readdir: "list_dir",
253
+ readFile: "read_file",
254
+ read_multiple_files: "read_files",
255
+ writeFile: "write_file",
256
+ appendToFile: "append_to_file",
257
+ replaceInFile: "replace_in_file",
258
+ replaceLines: "replace_lines",
259
+ applyPatch: "apply_patch",
260
+ insertAtMarker: "insert_at_marker",
261
+ rm: "delete_path",
262
+ mkdir: "make_dir",
263
+ draftEmail: "draft_email",
264
+ queueEmail: "queue_email",
265
+ sendEmail: "send_email",
266
+ // Familiar coding-agent vocabulary improves tool selection for local
267
+ // models. The old semantic name remains a hidden dispatch alias.
268
+ search_files: "grep_files",
269
+ // Not part of the snake_case sweep — a later, semantic rename. `run_script`
270
+ // read as "run a script", so models that had just written `derive.mjs`
271
+ // called it with a file path and got a "script not found" dead end; the
272
+ // 2026-08-02 core suite caught gemma4-e4b doing this 6 times in one trial
273
+ // and then fabricating the output it could not compute. Measured, not
274
+ // assumed: forcing `prompt.derive-by-execution` (whose text names
275
+ // `derive_file` and `run_nodejs_script` outright) did NOT redirect it —
276
+ // the model still reached for `run_script`. The name is the pull, so the
277
+ // name changes; `run_script` stays callable here forever.
278
+ run_script: "run_installed_script"
279
+ };
280
+ var TOOL_NAME_TOMBSTONES = {
281
+ update_task_step: { replacement: void 0, reason: "no such MCP tool" },
282
+ commitProjectGit: { replacement: void 0, reason: "UI/client method, not an MCP tool" },
283
+ pushProjectGit: { replacement: void 0, reason: "UI/client method, not an MCP tool" },
284
+ listAudioVoices: { replacement: void 0, reason: "UI/client method, not an MCP tool" },
285
+ create_project: { replacement: "start_project", reason: "removed project-creation tool" },
286
+ inspect_git_workdir: { replacement: "run_git", reason: "foreign coding-agent tool" },
287
+ ensureGezel: { replacement: "ensure_gezel", reason: "client method, not an MCP tool" },
288
+ pushProjectGithub: { replacement: void 0, reason: "client method, not an MCP tool" },
289
+ AskUserQuestion: { replacement: "ask_user_question", reason: "foreign coding-agent tool" },
290
+ WebSearch: { replacement: "web_search", reason: "foreign coding-agent tool" },
291
+ Grep: { replacement: "grep_files", reason: "foreign coding-agent tool" },
292
+ Read: { replacement: "read_file", reason: "foreign coding-agent tool" },
293
+ Edit: { replacement: "replace_in_file", reason: "foreign coding-agent tool" },
294
+ Agent: { replacement: "message_gezel", reason: "foreign coding-agent tool" },
295
+ Bash: { replacement: void 0, reason: "foreign shell tool; no unrestricted shell is exposed" },
296
+ ExitPlanMode: { replacement: void 0, reason: "foreign coding-agent control tool" }
297
+ };
298
+ var CANONICAL_TOOL_NAMES = Object.freeze([
299
+ ...ALWAYS_REGISTERED_TOOLS,
300
+ ...Object.keys(CONDITIONALLY_REGISTERED_TOOLS)
301
+ ]);
302
+ var LEGACY_TOOL_NAMES = Object.freeze(
303
+ Object.keys(RENAMED_TOOLS)
304
+ );
305
+ var aliasesByCanonical = /* @__PURE__ */ new Map();
306
+ for (const [alias, canonical] of Object.entries(RENAMED_TOOLS)) {
307
+ const aliases = aliasesByCanonical.get(canonical) ?? [];
308
+ aliases.push(alias);
309
+ aliasesByCanonical.set(canonical, aliases);
310
+ }
311
+ var TOOL_REGISTRY = Object.freeze(
312
+ Object.fromEntries(
313
+ CANONICAL_TOOL_NAMES.map((canonicalName) => {
314
+ const conditional = CONDITIONALLY_REGISTERED_TOOLS[canonicalName];
315
+ const aliases = Object.freeze([
316
+ ...aliasesByCanonical.get(canonicalName) ?? []
317
+ ]);
318
+ const entry = conditional ? {
319
+ canonicalName,
320
+ registration: "conditional",
321
+ gate: { envVar: conditional.envVar, envValue: conditional.envValue },
322
+ aliases,
323
+ advertisedByDefault: false,
324
+ modelFacing: conditional.modelFacing
325
+ } : {
326
+ canonicalName,
327
+ registration: "always",
328
+ aliases,
329
+ advertisedByDefault: true,
330
+ modelFacing: true
331
+ };
332
+ return [canonicalName, Object.freeze(entry)];
333
+ })
334
+ )
335
+ );
336
+ var BUILTIN_TOOL_NAMES = Object.freeze([
337
+ ...CANONICAL_TOOL_NAMES,
338
+ ...LEGACY_TOOL_NAMES
339
+ ]);
340
+ var RESERVED_TOOL_NAMES = Object.freeze([
341
+ ...BUILTIN_TOOL_NAMES,
342
+ ...Object.keys(TOOL_NAME_TOMBSTONES)
343
+ ]);
344
+ var LEGACY_SPELLING_BY_CANONICAL = Object.fromEntries(
345
+ Object.entries(RENAMED_TOOLS).map(([legacy, canonical]) => [canonical, legacy])
346
+ );
347
+ function normalizeToolNameSpelling(name) {
348
+ return name.toLowerCase().replace(/[^a-z0-9]/g, "");
349
+ }
350
+ function canonicalToolName(name) {
351
+ const direct = RENAMED_TOOLS[name];
352
+ if (direct) return direct;
353
+ return name;
354
+ }
355
+ function resolveToolNameSpelling(requested, knownNames) {
356
+ if (knownNames.has(requested)) return requested;
357
+ if (requested in TOOL_NAME_TOMBSTONES) return requested;
358
+ const viaRename = RENAMED_TOOLS[requested];
359
+ if (viaRename && knownNames.has(viaRename)) return viaRename;
360
+ const viaLegacy = LEGACY_SPELLING_BY_CANONICAL[requested];
361
+ if (viaLegacy && knownNames.has(viaLegacy)) return viaLegacy;
362
+ const wanted = normalizeToolNameSpelling(requested);
363
+ if (!wanted) return requested;
364
+ for (const candidate of knownNames) {
365
+ if (normalizeToolNameSpelling(candidate) === wanted) return candidate;
366
+ }
367
+ for (const [legacy, canonical] of Object.entries(RENAMED_TOOLS)) {
368
+ if (normalizeToolNameSpelling(legacy) === wanted && knownNames.has(canonical)) return canonical;
369
+ if (normalizeToolNameSpelling(canonical) === wanted && knownNames.has(legacy)) return legacy;
370
+ }
371
+ return requested;
372
+ }
373
+
374
+ // src/validate.ts
375
+ import ts from "typescript";
376
+ function validateFile(path, content) {
377
+ const lower = path.toLowerCase();
378
+ if (lower.endsWith(".html") || lower.endsWith(".htm")) {
379
+ return { path, checks: validateHtml(path, content) };
380
+ }
381
+ if (lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs") || lower.endsWith(".ts") || lower.endsWith(".tsx")) {
382
+ return { path, checks: validateJsTs(path, content) };
383
+ }
384
+ if (lower.endsWith(".json")) {
385
+ return { path, checks: validateJson(path, content) };
386
+ }
387
+ if (lower.endsWith(".png") || lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".webp") || lower.endsWith(".gif") || lower.endsWith(".svg")) {
388
+ return { path, checks: validateImage(path, content) };
389
+ }
390
+ return { path, checks: [fileNonEmptyCheck(content)] };
391
+ }
392
+ function formatValidateResult(result) {
393
+ const fails = result.checks.filter((c) => c.ok === false);
394
+ const passes = result.checks.filter((c) => c.ok === true);
395
+ const skips = result.checks.filter((c) => c.ok === null);
396
+ const skipSuffix = skips.length > 0 ? `; ${skips.length} skipped` : "";
397
+ const summary = fails.length === 0 ? `validate ${result.path} \u2014 PASS (${passes.length} check${passes.length === 1 ? "" : "s"}${skipSuffix})` : `validate ${result.path} \u2014 FAIL (${fails.length} of ${fails.length + passes.length} completed check${fails.length + passes.length === 1 ? "" : "s"} failed${skipSuffix})`;
398
+ const lines = [summary, ""];
399
+ for (const f of fails) {
400
+ const loc = f.location ? ` at line ${f.location.line}${f.location.col ? `, col ${f.location.col}` : ""}` : "";
401
+ lines.push(`\u2717 ${f.name}: ${f.message}${loc}`);
402
+ if (f.excerpt) {
403
+ lines.push(" Context:");
404
+ lines.push(f.excerpt);
405
+ }
406
+ if (f.fixHint) {
407
+ lines.push(` Fix hint: ${f.fixHint}`);
408
+ }
409
+ lines.push("");
410
+ }
411
+ for (const p of passes) {
412
+ lines.push(`\u2713 ${p.name}${p.detail ? `: ${p.detail}` : ""}`);
413
+ }
414
+ for (const s of skips) {
415
+ lines.push(`- ${s.name}: skipped \u2014 ${s.detail}`);
416
+ }
417
+ return lines.join("\n").trimEnd();
418
+ }
419
+ function fileNonEmptyCheck(content) {
420
+ if (content.totalBytes === 0) {
421
+ return {
422
+ ok: false,
423
+ name: "file-non-empty",
424
+ message: "file is empty (0 bytes)",
425
+ fixHint: "write the intended content with `write_file` (or `copy_artifact_to_workspace` if the source is in the artifacts drawer)."
426
+ };
427
+ }
428
+ return { ok: true, name: "file-non-empty", detail: `${content.totalBytes} bytes` };
429
+ }
430
+ function buildExcerpt(text, targetLine, context = 2) {
431
+ const lines = text.split("\n");
432
+ if (lines.length === 0) return "";
433
+ const start = Math.max(0, targetLine - 1 - context);
434
+ const end = Math.min(lines.length - 1, targetLine - 1 + context);
435
+ const width = String(end + 1).length;
436
+ const out = [];
437
+ for (let i = start; i <= end; i++) {
438
+ const num = String(i + 1).padStart(width);
439
+ const arrow = i + 1 === targetLine ? " \u2190 here" : "";
440
+ out.push(` ${num} | ${lines[i] ?? ""}${arrow}`);
441
+ }
442
+ return out.join("\n");
443
+ }
444
+ var SCRIPT_RE = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
445
+ var SCRIPT_OPEN_RE = /<script\b[^>]*>/gi;
446
+ var SCRIPT_CLOSE_RE = /<\/script\s*>/gi;
447
+ function validateHtml(_path, content) {
448
+ if (!content.text) {
449
+ return [
450
+ {
451
+ ok: false,
452
+ name: "file-readable",
453
+ message: "could not read HTML as text",
454
+ fixHint: "the file may be corrupted; try writing it again with `write_file`."
455
+ }
456
+ ];
457
+ }
458
+ const html = content.text;
459
+ const checks = [fileNonEmptyCheck(content)];
460
+ checks.push(validateHtmlDocumentStructure(html));
461
+ checks.push(validateUniqueHtmlIds(html));
462
+ const opens = (html.match(SCRIPT_OPEN_RE) ?? []).length;
463
+ const closes = (html.match(SCRIPT_CLOSE_RE) ?? []).length;
464
+ if (opens === 0) {
465
+ checks.push({
466
+ ok: true,
467
+ name: "script-tag-present",
468
+ detail: "no inline scripts (valid for a static page)"
469
+ });
470
+ } else if (opens > closes) {
471
+ checks.push({
472
+ ok: false,
473
+ name: "script-tag-balanced",
474
+ message: `${opens} <script> opening tag(s) but only ${closes} </script> closing tag(s) \u2014 the file is truncated mid-script`,
475
+ fixHint: "append the missing </script> close with `append_to_file`, or re-emit the full file with `write_file`."
476
+ });
477
+ return checks;
478
+ } else {
479
+ checks.push({
480
+ ok: true,
481
+ name: "script-tag-present",
482
+ detail: `${opens} inline <script> tag(s)`
483
+ });
484
+ }
485
+ let scriptIdx = 0;
486
+ const scripts = [];
487
+ for (const m of html.matchAll(SCRIPT_RE)) {
488
+ scriptIdx += 1;
489
+ const attrs = m[1] ?? "";
490
+ const body = m[2] ?? "";
491
+ if (body.length === 0) continue;
492
+ if (/\bsrc\s*=/.test(attrs)) continue;
493
+ const typeMatch = attrs.match(/\btype\s*=\s*["']([^"']+)["']/i);
494
+ if (typeMatch) {
495
+ const t = typeMatch[1].toLowerCase().trim();
496
+ if (t !== "text/javascript" && t !== "application/javascript" && t !== "module") {
497
+ continue;
498
+ }
499
+ }
500
+ const openIdx = m.index ?? 0;
501
+ const openLine = (html.slice(0, openIdx).match(/\n/g)?.length ?? 0) + 1;
502
+ scripts.push({ body, attrs, openLine });
503
+ const parseError = isModuleScript(attrs) ? tryParseSource(body, ts.ScriptKind.JS) : tryParseFunctionBody(body);
504
+ if (parseError) {
505
+ const locMatch = parseError.match(/line (\d+)(?:.*?col(?:umn)?\s*(\d+))?/i);
506
+ const scriptInternalLine = locMatch ? Number(locMatch[1]) : 1;
507
+ const col = locMatch?.[2] ? Number(locMatch[2]) : void 0;
508
+ const fileLine = openLine + scriptInternalLine - 1;
509
+ checks.push({
510
+ ok: false,
511
+ name: scriptIdx === 1 ? "script-body-parses" : `script-body-parses[${scriptIdx}]`,
512
+ message: parseError.replace(/\s+at <anonymous>.*$/s, "").trim(),
513
+ location: { line: fileLine, ...col ? { col } : {} },
514
+ excerpt: buildExcerpt(html, fileLine, 2),
515
+ fixHint: "fix the syntax error in the inline <script> body. If the script got cut off mid-statement, use `append_to_file` to send only the missing tail."
516
+ });
517
+ return checks;
518
+ }
519
+ }
520
+ if (scriptIdx > 0) {
521
+ checks.push({
522
+ ok: true,
523
+ name: "script-body-parses",
524
+ detail: `${scriptIdx} inline script(s) parse cleanly`
525
+ });
526
+ checks.push(validateUniqueTopLevelFunctions(scripts));
527
+ }
528
+ return checks;
529
+ }
530
+ function isModuleScript(attrs) {
531
+ return /\btype\s*=\s*["']module["']/i.test(attrs);
532
+ }
533
+ function validateHtmlDocumentStructure(html) {
534
+ const hasDocumentShell = /<!doctype\s+html\b/i.test(html) || /<html\b/i.test(html);
535
+ if (!hasDocumentShell) {
536
+ return { ok: true, name: "document-structure", detail: "HTML fragment" };
537
+ }
538
+ const missing = [];
539
+ if (/<html\b/i.test(html) && !/<\/html\s*>/i.test(html)) missing.push("</html>");
540
+ if (/<body\b/i.test(html) && !/<\/body\s*>/i.test(html)) missing.push("</body>");
541
+ if (missing.length > 0) {
542
+ return {
543
+ ok: false,
544
+ name: "document-structure",
545
+ message: `document is missing ${missing.join(" and ")}`,
546
+ fixHint: "restore the missing closing tag(s); the HTML document appears truncated."
547
+ };
548
+ }
549
+ return { ok: true, name: "document-structure", detail: "document shell closes cleanly" };
550
+ }
551
+ function validateUniqueHtmlIds(html) {
552
+ const withoutExecutableBodies = html.replace(
553
+ /<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,
554
+ (match) => match.replace(/[^\n]/g, " ")
555
+ );
556
+ const seen = /* @__PURE__ */ new Map();
557
+ const idRe = /\bid\s*=\s*(["'])([^"']+)\1/gi;
558
+ for (const match of withoutExecutableBodies.matchAll(idRe)) {
559
+ const id = match[2];
560
+ const line = (withoutExecutableBodies.slice(0, match.index).match(/\n/g)?.length ?? 0) + 1;
561
+ const firstLine = seen.get(id);
562
+ if (firstLine !== void 0) {
563
+ return {
564
+ ok: false,
565
+ name: "dom-ids-unique",
566
+ message: `duplicate id="${id}" (first declared at line ${firstLine})`,
567
+ location: { line },
568
+ excerpt: buildExcerpt(html, line, 2),
569
+ fixHint: "give each static DOM element a unique id and update matching JavaScript/CSS references."
570
+ };
571
+ }
572
+ seen.set(id, line);
573
+ }
574
+ return {
575
+ ok: true,
576
+ name: "dom-ids-unique",
577
+ detail: `${seen.size} static id${seen.size === 1 ? "" : "s"} checked`
578
+ };
579
+ }
580
+ function validateUniqueTopLevelFunctions(scripts) {
581
+ const seen = /* @__PURE__ */ new Map();
582
+ let count = 0;
583
+ for (const script of scripts) {
584
+ const sf = ts.createSourceFile(
585
+ "inline-script.js",
586
+ script.body,
587
+ ts.ScriptTarget.ES2022,
588
+ true,
589
+ ts.ScriptKind.JS
590
+ );
591
+ for (const statement of sf.statements) {
592
+ if (!ts.isFunctionDeclaration(statement) || !statement.name) continue;
593
+ count += 1;
594
+ const relative = sf.getLineAndCharacterOfPosition(statement.name.getStart(sf));
595
+ const line = script.openLine + relative.line;
596
+ const name = statement.name.text;
597
+ const firstLine = seen.get(name);
598
+ if (firstLine !== void 0) {
599
+ return {
600
+ ok: false,
601
+ name: "top-level-functions-unique",
602
+ message: `top-level function "${name}" is declared more than once (first declared at line ${firstLine}); the later declaration silently replaces the earlier one`,
603
+ location: { line, col: relative.character + 1 },
604
+ fixHint: "keep one implementation, merge the intended behavior into it, and remove the duplicate declaration."
605
+ };
606
+ }
607
+ seen.set(name, line);
608
+ }
609
+ }
610
+ return {
611
+ ok: true,
612
+ name: "top-level-functions-unique",
613
+ detail: `${count} function declaration${count === 1 ? "" : "s"} checked`
614
+ };
615
+ }
616
+ function tryParseSource(source, scriptKind) {
617
+ const fileName = scriptKind === ts.ScriptKind.TSX ? "source.tsx" : "source.js";
618
+ const output = ts.transpileModule(source, {
619
+ fileName,
620
+ reportDiagnostics: true,
621
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }
622
+ });
623
+ const diagnostics = output.diagnostics?.filter(
624
+ (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error && diagnostic.file !== void 0 && diagnostic.start !== void 0
625
+ );
626
+ if (!diagnostics || diagnostics.length === 0) return null;
627
+ const first = diagnostics[0];
628
+ const message = ts.flattenDiagnosticMessageText(first.messageText, "\n");
629
+ const { line, character } = first.file.getLineAndCharacterOfPosition(first.start);
630
+ return `${message} at line ${line + 1}, col ${character + 1}`;
631
+ }
632
+ function tryParseFunctionBody(body) {
633
+ try {
634
+ new Function(body);
635
+ return null;
636
+ } catch (err) {
637
+ return err instanceof Error ? err.message : String(err);
638
+ }
639
+ }
640
+ function validateJsTs(path, content) {
641
+ if (!content.text) {
642
+ return [{ ok: false, name: "file-readable", message: "could not read source as text" }];
643
+ }
644
+ const checks = [fileNonEmptyCheck(content)];
645
+ const lower = path.toLowerCase();
646
+ const scriptKind = lower.endsWith(".tsx") ? ts.ScriptKind.TSX : lower.endsWith(".ts") ? ts.ScriptKind.TS : lower.endsWith(".jsx") ? ts.ScriptKind.JSX : ts.ScriptKind.JS;
647
+ const sf = ts.createSourceFile(
648
+ path,
649
+ content.text,
650
+ ts.ScriptTarget.ES2022,
651
+ /*setParentNodes*/
652
+ true,
653
+ scriptKind
654
+ );
655
+ const diags = sf.parseDiagnostics;
656
+ if (!diags || diags.length === 0) {
657
+ const nestedModuleSyntax = findNestedStaticModuleDeclaration(sf);
658
+ if (nestedModuleSyntax) {
659
+ const { line: line2, character: character2 } = sf.getLineAndCharacterOfPosition(nestedModuleSyntax.getStart(sf));
660
+ checks.push({
661
+ ok: false,
662
+ name: "module-syntax",
663
+ message: "static import/export declarations are only valid at the top level of a module",
664
+ location: { line: line2 + 1, col: character2 + 1 },
665
+ excerpt: buildExcerpt(content.text, line2 + 1, 2),
666
+ fixHint: "move this import/export to the top of the file, or use dynamic import(...) inside functions."
667
+ });
668
+ return checks;
669
+ }
670
+ checks.push({
671
+ ok: true,
672
+ name: "parses",
673
+ detail: `${scriptKind === ts.ScriptKind.TS || scriptKind === ts.ScriptKind.TSX ? "TypeScript" : "JavaScript"} parses cleanly`
674
+ });
675
+ return checks;
676
+ }
677
+ const first = diags[0];
678
+ const msg = ts.flattenDiagnosticMessageText(first.messageText, "\n");
679
+ const { line, character } = sf.getLineAndCharacterOfPosition(first.start);
680
+ checks.push({
681
+ ok: false,
682
+ name: "parses",
683
+ message: msg,
684
+ location: { line: line + 1, col: character + 1 },
685
+ excerpt: buildExcerpt(content.text, line + 1, 2),
686
+ fixHint: "fix the syntax error and re-emit. If the file was cut off mid-statement, use `append_to_file` to send only the missing tail."
687
+ });
688
+ return checks;
689
+ }
690
+ function findNestedStaticModuleDeclaration(sf) {
691
+ let found = null;
692
+ const visit = (node) => {
693
+ if (found) return;
694
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node) || ts.isExportAssignment(node)) && node.parent !== sf) {
695
+ found = node;
696
+ return;
697
+ }
698
+ ts.forEachChild(node, visit);
699
+ };
700
+ visit(sf);
701
+ return found;
702
+ }
703
+ function validateJson(_path, content) {
704
+ if (!content.text) {
705
+ return [{ ok: false, name: "file-readable", message: "could not read JSON as text" }];
706
+ }
707
+ const checks = [fileNonEmptyCheck(content)];
708
+ try {
709
+ JSON.parse(content.text);
710
+ checks.push({ ok: true, name: "parses", detail: "JSON parses cleanly" });
711
+ } catch (err) {
712
+ const msg = err instanceof Error ? err.message : String(err);
713
+ const posMatch = msg.match(/at position (\d+)/);
714
+ if (posMatch) {
715
+ const pos = Number(posMatch[1]);
716
+ const before = content.text.slice(0, pos);
717
+ const line = (before.match(/\n/g)?.length ?? 0) + 1;
718
+ const lastNl = before.lastIndexOf("\n");
719
+ const col = lastNl < 0 ? pos + 1 : pos - lastNl;
720
+ checks.push({
721
+ ok: false,
722
+ name: "parses",
723
+ message: msg.replace(/\s+at position \d+/, ""),
724
+ location: { line, col },
725
+ excerpt: buildExcerpt(content.text, line, 2)
726
+ });
727
+ } else {
728
+ checks.push({ ok: false, name: "parses", message: msg });
729
+ }
730
+ }
731
+ return checks;
732
+ }
733
+ var PNG_MAGIC = [137, 80, 78, 71, 13, 10, 26, 10];
734
+ var JPG_MAGIC = [255, 216, 255];
735
+ var WEBP_RIFF = [82, 73, 70, 70];
736
+ var WEBP_VP8 = [87, 69, 66, 80];
737
+ var GIF_MAGIC = [71, 73, 70, 56];
738
+ function bytesMatch(actual, expected, offset = 0) {
739
+ if (actual.length < offset + expected.length) return false;
740
+ for (let i = 0; i < expected.length; i++) {
741
+ if (actual[offset + i] !== expected[i]) return false;
742
+ }
743
+ return true;
744
+ }
745
+ function hexHead(bytes, n = 8) {
746
+ const slice = bytes.slice(0, n);
747
+ return Array.from(slice).map((b) => b.toString(16).padStart(2, "0")).join(" ");
748
+ }
749
+ var BINARY_ROUND_TRIP_HINT = "binary content was likely corrupted by `write_file` (which round-trips through a JSON string and breaks non-UTF-8 bytes). Use `copy_artifact_to_workspace` instead to move generated images from the artifacts drawer.";
750
+ function validateImage(path, content) {
751
+ const lower = path.toLowerCase();
752
+ const checks = [];
753
+ if (content.totalBytes === 0) {
754
+ checks.push({
755
+ ok: false,
756
+ name: "file-non-empty",
757
+ message: "file is empty (0 bytes)",
758
+ fixHint: BINARY_ROUND_TRIP_HINT
759
+ });
760
+ return checks;
761
+ }
762
+ checks.push({ ok: true, name: "file-non-empty", detail: `${content.totalBytes} bytes` });
763
+ if (!lower.endsWith(".svg")) {
764
+ if (content.totalBytes < 100) {
765
+ checks.push({
766
+ ok: false,
767
+ name: "bytes-min",
768
+ message: `${content.totalBytes} bytes \u2014 too small to be a real image (\u2265 100 bytes expected)`,
769
+ fixHint: BINARY_ROUND_TRIP_HINT
770
+ });
771
+ } else {
772
+ checks.push({ ok: true, name: "bytes-min", detail: `${content.totalBytes} bytes \u2265 100` });
773
+ }
774
+ }
775
+ if (!content.bytes) {
776
+ checks.push({
777
+ ok: false,
778
+ name: "magic-bytes",
779
+ message: "image bytes not available to validate header",
780
+ fixHint: "caller did not provide binary content; this check requires the raw bytes."
781
+ });
782
+ return checks;
783
+ }
784
+ if (lower.endsWith(".svg")) {
785
+ const head = new TextDecoder("utf-8", { fatal: false }).decode(content.bytes.slice(0, 256)).trimStart();
786
+ if (head.startsWith("<?xml") || head.startsWith("<svg")) {
787
+ checks.push({ ok: true, name: "svg-header", detail: "starts with <?xml or <svg" });
788
+ } else {
789
+ checks.push({
790
+ ok: false,
791
+ name: "svg-header",
792
+ message: `SVG should start with <?xml or <svg, got: "${head.slice(0, 40)}"`,
793
+ fixHint: BINARY_ROUND_TRIP_HINT
794
+ });
795
+ }
796
+ return checks;
797
+ }
798
+ let expected;
799
+ let label;
800
+ let pass = false;
801
+ if (lower.endsWith(".png")) {
802
+ expected = PNG_MAGIC;
803
+ label = "PNG";
804
+ pass = bytesMatch(content.bytes, PNG_MAGIC);
805
+ } else if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) {
806
+ expected = JPG_MAGIC;
807
+ label = "JPEG";
808
+ pass = bytesMatch(content.bytes, JPG_MAGIC);
809
+ } else if (lower.endsWith(".webp")) {
810
+ expected = WEBP_RIFF;
811
+ label = "WebP";
812
+ pass = bytesMatch(content.bytes, WEBP_RIFF) && bytesMatch(content.bytes, WEBP_VP8, 8);
813
+ } else if (lower.endsWith(".gif")) {
814
+ expected = GIF_MAGIC;
815
+ label = "GIF";
816
+ pass = bytesMatch(content.bytes, GIF_MAGIC);
817
+ } else {
818
+ checks.push({ ok: true, name: "magic-bytes", detail: "no validator registered for extension" });
819
+ return checks;
820
+ }
821
+ if (pass) {
822
+ checks.push({
823
+ ok: true,
824
+ name: "magic-bytes",
825
+ detail: `valid ${label} header`
826
+ });
827
+ } else {
828
+ const expectedHex = expected.map((b) => b.toString(16).padStart(2, "0")).join(" ");
829
+ checks.push({
830
+ ok: false,
831
+ name: "magic-bytes",
832
+ message: `not a valid ${label} header. First ${expected.length} bytes: ${hexHead(content.bytes, expected.length)} (expected: ${expectedHex})`,
833
+ fixHint: BINARY_ROUND_TRIP_HINT
834
+ });
835
+ }
836
+ return checks;
837
+ }
838
+
839
+ // src/platform-tool-availability.ts
840
+ import { spawnSync } from "child_process";
841
+ var DENY_NET_TOOLS = ["run_nodejs_script", "derive_file"];
842
+ var linuxSystemdProbe;
843
+ function canUseLinuxSystemdDenyNet() {
844
+ if (process.platform !== "linux") return false;
845
+ if (linuxSystemdProbe !== void 0) return linuxSystemdProbe;
846
+ const probe = "const net=require('node:net');const s=net.connect({host:'127.0.0.1',port:9});s.once('connect',()=>process.exit(9));s.once('error',e=>process.exit(['EAFNOSUPPORT','EPERM','EACCES'].includes(e.code)?0:2));setTimeout(()=>process.exit(3),1000);";
847
+ const result = spawnSync(
848
+ "systemd-run",
849
+ [
850
+ "--user",
851
+ "--quiet",
852
+ "--pipe",
853
+ "--wait",
854
+ "--collect",
855
+ "-p",
856
+ "RestrictAddressFamilies=AF_UNIX",
857
+ "-p",
858
+ "RuntimeMaxSec=3",
859
+ "--",
860
+ process.execPath,
861
+ "-e",
862
+ probe
863
+ ],
864
+ { stdio: "ignore", timeout: 3e3 }
865
+ );
866
+ linuxSystemdProbe = result.status === 0;
867
+ return linuxSystemdProbe;
868
+ }
869
+ function unavailableToolsForPlatform(platform, options = {}) {
870
+ if (platform === "darwin") return [];
871
+ if (platform === "linux" && (options.linuxSystemdAvailable ?? canUseLinuxSystemdDenyNet())) {
872
+ return [];
873
+ }
874
+ return DENY_NET_TOOLS;
875
+ }
876
+
877
+ // src/github-pr-selection.ts
878
+ function prioritizePullsForCurrentBranch(pulls, currentBranch) {
879
+ const branch = currentBranch?.trim();
880
+ if (!branch) return { pulls: [...pulls], matchingCount: 0 };
881
+ const matching = [];
882
+ const others = [];
883
+ for (const pull of pulls) {
884
+ (pull.headRef === branch ? matching : others).push(pull);
885
+ }
886
+ return {
887
+ pulls: [...matching, ...others],
888
+ currentBranch: branch,
889
+ matchingCount: matching.length
890
+ };
891
+ }
892
+ export {
893
+ ALWAYS_REGISTERED_TOOLS,
894
+ BUILTIN_TOOL_NAMES,
895
+ CANONICAL_TOOL_NAMES,
896
+ CONDITIONALLY_REGISTERED_TOOLS,
897
+ LEGACY_SPELLING_BY_CANONICAL,
898
+ LEGACY_TOOL_NAMES,
899
+ RENAMED_TOOLS,
900
+ RESERVED_TOOL_NAMES,
901
+ TOOL_NAME_TOMBSTONES,
902
+ TOOL_REGISTRY,
903
+ canUseLinuxSystemdDenyNet,
904
+ canonicalToolName,
905
+ formatValidateResult,
906
+ normalizeToolNameSpelling,
907
+ prioritizePullsForCurrentBranch,
908
+ resolveToolNameSpelling,
909
+ unavailableToolsForPlatform,
910
+ validateFile
911
+ };