@bendyline/gezel-mcp 1.2.7 → 1.2.9

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.
@@ -0,0 +1,3027 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/harness/index.ts
4
+ import { createRequire } from "module";
5
+ import { fileURLToPath } from "url";
6
+ import { HARNESS_SERVER_INSTRUCTIONS, HarnessClientIdSchema } from "@bendyline/gezel";
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { RootsListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
10
+
11
+ // src/harness/arguments.ts
12
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
13
+ import { z } from "zod";
14
+ var EXAMPLES = {
15
+ search: { query: "where uploaded files are checked for size" },
16
+ search_memory: { query: "how we name release branches" },
17
+ save_memory: { text: "Releases ship on Tuesdays after the 14:00 check-in." },
18
+ read_doc_as_markdown: { path: "docs/report.docx" },
19
+ read_document: { path: "style-guide.md" },
20
+ describe_image: { path: "screenshots/error.png" },
21
+ generate_image: {
22
+ prompt: "A white delivery van on a quiet street at sunrise, flat illustration"
23
+ },
24
+ convert_document: {
25
+ source: { kind: "markdown", markdown: "# Title\n\nBody text." },
26
+ targets: ["docx"]
27
+ },
28
+ save_artifact: {
29
+ artifactUri: "docblocks://artifacts/<id from convert_document>",
30
+ destination: { path: "report.docx" }
31
+ },
32
+ preview_document: { source: { kind: "artifact", uri: "docblocks://artifacts/<id>" } },
33
+ inspect_document: { source: { kind: "file", path: "docs/report.docx" } }
34
+ };
35
+ function missingArguments(schema, args) {
36
+ const given = args && typeof args === "object" ? args : {};
37
+ return (schema.required ?? []).filter(
38
+ (name) => given[name] === void 0 || given[name] === null
39
+ );
40
+ }
41
+ function describe(schema, name) {
42
+ const description = schema.properties?.[name]?.description?.trim();
43
+ return description ? `\`${name}\` (${description.replace(/\.$/, "")})` : `\`${name}\``;
44
+ }
45
+ function listed(items) {
46
+ return items.length <= 1 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
47
+ }
48
+ function argumentHelp(tool, schema, args, detail) {
49
+ const missing = missingArguments(schema, args);
50
+ const example = EXAMPLES[tool];
51
+ const parts = missing.length > 0 ? [`\`${tool}\` needs ${listed(missing.map((name) => describe(schema, name)))}.`] : [
52
+ `\`${tool}\` could not use those arguments: ${detail ?? "they do not match its schema"}.`,
53
+ ...(schema.required ?? []).length > 0 ? [`It needs ${listed((schema.required ?? []).map((name) => describe(schema, name)))}.`] : []
54
+ ];
55
+ if (example) parts.push(`For example: ${JSON.stringify(example)}`);
56
+ return parts.join(" ");
57
+ }
58
+ var SDK_PREFIX = /^(MCP error -?\d+: )?Input validation error: Invalid arguments for tool \S+: /;
59
+ function teachInvalidArguments(server) {
60
+ const target = server;
61
+ const validate = target.validateToolInput.bind(server);
62
+ target.validateToolInput = async (tool, args, name) => {
63
+ try {
64
+ return await validate(tool, args, name);
65
+ } catch (err) {
66
+ if (!(err instanceof McpError) || err.code !== ErrorCode.InvalidParams) throw err;
67
+ let schema = {};
68
+ try {
69
+ schema = z.toJSONSchema(tool.inputSchema, { io: "input" });
70
+ } catch {
71
+ }
72
+ throw new Error(argumentHelp(name, schema, args, err.message.replace(SDK_PREFIX, "")));
73
+ }
74
+ };
75
+ }
76
+
77
+ // src/harness/documents.ts
78
+ import { createHash } from "crypto";
79
+ import { constants, existsSync, readFileSync as readFileSync2 } from "fs";
80
+ import { access, mkdir } from "fs/promises";
81
+ import { tmpdir } from "os";
82
+ import { basename, dirname, isAbsolute as isAbsolute4, join as join3, resolve as resolve3 } from "path";
83
+ import {
84
+ HARNESS_DOCUMENT_TOOL_NAMES,
85
+ HARNESS_DOCUMENT_TOOL_NOTES
86
+ } from "@bendyline/gezel";
87
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
88
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
89
+ import { z as z3 } from "zod";
90
+
91
+ // src/harness/docblocks-tools.json
92
+ var docblocks_tools_default = {
93
+ docblocksVersion: "2.7.5",
94
+ tools: [
95
+ {
96
+ name: "convert_document",
97
+ description: "Convert plain text, Markdown, bundles, or linked-registry inputs directly into one or more immutable artifacts. Plain Markdown needs no preflight or annotations; valid Squisq annotations are optional layout hints. For PPTX, heading-based slide boundaries do not need --- separators. Use save_artifact only for durable filesystem output.",
98
+ inputSchema: {
99
+ type: "object",
100
+ properties: {
101
+ source: {
102
+ anyOf: [
103
+ {
104
+ type: "object",
105
+ properties: {
106
+ kind: {
107
+ type: "string",
108
+ const: "markdown"
109
+ },
110
+ markdown: {
111
+ type: "string",
112
+ maxLength: 20971520,
113
+ pattern: "^[^\\u0000\\u007f]*$"
114
+ },
115
+ name: {
116
+ anyOf: [
117
+ {
118
+ type: "string",
119
+ maxLength: 1024,
120
+ pattern: "^[^\\u0000\\u007f]*$"
121
+ },
122
+ {
123
+ type: "null"
124
+ }
125
+ ],
126
+ default: null
127
+ }
128
+ },
129
+ required: ["kind", "markdown"],
130
+ additionalProperties: false
131
+ },
132
+ {
133
+ type: "object",
134
+ properties: {
135
+ kind: {
136
+ type: "string",
137
+ const: "file"
138
+ },
139
+ rootId: {
140
+ anyOf: [
141
+ {
142
+ type: "string",
143
+ minLength: 1,
144
+ maxLength: 256,
145
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
146
+ },
147
+ {
148
+ type: "null"
149
+ }
150
+ ],
151
+ default: null
152
+ },
153
+ path: {
154
+ type: "string",
155
+ minLength: 1,
156
+ maxLength: 4096,
157
+ pattern: "^(?!\\/)(?![A-Za-z]:)(?!.*(?:^|\\/)(?:\\.{1,2})(?:\\/|$))(?!.*\\/\\/)(?!.*[\\\\\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"
158
+ },
159
+ format: {
160
+ anyOf: [
161
+ {
162
+ type: "string",
163
+ minLength: 1,
164
+ maxLength: 64,
165
+ pattern: "^[a-z0-9][a-z0-9.+_-]*$"
166
+ },
167
+ {
168
+ type: "null"
169
+ }
170
+ ],
171
+ default: null
172
+ }
173
+ },
174
+ required: ["kind", "path"],
175
+ additionalProperties: false
176
+ },
177
+ {
178
+ type: "object",
179
+ properties: {
180
+ kind: {
181
+ type: "string",
182
+ const: "artifact"
183
+ },
184
+ uri: {
185
+ type: "string",
186
+ maxLength: 278,
187
+ pattern: "^docblocks:\\/\\/artifacts\\/[A-Za-z0-9][A-Za-z0-9._:-]*$"
188
+ }
189
+ },
190
+ required: ["kind", "uri"],
191
+ additionalProperties: false
192
+ },
193
+ {
194
+ type: "object",
195
+ properties: {
196
+ kind: {
197
+ type: "string",
198
+ const: "bundle"
199
+ },
200
+ markdown: {
201
+ type: "string",
202
+ maxLength: 20971520,
203
+ pattern: "^[^\\u0000\\u007f]*$"
204
+ },
205
+ assets: {
206
+ type: "array",
207
+ items: {
208
+ type: "object",
209
+ properties: {
210
+ path: {
211
+ $ref: "#/properties/source/anyOf/1/properties/path"
212
+ },
213
+ source: {
214
+ anyOf: [
215
+ {
216
+ type: "object",
217
+ properties: {
218
+ kind: {
219
+ type: "string",
220
+ const: "file"
221
+ },
222
+ rootId: {
223
+ $ref: "#/properties/source/anyOf/1/properties/rootId/anyOf/0"
224
+ },
225
+ path: {
226
+ $ref: "#/properties/source/anyOf/1/properties/path"
227
+ }
228
+ },
229
+ required: ["kind", "rootId", "path"],
230
+ additionalProperties: false
231
+ },
232
+ {
233
+ type: "object",
234
+ properties: {
235
+ kind: {
236
+ type: "string",
237
+ const: "artifact"
238
+ },
239
+ uri: {
240
+ $ref: "#/properties/source/anyOf/2/properties/uri"
241
+ }
242
+ },
243
+ required: ["kind", "uri"],
244
+ additionalProperties: false
245
+ }
246
+ ]
247
+ },
248
+ mimeType: {
249
+ anyOf: [
250
+ {
251
+ type: "string",
252
+ minLength: 3,
253
+ maxLength: 256,
254
+ pattern: "^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$"
255
+ },
256
+ {
257
+ type: "null"
258
+ }
259
+ ]
260
+ },
261
+ altText: {
262
+ anyOf: [
263
+ {
264
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
265
+ },
266
+ {
267
+ type: "null"
268
+ }
269
+ ]
270
+ },
271
+ credit: {
272
+ anyOf: [
273
+ {
274
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
275
+ },
276
+ {
277
+ type: "null"
278
+ }
279
+ ]
280
+ },
281
+ license: {
282
+ anyOf: [
283
+ {
284
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
285
+ },
286
+ {
287
+ type: "null"
288
+ }
289
+ ]
290
+ }
291
+ },
292
+ required: ["path", "source", "mimeType", "altText", "credit", "license"],
293
+ additionalProperties: false
294
+ },
295
+ maxItems: 256
296
+ },
297
+ name: {
298
+ anyOf: [
299
+ {
300
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
301
+ },
302
+ {
303
+ type: "null"
304
+ }
305
+ ],
306
+ default: null
307
+ }
308
+ },
309
+ required: ["kind", "markdown", "assets"],
310
+ additionalProperties: false
311
+ }
312
+ ]
313
+ },
314
+ targets: {
315
+ type: "array",
316
+ items: {
317
+ anyOf: [
318
+ {
319
+ type: "object",
320
+ properties: {
321
+ format: {
322
+ type: "string",
323
+ const: "md"
324
+ },
325
+ fidelity: {
326
+ type: "string",
327
+ enum: ["semantic"]
328
+ }
329
+ },
330
+ required: ["format"],
331
+ additionalProperties: false
332
+ },
333
+ {
334
+ type: "object",
335
+ properties: {
336
+ format: {
337
+ type: "string",
338
+ const: "dbk"
339
+ },
340
+ fidelity: {
341
+ type: "string",
342
+ enum: ["semantic", "editable-native"]
343
+ }
344
+ },
345
+ required: ["format"],
346
+ additionalProperties: false
347
+ },
348
+ {
349
+ type: "object",
350
+ properties: {
351
+ format: {
352
+ type: "string",
353
+ const: "docx"
354
+ },
355
+ fidelity: {
356
+ type: "string",
357
+ enum: ["semantic", "editable-native"]
358
+ },
359
+ title: {
360
+ type: "string",
361
+ maxLength: 4e3
362
+ },
363
+ author: {
364
+ type: "string",
365
+ maxLength: 4e3
366
+ },
367
+ description: {
368
+ type: "string",
369
+ maxLength: 8e3
370
+ },
371
+ defaultFont: {
372
+ type: "string",
373
+ maxLength: 256
374
+ },
375
+ defaultFontSize: {
376
+ type: "number",
377
+ minimum: 6,
378
+ maximum: 96
379
+ }
380
+ },
381
+ required: ["format"],
382
+ additionalProperties: false
383
+ },
384
+ {
385
+ type: "object",
386
+ properties: {
387
+ format: {
388
+ type: "string",
389
+ const: "pdf"
390
+ },
391
+ fidelity: {
392
+ type: "string",
393
+ enum: ["semantic", "rendered-fidelity", "hybrid"]
394
+ },
395
+ title: {
396
+ $ref: "#/properties/targets/items/anyOf/2/properties/title"
397
+ },
398
+ author: {
399
+ $ref: "#/properties/targets/items/anyOf/2/properties/author"
400
+ },
401
+ pageSize: {
402
+ type: "string",
403
+ enum: ["letter", "a4"]
404
+ },
405
+ margin: {
406
+ type: "number",
407
+ minimum: 0,
408
+ maximum: 288
409
+ },
410
+ defaultFontSize: {
411
+ type: "number",
412
+ minimum: 6,
413
+ maximum: 96
414
+ },
415
+ width: {
416
+ type: "integer",
417
+ minimum: 160,
418
+ maximum: 1920
419
+ },
420
+ height: {
421
+ type: "integer",
422
+ minimum: 90,
423
+ maximum: 1920
424
+ }
425
+ },
426
+ required: ["format"],
427
+ additionalProperties: false
428
+ },
429
+ {
430
+ type: "object",
431
+ properties: {
432
+ format: {
433
+ type: "string",
434
+ const: "pptx"
435
+ },
436
+ fidelity: {
437
+ type: "string",
438
+ enum: ["semantic", "editable-native", "rendered-fidelity", "hybrid"]
439
+ },
440
+ title: {
441
+ $ref: "#/properties/targets/items/anyOf/2/properties/title"
442
+ },
443
+ author: {
444
+ $ref: "#/properties/targets/items/anyOf/2/properties/author"
445
+ },
446
+ description: {
447
+ $ref: "#/properties/targets/items/anyOf/2/properties/description"
448
+ },
449
+ slideBreak: {
450
+ type: "string",
451
+ enum: ["h1", "h2", "heading"],
452
+ default: "h1",
453
+ description: "Defaults to h1: author one H1 per slide; deeper headings remain body text and no extra cover is inserted. h2 breaks at H1/H2; heading breaks at any depth. Include a title slide as an authored heading; do not add --- between heading-based slides."
454
+ },
455
+ defaultFont: {
456
+ type: "string",
457
+ maxLength: 256
458
+ },
459
+ defaultFontSize: {
460
+ type: "number",
461
+ minimum: 6,
462
+ maximum: 96
463
+ },
464
+ width: {
465
+ type: "integer",
466
+ minimum: 160,
467
+ maximum: 1920
468
+ },
469
+ height: {
470
+ type: "integer",
471
+ minimum: 90,
472
+ maximum: 1920
473
+ }
474
+ },
475
+ required: ["format"],
476
+ additionalProperties: false
477
+ },
478
+ {
479
+ type: "object",
480
+ properties: {
481
+ format: {
482
+ type: "string",
483
+ const: "xlsx"
484
+ },
485
+ fidelity: {
486
+ type: "string",
487
+ enum: ["semantic", "editable-native"]
488
+ },
489
+ title: {
490
+ $ref: "#/properties/targets/items/anyOf/2/properties/title"
491
+ },
492
+ author: {
493
+ $ref: "#/properties/targets/items/anyOf/2/properties/author"
494
+ },
495
+ sheetNamePrefix: {
496
+ type: "string",
497
+ maxLength: 31
498
+ }
499
+ },
500
+ required: ["format"],
501
+ additionalProperties: false
502
+ },
503
+ {
504
+ type: "object",
505
+ properties: {
506
+ format: {
507
+ type: "string",
508
+ const: "csv"
509
+ },
510
+ fidelity: {
511
+ type: "string",
512
+ enum: ["semantic"]
513
+ },
514
+ delimiter: {
515
+ type: "string",
516
+ minLength: 1,
517
+ maxLength: 4
518
+ },
519
+ tableIndex: {
520
+ type: "integer",
521
+ minimum: 0,
522
+ maximum: 1e4
523
+ }
524
+ },
525
+ required: ["format"],
526
+ additionalProperties: false
527
+ },
528
+ {
529
+ type: "object",
530
+ properties: {
531
+ format: {
532
+ type: "string",
533
+ const: "html"
534
+ },
535
+ fidelity: {
536
+ type: "string",
537
+ enum: ["semantic"]
538
+ },
539
+ mode: {
540
+ type: "string",
541
+ enum: ["slideshow", "static"]
542
+ },
543
+ autoPlay: {
544
+ type: "boolean"
545
+ },
546
+ title: {
547
+ $ref: "#/properties/targets/items/anyOf/2/properties/title"
548
+ }
549
+ },
550
+ required: ["format"],
551
+ additionalProperties: false
552
+ },
553
+ {
554
+ type: "object",
555
+ properties: {
556
+ format: {
557
+ type: "string",
558
+ const: "htmlzip"
559
+ },
560
+ fidelity: {
561
+ type: "string",
562
+ enum: ["semantic"]
563
+ },
564
+ mode: {
565
+ type: "string",
566
+ enum: ["slideshow", "static"]
567
+ },
568
+ autoPlay: {
569
+ type: "boolean"
570
+ },
571
+ title: {
572
+ $ref: "#/properties/targets/items/anyOf/2/properties/title"
573
+ }
574
+ },
575
+ required: ["format"],
576
+ additionalProperties: false
577
+ },
578
+ {
579
+ type: "object",
580
+ properties: {
581
+ format: {
582
+ type: "string",
583
+ const: "epub"
584
+ },
585
+ fidelity: {
586
+ type: "string",
587
+ enum: ["semantic"]
588
+ },
589
+ title: {
590
+ $ref: "#/properties/targets/items/anyOf/2/properties/title"
591
+ },
592
+ author: {
593
+ $ref: "#/properties/targets/items/anyOf/2/properties/author"
594
+ },
595
+ description: {
596
+ $ref: "#/properties/targets/items/anyOf/2/properties/description"
597
+ },
598
+ language: {
599
+ type: "string",
600
+ maxLength: 64
601
+ },
602
+ publisher: {
603
+ type: "string",
604
+ maxLength: 4e3
605
+ }
606
+ },
607
+ required: ["format"],
608
+ additionalProperties: false
609
+ },
610
+ {
611
+ type: "object",
612
+ properties: {
613
+ format: {
614
+ type: "string",
615
+ const: "mp4"
616
+ },
617
+ fidelity: {
618
+ type: "string",
619
+ enum: ["rendered-fidelity"]
620
+ },
621
+ fps: {
622
+ type: "integer",
623
+ minimum: 1,
624
+ maximum: 60
625
+ },
626
+ quality: {
627
+ type: "string",
628
+ enum: ["draft", "normal", "high"]
629
+ },
630
+ orientation: {
631
+ type: "string",
632
+ enum: ["landscape", "portrait"]
633
+ },
634
+ width: {
635
+ type: "integer",
636
+ minimum: 16,
637
+ maximum: 3840
638
+ },
639
+ height: {
640
+ type: "integer",
641
+ minimum: 16,
642
+ maximum: 3840
643
+ },
644
+ captionStyle: {
645
+ type: "string",
646
+ enum: ["standard", "social"]
647
+ },
648
+ coverPreRoll: {
649
+ type: "number",
650
+ minimum: 0,
651
+ maximum: 60
652
+ },
653
+ animationsEnabled: {
654
+ type: "boolean",
655
+ description: "Explicit rendered-media motion switch. Use it only to honor a user preference such as no motion or dynamic motion; otherwise rely on the theme/target default. It does not select an individual transition."
656
+ }
657
+ },
658
+ required: ["format"],
659
+ additionalProperties: false
660
+ },
661
+ {
662
+ type: "object",
663
+ properties: {
664
+ format: {
665
+ type: "string",
666
+ const: "gif"
667
+ },
668
+ fidelity: {
669
+ type: "string",
670
+ enum: ["rendered-fidelity"]
671
+ },
672
+ fps: {
673
+ type: "integer",
674
+ minimum: 1,
675
+ maximum: 30
676
+ },
677
+ orientation: {
678
+ type: "string",
679
+ enum: ["landscape", "portrait"]
680
+ },
681
+ width: {
682
+ type: "integer",
683
+ minimum: 16,
684
+ maximum: 1920
685
+ },
686
+ height: {
687
+ type: "integer",
688
+ minimum: 16,
689
+ maximum: 1920
690
+ },
691
+ captionStyle: {
692
+ type: "string",
693
+ enum: ["standard", "social"]
694
+ },
695
+ coverPreRoll: {
696
+ type: "number",
697
+ minimum: 0,
698
+ maximum: 60
699
+ },
700
+ animationsEnabled: {
701
+ type: "boolean",
702
+ description: "Explicit rendered-media motion switch. Use it only to honor a user preference such as no motion or dynamic motion; otherwise rely on the theme/target default. It does not select an individual transition."
703
+ },
704
+ loop: {
705
+ type: "integer",
706
+ minimum: -1,
707
+ maximum: 65535
708
+ },
709
+ maxColors: {
710
+ type: "integer",
711
+ minimum: 2,
712
+ maximum: 256
713
+ },
714
+ dither: {
715
+ type: "string",
716
+ enum: [
717
+ "none",
718
+ "bayer",
719
+ "heckbert",
720
+ "floyd_steinberg",
721
+ "sierra2",
722
+ "sierra2_4a"
723
+ ]
724
+ },
725
+ bayerScale: {
726
+ type: "integer",
727
+ minimum: 0,
728
+ maximum: 5
729
+ }
730
+ },
731
+ required: ["format"],
732
+ additionalProperties: false
733
+ },
734
+ {
735
+ type: "object",
736
+ properties: {
737
+ format: {
738
+ type: "string",
739
+ const: "png"
740
+ },
741
+ fidelity: {
742
+ type: "string",
743
+ enum: ["rendered-fidelity"]
744
+ },
745
+ resolution: {
746
+ type: "string",
747
+ enum: [
748
+ "hd",
749
+ "fhd",
750
+ "4k",
751
+ "square",
752
+ "square-2k",
753
+ "portrait",
754
+ "portrait-4k",
755
+ "standard"
756
+ ],
757
+ description: "Named output size for the Dashboard image. Mutually exclusive with width/height."
758
+ },
759
+ width: {
760
+ type: "integer",
761
+ minimum: 64,
762
+ maximum: 7680,
763
+ description: "Custom pixel width. Requires height and excludes resolution."
764
+ },
765
+ height: {
766
+ type: "integer",
767
+ minimum: 64,
768
+ maximum: 7680,
769
+ description: "Custom pixel height. Requires width and excludes resolution."
770
+ },
771
+ layout: {
772
+ type: "string",
773
+ maxLength: 64,
774
+ description: `Dashboard layout id, or "auto" to pick by block count. Omit to honor the document's own squisq-dashboard-layout frontmatter.`
775
+ },
776
+ style: {
777
+ type: "string",
778
+ enum: ["basic", "card", "panel", "accent"],
779
+ description: "Cell dressing around each block. Omit to honor the document's own squisq-dashboard-style frontmatter."
780
+ },
781
+ title: {
782
+ type: "boolean",
783
+ description: "Render the document-title band. Omit to honor the document\u2019s own setting."
784
+ }
785
+ },
786
+ required: ["format"],
787
+ additionalProperties: false
788
+ }
789
+ ]
790
+ },
791
+ minItems: 1,
792
+ maxItems: 12
793
+ },
794
+ themeId: {
795
+ type: "string",
796
+ minLength: 1,
797
+ maxLength: 256,
798
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$",
799
+ description: "Exact Squisq theme id. Infer it from the brief when the visual direction is clear. If transformId is set and no exact theme was requested, omit themeId so the transform can apply its preferred compatible theme."
800
+ },
801
+ transformId: {
802
+ $ref: "#/properties/themeId",
803
+ description: "Optional Squisq Summarize style id. It can change content emphasis, density, pacing, and structure; leave it unset for source-preserving work unless summarization or visual restructuring is requested or permitted."
804
+ },
805
+ autoTemplates: {
806
+ type: "boolean",
807
+ description: "Enable content-aware automatic template selection. Defaults to true; explicit annotations still take precedence."
808
+ },
809
+ title: {
810
+ type: "string",
811
+ maxLength: 4e3
812
+ }
813
+ },
814
+ required: ["source", "targets"],
815
+ additionalProperties: false,
816
+ $schema: "http://json-schema.org/draft-07/schema#"
817
+ },
818
+ annotations: {
819
+ readOnlyHint: false,
820
+ destructiveHint: false,
821
+ idempotentHint: false,
822
+ openWorldHint: false
823
+ }
824
+ },
825
+ {
826
+ name: "save_artifact",
827
+ description: "Materialize an immutable artifact below a configured write root. Creation is no-replace; replacement requires the current SHA-256.",
828
+ inputSchema: {
829
+ type: "object",
830
+ properties: {
831
+ artifactUri: {
832
+ type: "string",
833
+ maxLength: 278,
834
+ pattern: "^docblocks:\\/\\/artifacts\\/[A-Za-z0-9][A-Za-z0-9._:-]*$"
835
+ },
836
+ destination: {
837
+ anyOf: [
838
+ {
839
+ type: "object",
840
+ properties: {
841
+ rootId: {
842
+ type: "string",
843
+ minLength: 1,
844
+ maxLength: 256,
845
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
846
+ },
847
+ path: {
848
+ type: "string",
849
+ minLength: 1,
850
+ maxLength: 4096,
851
+ pattern: "^(?!\\/)(?![A-Za-z]:)(?!.*(?:^|\\/)(?:\\.{1,2})(?:\\/|$))(?!.*\\/\\/)(?!.*[\\\\\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"
852
+ },
853
+ ifExists: {
854
+ type: "string",
855
+ const: "error"
856
+ },
857
+ expectedSha256: {
858
+ type: "null",
859
+ default: null
860
+ }
861
+ },
862
+ required: ["rootId", "path", "ifExists"],
863
+ additionalProperties: false
864
+ },
865
+ {
866
+ type: "object",
867
+ properties: {
868
+ rootId: {
869
+ $ref: "#/properties/destination/anyOf/0/properties/rootId"
870
+ },
871
+ path: {
872
+ $ref: "#/properties/destination/anyOf/0/properties/path"
873
+ },
874
+ ifExists: {
875
+ type: "string",
876
+ const: "replace"
877
+ },
878
+ expectedSha256: {
879
+ type: "string",
880
+ pattern: "^[a-f0-9]{64}$"
881
+ }
882
+ },
883
+ required: ["rootId", "path", "ifExists", "expectedSha256"],
884
+ additionalProperties: false
885
+ }
886
+ ]
887
+ }
888
+ },
889
+ required: ["artifactUri", "destination"],
890
+ additionalProperties: false,
891
+ $schema: "http://json-schema.org/draft-07/schema#"
892
+ },
893
+ annotations: {
894
+ readOnlyHint: false,
895
+ destructiveHint: true,
896
+ idempotentHint: false,
897
+ openWorldHint: false
898
+ }
899
+ },
900
+ {
901
+ name: "preview_document",
902
+ description: "Render bounded visual previews as immutable image artifacts and report previewBasis. Markdown/DBK use source-render, imported document artifacts use reconstructed-import, and MP4/GIF sources use a native-extracted first-frame JPEG. Supports pagination and protocol progress/cancellation.",
903
+ inputSchema: {
904
+ type: "object",
905
+ properties: {
906
+ source: {
907
+ anyOf: [
908
+ {
909
+ type: "object",
910
+ properties: {
911
+ kind: {
912
+ type: "string",
913
+ const: "markdown"
914
+ },
915
+ markdown: {
916
+ type: "string",
917
+ maxLength: 20971520,
918
+ pattern: "^[^\\u0000\\u007f]*$"
919
+ },
920
+ name: {
921
+ anyOf: [
922
+ {
923
+ type: "string",
924
+ maxLength: 1024,
925
+ pattern: "^[^\\u0000\\u007f]*$"
926
+ },
927
+ {
928
+ type: "null"
929
+ }
930
+ ],
931
+ default: null
932
+ }
933
+ },
934
+ required: ["kind", "markdown"],
935
+ additionalProperties: false
936
+ },
937
+ {
938
+ type: "object",
939
+ properties: {
940
+ kind: {
941
+ type: "string",
942
+ const: "file"
943
+ },
944
+ rootId: {
945
+ anyOf: [
946
+ {
947
+ type: "string",
948
+ minLength: 1,
949
+ maxLength: 256,
950
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
951
+ },
952
+ {
953
+ type: "null"
954
+ }
955
+ ],
956
+ default: null
957
+ },
958
+ path: {
959
+ type: "string",
960
+ minLength: 1,
961
+ maxLength: 4096,
962
+ pattern: "^(?!\\/)(?![A-Za-z]:)(?!.*(?:^|\\/)(?:\\.{1,2})(?:\\/|$))(?!.*\\/\\/)(?!.*[\\\\\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"
963
+ },
964
+ format: {
965
+ anyOf: [
966
+ {
967
+ type: "string",
968
+ minLength: 1,
969
+ maxLength: 64,
970
+ pattern: "^[a-z0-9][a-z0-9.+_-]*$"
971
+ },
972
+ {
973
+ type: "null"
974
+ }
975
+ ],
976
+ default: null
977
+ }
978
+ },
979
+ required: ["kind", "path"],
980
+ additionalProperties: false
981
+ },
982
+ {
983
+ type: "object",
984
+ properties: {
985
+ kind: {
986
+ type: "string",
987
+ const: "artifact"
988
+ },
989
+ uri: {
990
+ type: "string",
991
+ maxLength: 278,
992
+ pattern: "^docblocks:\\/\\/artifacts\\/[A-Za-z0-9][A-Za-z0-9._:-]*$"
993
+ }
994
+ },
995
+ required: ["kind", "uri"],
996
+ additionalProperties: false
997
+ },
998
+ {
999
+ type: "object",
1000
+ properties: {
1001
+ kind: {
1002
+ type: "string",
1003
+ const: "bundle"
1004
+ },
1005
+ markdown: {
1006
+ type: "string",
1007
+ maxLength: 20971520,
1008
+ pattern: "^[^\\u0000\\u007f]*$"
1009
+ },
1010
+ assets: {
1011
+ type: "array",
1012
+ items: {
1013
+ type: "object",
1014
+ properties: {
1015
+ path: {
1016
+ $ref: "#/properties/source/anyOf/1/properties/path"
1017
+ },
1018
+ source: {
1019
+ anyOf: [
1020
+ {
1021
+ type: "object",
1022
+ properties: {
1023
+ kind: {
1024
+ type: "string",
1025
+ const: "file"
1026
+ },
1027
+ rootId: {
1028
+ $ref: "#/properties/source/anyOf/1/properties/rootId/anyOf/0"
1029
+ },
1030
+ path: {
1031
+ $ref: "#/properties/source/anyOf/1/properties/path"
1032
+ }
1033
+ },
1034
+ required: ["kind", "rootId", "path"],
1035
+ additionalProperties: false
1036
+ },
1037
+ {
1038
+ type: "object",
1039
+ properties: {
1040
+ kind: {
1041
+ type: "string",
1042
+ const: "artifact"
1043
+ },
1044
+ uri: {
1045
+ $ref: "#/properties/source/anyOf/2/properties/uri"
1046
+ }
1047
+ },
1048
+ required: ["kind", "uri"],
1049
+ additionalProperties: false
1050
+ }
1051
+ ]
1052
+ },
1053
+ mimeType: {
1054
+ anyOf: [
1055
+ {
1056
+ type: "string",
1057
+ minLength: 3,
1058
+ maxLength: 256,
1059
+ pattern: "^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$"
1060
+ },
1061
+ {
1062
+ type: "null"
1063
+ }
1064
+ ]
1065
+ },
1066
+ altText: {
1067
+ anyOf: [
1068
+ {
1069
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1070
+ },
1071
+ {
1072
+ type: "null"
1073
+ }
1074
+ ]
1075
+ },
1076
+ credit: {
1077
+ anyOf: [
1078
+ {
1079
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1080
+ },
1081
+ {
1082
+ type: "null"
1083
+ }
1084
+ ]
1085
+ },
1086
+ license: {
1087
+ anyOf: [
1088
+ {
1089
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1090
+ },
1091
+ {
1092
+ type: "null"
1093
+ }
1094
+ ]
1095
+ }
1096
+ },
1097
+ required: ["path", "source", "mimeType", "altText", "credit", "license"],
1098
+ additionalProperties: false
1099
+ },
1100
+ maxItems: 256
1101
+ },
1102
+ name: {
1103
+ anyOf: [
1104
+ {
1105
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1106
+ },
1107
+ {
1108
+ type: "null"
1109
+ }
1110
+ ],
1111
+ default: null
1112
+ }
1113
+ },
1114
+ required: ["kind", "markdown", "assets"],
1115
+ additionalProperties: false
1116
+ }
1117
+ ]
1118
+ },
1119
+ startIndex: {
1120
+ type: "integer",
1121
+ minimum: 0,
1122
+ maximum: 1e5
1123
+ },
1124
+ maxItems: {
1125
+ type: "integer",
1126
+ minimum: 1,
1127
+ maximum: 20
1128
+ },
1129
+ width: {
1130
+ type: "integer",
1131
+ minimum: 160,
1132
+ maximum: 1920
1133
+ },
1134
+ height: {
1135
+ type: "integer",
1136
+ minimum: 90,
1137
+ maximum: 1920
1138
+ }
1139
+ },
1140
+ required: ["source"],
1141
+ additionalProperties: false,
1142
+ $schema: "http://json-schema.org/draft-07/schema#"
1143
+ },
1144
+ annotations: {
1145
+ readOnlyHint: false,
1146
+ destructiveHint: false,
1147
+ idempotentHint: false,
1148
+ openWorldHint: false
1149
+ }
1150
+ },
1151
+ {
1152
+ name: "inspect_document",
1153
+ description: "Inspect bounded semantic structure, block provenance, assets, metadata, theme, and diagnostics when the user asks for document analysis. Inspection is never required before conversion.",
1154
+ inputSchema: {
1155
+ type: "object",
1156
+ properties: {
1157
+ source: {
1158
+ anyOf: [
1159
+ {
1160
+ type: "object",
1161
+ properties: {
1162
+ kind: {
1163
+ type: "string",
1164
+ const: "markdown"
1165
+ },
1166
+ markdown: {
1167
+ type: "string",
1168
+ maxLength: 20971520,
1169
+ pattern: "^[^\\u0000\\u007f]*$"
1170
+ },
1171
+ name: {
1172
+ anyOf: [
1173
+ {
1174
+ type: "string",
1175
+ maxLength: 1024,
1176
+ pattern: "^[^\\u0000\\u007f]*$"
1177
+ },
1178
+ {
1179
+ type: "null"
1180
+ }
1181
+ ],
1182
+ default: null
1183
+ }
1184
+ },
1185
+ required: ["kind", "markdown"],
1186
+ additionalProperties: false
1187
+ },
1188
+ {
1189
+ type: "object",
1190
+ properties: {
1191
+ kind: {
1192
+ type: "string",
1193
+ const: "file"
1194
+ },
1195
+ rootId: {
1196
+ anyOf: [
1197
+ {
1198
+ type: "string",
1199
+ minLength: 1,
1200
+ maxLength: 256,
1201
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
1202
+ },
1203
+ {
1204
+ type: "null"
1205
+ }
1206
+ ],
1207
+ default: null
1208
+ },
1209
+ path: {
1210
+ type: "string",
1211
+ minLength: 1,
1212
+ maxLength: 4096,
1213
+ pattern: "^(?!\\/)(?![A-Za-z]:)(?!.*(?:^|\\/)(?:\\.{1,2})(?:\\/|$))(?!.*\\/\\/)(?!.*[\\\\\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"
1214
+ },
1215
+ format: {
1216
+ anyOf: [
1217
+ {
1218
+ type: "string",
1219
+ minLength: 1,
1220
+ maxLength: 64,
1221
+ pattern: "^[a-z0-9][a-z0-9.+_-]*$"
1222
+ },
1223
+ {
1224
+ type: "null"
1225
+ }
1226
+ ],
1227
+ default: null
1228
+ }
1229
+ },
1230
+ required: ["kind", "path"],
1231
+ additionalProperties: false
1232
+ },
1233
+ {
1234
+ type: "object",
1235
+ properties: {
1236
+ kind: {
1237
+ type: "string",
1238
+ const: "artifact"
1239
+ },
1240
+ uri: {
1241
+ type: "string",
1242
+ maxLength: 278,
1243
+ pattern: "^docblocks:\\/\\/artifacts\\/[A-Za-z0-9][A-Za-z0-9._:-]*$"
1244
+ }
1245
+ },
1246
+ required: ["kind", "uri"],
1247
+ additionalProperties: false
1248
+ },
1249
+ {
1250
+ type: "object",
1251
+ properties: {
1252
+ kind: {
1253
+ type: "string",
1254
+ const: "bundle"
1255
+ },
1256
+ markdown: {
1257
+ type: "string",
1258
+ maxLength: 20971520,
1259
+ pattern: "^[^\\u0000\\u007f]*$"
1260
+ },
1261
+ assets: {
1262
+ type: "array",
1263
+ items: {
1264
+ type: "object",
1265
+ properties: {
1266
+ path: {
1267
+ $ref: "#/properties/source/anyOf/1/properties/path"
1268
+ },
1269
+ source: {
1270
+ anyOf: [
1271
+ {
1272
+ type: "object",
1273
+ properties: {
1274
+ kind: {
1275
+ type: "string",
1276
+ const: "file"
1277
+ },
1278
+ rootId: {
1279
+ $ref: "#/properties/source/anyOf/1/properties/rootId/anyOf/0"
1280
+ },
1281
+ path: {
1282
+ $ref: "#/properties/source/anyOf/1/properties/path"
1283
+ }
1284
+ },
1285
+ required: ["kind", "rootId", "path"],
1286
+ additionalProperties: false
1287
+ },
1288
+ {
1289
+ type: "object",
1290
+ properties: {
1291
+ kind: {
1292
+ type: "string",
1293
+ const: "artifact"
1294
+ },
1295
+ uri: {
1296
+ $ref: "#/properties/source/anyOf/2/properties/uri"
1297
+ }
1298
+ },
1299
+ required: ["kind", "uri"],
1300
+ additionalProperties: false
1301
+ }
1302
+ ]
1303
+ },
1304
+ mimeType: {
1305
+ anyOf: [
1306
+ {
1307
+ type: "string",
1308
+ minLength: 3,
1309
+ maxLength: 256,
1310
+ pattern: "^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$"
1311
+ },
1312
+ {
1313
+ type: "null"
1314
+ }
1315
+ ]
1316
+ },
1317
+ altText: {
1318
+ anyOf: [
1319
+ {
1320
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1321
+ },
1322
+ {
1323
+ type: "null"
1324
+ }
1325
+ ]
1326
+ },
1327
+ credit: {
1328
+ anyOf: [
1329
+ {
1330
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1331
+ },
1332
+ {
1333
+ type: "null"
1334
+ }
1335
+ ]
1336
+ },
1337
+ license: {
1338
+ anyOf: [
1339
+ {
1340
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1341
+ },
1342
+ {
1343
+ type: "null"
1344
+ }
1345
+ ]
1346
+ }
1347
+ },
1348
+ required: ["path", "source", "mimeType", "altText", "credit", "license"],
1349
+ additionalProperties: false
1350
+ },
1351
+ maxItems: 256
1352
+ },
1353
+ name: {
1354
+ anyOf: [
1355
+ {
1356
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1357
+ },
1358
+ {
1359
+ type: "null"
1360
+ }
1361
+ ],
1362
+ default: null
1363
+ }
1364
+ },
1365
+ required: ["kind", "markdown", "assets"],
1366
+ additionalProperties: false
1367
+ }
1368
+ ]
1369
+ },
1370
+ maxBlocks: {
1371
+ type: "integer",
1372
+ minimum: 1,
1373
+ maximum: 2e3
1374
+ },
1375
+ cursor: {
1376
+ anyOf: [
1377
+ {
1378
+ type: "string",
1379
+ maxLength: 256
1380
+ },
1381
+ {
1382
+ type: "null"
1383
+ }
1384
+ ]
1385
+ }
1386
+ },
1387
+ required: ["source"],
1388
+ additionalProperties: false,
1389
+ $schema: "http://json-schema.org/draft-07/schema#"
1390
+ },
1391
+ annotations: {
1392
+ readOnlyHint: true,
1393
+ destructiveHint: false,
1394
+ idempotentHint: true,
1395
+ openWorldHint: false
1396
+ }
1397
+ },
1398
+ {
1399
+ name: "list_themes",
1400
+ description: "List the linked Squisq built-in visual themes.",
1401
+ inputSchema: {
1402
+ type: "object",
1403
+ properties: {},
1404
+ additionalProperties: false,
1405
+ $schema: "http://json-schema.org/draft-07/schema#"
1406
+ },
1407
+ annotations: {
1408
+ readOnlyHint: true,
1409
+ destructiveHint: false,
1410
+ idempotentHint: true,
1411
+ openWorldHint: false
1412
+ }
1413
+ },
1414
+ {
1415
+ name: "get_authoring_context",
1416
+ description: "Optionally discover target capabilities, safe defaults, semantically described themes and Squisq Summarize styles, and exact starter annotation examples. Use these descriptions to choose for the user rather than presenting raw ids. Plain Markdown can be converted without calling this tool.",
1417
+ inputSchema: {
1418
+ type: "object",
1419
+ properties: {
1420
+ targetFormat: {
1421
+ type: "string",
1422
+ minLength: 1,
1423
+ maxLength: 64,
1424
+ pattern: "^[A-Za-z0-9][A-Za-z0-9.+_-]*$"
1425
+ },
1426
+ goal: {
1427
+ type: "string",
1428
+ enum: ["content-first", "visual-polish"]
1429
+ },
1430
+ source: {
1431
+ anyOf: [
1432
+ {
1433
+ type: "object",
1434
+ properties: {
1435
+ kind: {
1436
+ type: "string",
1437
+ const: "markdown"
1438
+ },
1439
+ markdown: {
1440
+ type: "string",
1441
+ maxLength: 20971520,
1442
+ pattern: "^[^\\u0000\\u007f]*$"
1443
+ },
1444
+ name: {
1445
+ anyOf: [
1446
+ {
1447
+ type: "string",
1448
+ maxLength: 1024,
1449
+ pattern: "^[^\\u0000\\u007f]*$"
1450
+ },
1451
+ {
1452
+ type: "null"
1453
+ }
1454
+ ],
1455
+ default: null
1456
+ }
1457
+ },
1458
+ required: ["kind", "markdown"],
1459
+ additionalProperties: false
1460
+ },
1461
+ {
1462
+ type: "object",
1463
+ properties: {
1464
+ kind: {
1465
+ type: "string",
1466
+ const: "file"
1467
+ },
1468
+ rootId: {
1469
+ anyOf: [
1470
+ {
1471
+ type: "string",
1472
+ minLength: 1,
1473
+ maxLength: 256,
1474
+ pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
1475
+ },
1476
+ {
1477
+ type: "null"
1478
+ }
1479
+ ],
1480
+ default: null
1481
+ },
1482
+ path: {
1483
+ type: "string",
1484
+ minLength: 1,
1485
+ maxLength: 4096,
1486
+ pattern: "^(?!\\/)(?![A-Za-z]:)(?!.*(?:^|\\/)(?:\\.{1,2})(?:\\/|$))(?!.*\\/\\/)(?!.*[\\\\\\u0000-\\u001f\\u007f])(?!.*\\/$).+$"
1487
+ },
1488
+ format: {
1489
+ anyOf: [
1490
+ {
1491
+ type: "string",
1492
+ minLength: 1,
1493
+ maxLength: 64,
1494
+ pattern: "^[a-z0-9][a-z0-9.+_-]*$"
1495
+ },
1496
+ {
1497
+ type: "null"
1498
+ }
1499
+ ],
1500
+ default: null
1501
+ }
1502
+ },
1503
+ required: ["kind", "path"],
1504
+ additionalProperties: false
1505
+ },
1506
+ {
1507
+ type: "object",
1508
+ properties: {
1509
+ kind: {
1510
+ type: "string",
1511
+ const: "artifact"
1512
+ },
1513
+ uri: {
1514
+ type: "string",
1515
+ maxLength: 278,
1516
+ pattern: "^docblocks:\\/\\/artifacts\\/[A-Za-z0-9][A-Za-z0-9._:-]*$"
1517
+ }
1518
+ },
1519
+ required: ["kind", "uri"],
1520
+ additionalProperties: false
1521
+ },
1522
+ {
1523
+ type: "object",
1524
+ properties: {
1525
+ kind: {
1526
+ type: "string",
1527
+ const: "bundle"
1528
+ },
1529
+ markdown: {
1530
+ type: "string",
1531
+ maxLength: 20971520,
1532
+ pattern: "^[^\\u0000\\u007f]*$"
1533
+ },
1534
+ assets: {
1535
+ type: "array",
1536
+ items: {
1537
+ type: "object",
1538
+ properties: {
1539
+ path: {
1540
+ $ref: "#/properties/source/anyOf/1/properties/path"
1541
+ },
1542
+ source: {
1543
+ anyOf: [
1544
+ {
1545
+ type: "object",
1546
+ properties: {
1547
+ kind: {
1548
+ type: "string",
1549
+ const: "file"
1550
+ },
1551
+ rootId: {
1552
+ $ref: "#/properties/source/anyOf/1/properties/rootId/anyOf/0"
1553
+ },
1554
+ path: {
1555
+ $ref: "#/properties/source/anyOf/1/properties/path"
1556
+ }
1557
+ },
1558
+ required: ["kind", "rootId", "path"],
1559
+ additionalProperties: false
1560
+ },
1561
+ {
1562
+ type: "object",
1563
+ properties: {
1564
+ kind: {
1565
+ type: "string",
1566
+ const: "artifact"
1567
+ },
1568
+ uri: {
1569
+ $ref: "#/properties/source/anyOf/2/properties/uri"
1570
+ }
1571
+ },
1572
+ required: ["kind", "uri"],
1573
+ additionalProperties: false
1574
+ }
1575
+ ]
1576
+ },
1577
+ mimeType: {
1578
+ anyOf: [
1579
+ {
1580
+ type: "string",
1581
+ minLength: 3,
1582
+ maxLength: 256,
1583
+ pattern: "^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$"
1584
+ },
1585
+ {
1586
+ type: "null"
1587
+ }
1588
+ ]
1589
+ },
1590
+ altText: {
1591
+ anyOf: [
1592
+ {
1593
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1594
+ },
1595
+ {
1596
+ type: "null"
1597
+ }
1598
+ ]
1599
+ },
1600
+ credit: {
1601
+ anyOf: [
1602
+ {
1603
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1604
+ },
1605
+ {
1606
+ type: "null"
1607
+ }
1608
+ ]
1609
+ },
1610
+ license: {
1611
+ anyOf: [
1612
+ {
1613
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1614
+ },
1615
+ {
1616
+ type: "null"
1617
+ }
1618
+ ]
1619
+ }
1620
+ },
1621
+ required: ["path", "source", "mimeType", "altText", "credit", "license"],
1622
+ additionalProperties: false
1623
+ },
1624
+ maxItems: 256
1625
+ },
1626
+ name: {
1627
+ anyOf: [
1628
+ {
1629
+ $ref: "#/properties/source/anyOf/0/properties/name/anyOf/0"
1630
+ },
1631
+ {
1632
+ type: "null"
1633
+ }
1634
+ ],
1635
+ default: null
1636
+ }
1637
+ },
1638
+ required: ["kind", "markdown", "assets"],
1639
+ additionalProperties: false
1640
+ }
1641
+ ]
1642
+ },
1643
+ maxBlocks: {
1644
+ type: "integer",
1645
+ minimum: 1,
1646
+ maximum: 100
1647
+ }
1648
+ },
1649
+ additionalProperties: false,
1650
+ $schema: "http://json-schema.org/draft-07/schema#"
1651
+ },
1652
+ annotations: {
1653
+ readOnlyHint: true,
1654
+ destructiveHint: false,
1655
+ idempotentHint: true,
1656
+ openWorldHint: false
1657
+ }
1658
+ }
1659
+ ]
1660
+ };
1661
+
1662
+ // src/harness/paths.ts
1663
+ import { isAbsolute, join, relative, resolve, sep } from "path";
1664
+ function relativeInside(root, child) {
1665
+ const rel = relative(root, child);
1666
+ if (rel === "") return "";
1667
+ if (rel.startsWith("..") || isAbsolute(rel)) return null;
1668
+ return rel.split(sep).join("/");
1669
+ }
1670
+ function absoluteFromApp(binding, path) {
1671
+ if (isAbsolute(path)) return resolve(path);
1672
+ const base = binding.folder ?? binding.info?.project?.workingDir;
1673
+ return base ? resolve(base, path) : resolve(path);
1674
+ }
1675
+ function rootedPath(binding, path) {
1676
+ const abs = absoluteFromApp(binding, path);
1677
+ const workingDir = binding.info?.project?.workingDir;
1678
+ if (workingDir) {
1679
+ const rel = relativeInside(workingDir, abs);
1680
+ if (rel !== null && rel !== "") return { root: "workspace", rel, abs };
1681
+ }
1682
+ const libraryDir = binding.info?.libraryDir;
1683
+ if (libraryDir) {
1684
+ const rel = relativeInside(libraryDir, abs);
1685
+ if (rel !== null && rel !== "") return { root: "library", rel, abs };
1686
+ }
1687
+ const artifactsDir = binding.info?.artifactsDir;
1688
+ if (artifactsDir) {
1689
+ const rel = relativeInside(artifactsDir, abs);
1690
+ if (rel !== null && rel !== "") return { root: "artifacts", rel, abs };
1691
+ }
1692
+ return null;
1693
+ }
1694
+ function whereFilesMayBe(binding) {
1695
+ const places = [];
1696
+ const project = binding.info?.project;
1697
+ if (project?.workingDir)
1698
+ places.push(`the folder Gezel knows as "${project.name}" (${project.workingDir})`);
1699
+ if (binding.info?.libraryDir) places.push(`the shared library (${binding.info.libraryDir})`);
1700
+ return places.length > 0 ? places.join(" or ") : "the shared library";
1701
+ }
1702
+ function absoluteForHit(binding, hit) {
1703
+ if (!hit.path) return null;
1704
+ const project = binding.info?.project;
1705
+ const ownProject = !hit.projectId || hit.projectId === project?.id;
1706
+ if (hit.retrievalSource === "shared" && binding.info?.libraryDir) {
1707
+ return join(binding.info.libraryDir, hit.path);
1708
+ }
1709
+ if (!ownProject) return null;
1710
+ if ((hit.retrievalSource === "artifacts" || hit.source === "artifacts") && binding.info?.artifactsDir) {
1711
+ return join(binding.info.artifactsDir, hit.path);
1712
+ }
1713
+ if (project?.workingDir && (hit.retrievalSource === "workspace" || hit.source === "workspace")) {
1714
+ return join(project.workingDir, hit.path);
1715
+ }
1716
+ return null;
1717
+ }
1718
+
1719
+ // src/harness/session.ts
1720
+ import { AsyncLocalStorage } from "async_hooks";
1721
+ import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2 } from "path";
1722
+ import {
1723
+ HARNESS_CONNECT_ERRORS,
1724
+ HarnessConnectResponseSchema
1725
+ } from "@bendyline/gezel";
1726
+ import {
1727
+ DaemonNotRunningError,
1728
+ LiveDaemonUnhealthyError,
1729
+ connectToLocalGezel,
1730
+ judgeDaemonHealth
1731
+ } from "@bendyline/gezel-client/node";
1732
+ var GEZEL_NOT_RUNNING = "Gezel isn't running. Open the Gezel app (or run `gezel start`), then try again.";
1733
+ var GEZEL_TOO_OLD = "This version of Gezel can't share its tools with other apps yet. Update Gezel, then try again.";
1734
+ var HarnessUnavailableError = class extends Error {
1735
+ constructor(message) {
1736
+ super(message);
1737
+ this.name = "HarnessUnavailableError";
1738
+ }
1739
+ };
1740
+ function boundProjectId(binding) {
1741
+ return binding.info?.project?.id ?? null;
1742
+ }
1743
+ function isSameOrInside(child, parent) {
1744
+ const rel = relative2(parent, child);
1745
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
1746
+ }
1747
+ var HarnessSession = class {
1748
+ client;
1749
+ opts;
1750
+ local = null;
1751
+ connecting = null;
1752
+ bindings = /* @__PURE__ */ new Map();
1753
+ roots;
1754
+ rootsProvider = null;
1755
+ current = new AsyncLocalStorage();
1756
+ closers = [];
1757
+ constructor(opts) {
1758
+ this.opts = opts;
1759
+ this.client = opts.client;
1760
+ }
1761
+ /** How the session asks the MCP client for its workspace folders. */
1762
+ setRootsProvider(provider) {
1763
+ this.rootsProvider = provider;
1764
+ }
1765
+ /** The client said its folders changed. */
1766
+ invalidateRoots() {
1767
+ this.roots = void 0;
1768
+ }
1769
+ /** The Gezel client, connected to the running service. */
1770
+ async api() {
1771
+ return (await this.connection()).client;
1772
+ }
1773
+ /**
1774
+ * The binding for a tool call. `pathHint` (an absolute path the call names)
1775
+ * picks among several workspace folders.
1776
+ */
1777
+ async bind(pathHint) {
1778
+ const target = await this.target(pathHint);
1779
+ let binding = this.bindings.get(target.key);
1780
+ if (!binding) {
1781
+ binding = target;
1782
+ this.bindings.set(target.key, binding);
1783
+ }
1784
+ const local = await this.connection();
1785
+ const launch = local.launch();
1786
+ if (binding.launchKey !== launch.key || !binding.token) await this.exchange(launch, binding);
1787
+ return binding;
1788
+ }
1789
+ /** Run `fn` with every Gezel request carrying `binding`'s token. */
1790
+ run(binding, fn) {
1791
+ return this.current.run(binding, async () => fn(await this.api()));
1792
+ }
1793
+ /** Run `fn` when the app disconnects: processes a tool started for it. */
1794
+ onClose(fn) {
1795
+ this.closers.push(fn);
1796
+ }
1797
+ async close() {
1798
+ await Promise.all(this.closers.map((fn) => fn().catch(() => {
1799
+ })));
1800
+ await this.local?.close().catch(() => {
1801
+ });
1802
+ this.local = null;
1803
+ }
1804
+ async target(pathHint) {
1805
+ const { client } = this.opts;
1806
+ if (this.opts.projectId) {
1807
+ return {
1808
+ key: `project:${this.opts.projectId}`,
1809
+ request: { client, projectId: this.opts.projectId }
1810
+ };
1811
+ }
1812
+ if (client === "claude-desktop" && !this.opts.folder) {
1813
+ return { key: "none", request: { client } };
1814
+ }
1815
+ const folders = this.opts.folder ? [resolve2(this.opts.folder)] : await this.workspaceFolders();
1816
+ const hint = pathHint && isAbsolute2(pathHint) ? pathHint : void 0;
1817
+ const inside = hint ? folders.filter((f) => isSameOrInside(hint, f)).sort((a, b) => b.length - a.length)[0] : void 0;
1818
+ const folder = inside ?? folders[0];
1819
+ if (!folder) return { key: "none", request: { client } };
1820
+ return { key: `folder:${folder}`, request: { client, folder }, folder };
1821
+ }
1822
+ async workspaceFolders() {
1823
+ if (this.roots === void 0) {
1824
+ this.roots = this.rootsProvider ? await this.rootsProvider().catch(() => null) : null;
1825
+ }
1826
+ if (this.roots && this.roots.length > 0) return this.roots;
1827
+ return [resolve2(this.opts.cwd ?? process.cwd())];
1828
+ }
1829
+ connection() {
1830
+ if (this.local) return Promise.resolve(this.local);
1831
+ this.connecting ??= this.open().finally(() => {
1832
+ this.connecting = null;
1833
+ });
1834
+ return this.connecting;
1835
+ }
1836
+ async open() {
1837
+ const connect = this.opts.connect ?? connectToLocalGezel;
1838
+ let local;
1839
+ try {
1840
+ local = await connect({
1841
+ ...this.opts.home ? { home: this.opts.home } : {},
1842
+ credential: {
1843
+ token: (launch) => this.tokenFor(launch),
1844
+ rejected: async () => {
1845
+ const binding = this.current.getStore();
1846
+ if (!binding) return false;
1847
+ binding.token = void 0;
1848
+ return true;
1849
+ }
1850
+ }
1851
+ });
1852
+ } catch (err) {
1853
+ if (err instanceof DaemonNotRunningError || err instanceof LiveDaemonUnhealthyError) {
1854
+ throw new HarnessUnavailableError(GEZEL_NOT_RUNNING);
1855
+ }
1856
+ throw err;
1857
+ }
1858
+ const health = await local.client.health().catch(() => null);
1859
+ const verdict = health ? judgeDaemonHealth(health, { client: "gezel-mcp" }) : null;
1860
+ if (verdict && !verdict.compatible) {
1861
+ await local.close().catch(() => {
1862
+ });
1863
+ throw new HarnessUnavailableError(`${verdict.reason} ${GEZEL_TOO_OLD}`);
1864
+ }
1865
+ this.local = local;
1866
+ return local;
1867
+ }
1868
+ async tokenFor(launch) {
1869
+ const binding = this.current.getStore();
1870
+ if (!binding) return null;
1871
+ if (binding.launchKey !== launch.key || !binding.token) await this.exchange(launch, binding);
1872
+ if (!binding.token) throw new HarnessUnavailableError(GEZEL_NOT_RUNNING);
1873
+ return binding.token;
1874
+ }
1875
+ async exchange(launch, binding) {
1876
+ let res;
1877
+ try {
1878
+ res = await launch.ownerFetch("/v1/apps/harness-connect", {
1879
+ method: "POST",
1880
+ headers: { "Content-Type": "application/json" },
1881
+ body: JSON.stringify(binding.request)
1882
+ });
1883
+ } catch {
1884
+ throw new HarnessUnavailableError(GEZEL_NOT_RUNNING);
1885
+ }
1886
+ const body = await res.json().catch(() => null);
1887
+ if (res.status === 404) throw new HarnessUnavailableError(GEZEL_TOO_OLD);
1888
+ if (!res.ok) {
1889
+ const hint = typeof body?.hint === "string" ? body.hint : null;
1890
+ const code = typeof body?.error === "string" ? body.error : "";
1891
+ if (HARNESS_CONNECT_ERRORS.includes(code) && hint) {
1892
+ throw new HarnessUnavailableError(hint);
1893
+ }
1894
+ throw new HarnessUnavailableError(
1895
+ hint ?? `Gezel could not connect this app (HTTP ${res.status}).`
1896
+ );
1897
+ }
1898
+ const info = HarnessConnectResponseSchema.parse(body);
1899
+ binding.info = info;
1900
+ binding.token = info.token;
1901
+ binding.launchKey = launch.key;
1902
+ }
1903
+ };
1904
+
1905
+ // src/harness/tools.ts
1906
+ import { readFileSync, statSync } from "fs";
1907
+ import { readFile, stat } from "fs/promises";
1908
+ import { extname, isAbsolute as isAbsolute3, join as join2, sep as sep2 } from "path";
1909
+ import {
1910
+ HARNESS_TOOL_DESCRIPTIONS,
1911
+ IMAGE_ASPECT_RATIOS,
1912
+ IMAGE_QUALITIES,
1913
+ isHarnessHiddenCatalog,
1914
+ parseKnowledgeUri
1915
+ } from "@bendyline/gezel";
1916
+ import { GezelApiError, apiErrorMessage } from "@bendyline/gezel-client/node";
1917
+ import { MEMORY_KINDS } from "@bendyline/gezel/runtime";
1918
+ import { z as z2 } from "zod";
1919
+ var UNBOUND_PROJECT = "default";
1920
+ var MAX_IMAGE_BYTES = 20 * 1024 * 1024;
1921
+ var SEARCH_SCOPES = ["folder", "library", "memories", "knowledge"];
1922
+ var DEFAULT_SCOPES = ["folder", "library", "memories"];
1923
+ var MAX_SIDE_HITS = 3;
1924
+ var MAX_DOC_HITS = 3;
1925
+ var DOC_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx", ".markdown", ".txt", ".rst", ".adoc"]);
1926
+ var DOC_BASENAMES = /* @__PURE__ */ new Set(["package.json", "package-lock.json", "license", "changelog"]);
1927
+ function isDocPath(path) {
1928
+ const normalized = path.replaceAll("\\", "/").toLowerCase();
1929
+ const base = normalized.slice(normalized.lastIndexOf("/") + 1);
1930
+ const dot = base.lastIndexOf(".");
1931
+ const ext = dot >= 0 ? base.slice(dot) : "";
1932
+ return DOC_EXTENSIONS.has(ext) || DOC_BASENAMES.has(base) || DOC_BASENAMES.has(base.slice(0, dot >= 0 ? dot : void 0)) || normalized.startsWith("docs/") || normalized.includes("/docs/");
1933
+ }
1934
+ var FOLDER_SOURCES = /* @__PURE__ */ new Set(["workspace", "artifacts"]);
1935
+ var SCOPE_SOURCES = {
1936
+ folder: ["workspace", "artifacts"],
1937
+ library: ["shared"],
1938
+ memories: ["project-memory", "user-memory"],
1939
+ knowledge: ["knowledge"]
1940
+ };
1941
+ var IMAGE_MIME = {
1942
+ ".png": "image/png",
1943
+ ".jpg": "image/jpeg",
1944
+ ".jpeg": "image/jpeg",
1945
+ ".webp": "image/webp",
1946
+ ".gif": "image/gif",
1947
+ ".bmp": "image/bmp",
1948
+ ".heic": "image/heic"
1949
+ };
1950
+ function text(value) {
1951
+ return { content: [{ type: "text", text: value }] };
1952
+ }
1953
+ function failure(value) {
1954
+ return { content: [{ type: "text", text: value }], isError: true };
1955
+ }
1956
+ function gezelMessage(err) {
1957
+ if (err instanceof HarnessUnavailableError) return err.message;
1958
+ if (err instanceof GezelApiError && err.details && typeof err.details === "object") {
1959
+ const { hint } = err.details;
1960
+ if (typeof hint === "string" && hint.trim()) return hint;
1961
+ }
1962
+ return apiErrorMessage(err);
1963
+ }
1964
+ async function guarded(fn) {
1965
+ try {
1966
+ return await fn();
1967
+ } catch (err) {
1968
+ return failure(gezelMessage(err));
1969
+ }
1970
+ }
1971
+ function harnessSources(binding, scopes) {
1972
+ const bound = boundProjectId(binding) !== null;
1973
+ const memory = binding.info?.memory ?? "off";
1974
+ const wanted = (scopes && scopes.length > 0 ? scopes : DEFAULT_SCOPES).flatMap(
1975
+ (scope) => SCOPE_SOURCES[scope]
1976
+ );
1977
+ return [...new Set(wanted)].filter((source) => {
1978
+ if (!bound && (source === "workspace" || source === "artifacts" || source === "project-memory")) {
1979
+ return false;
1980
+ }
1981
+ if (memory === "off" && (source === "project-memory" || source === "user-memory")) return false;
1982
+ return true;
1983
+ });
1984
+ }
1985
+ function renderHit(binding, hit) {
1986
+ const lines = hit.line !== void 0 ? `:${hit.line}${hit.lineEnd && hit.lineEnd !== hit.line ? `-${hit.lineEnd}` : ""}` : "";
1987
+ const snippet = hit.snippet?.replace(/\s+/g, " ").trim().slice(0, 300) ?? "";
1988
+ if (hit.kind === "memory") {
1989
+ const when = hit.memory ? ` (${hit.memory.day}, ${hit.memory.kind})` : "";
1990
+ return `- memory${when}: ${snippet || hit.title}`;
1991
+ }
1992
+ if (hit.retrievalSource === "knowledge" || hit.uri?.startsWith("knowledge://")) {
1993
+ const where = hit.topicPath?.length ? ` [${hit.topicPath.join(" \u203A ")}]` : "";
1994
+ return `- ${hit.uri ?? hit.title} \u2014 ${hit.title}${where}${snippet ? `
1995
+ ${snippet}` : ""}`;
1996
+ }
1997
+ const abs = absoluteForHit(binding, hit);
1998
+ const label = abs ?? (hit.projectName ? `${hit.projectName}: ${hit.path ?? hit.title}` : hit.path ?? hit.title);
1999
+ const corpus = hit.retrievalSource === "shared" ? " [shared library]" : "";
2000
+ return `- ${label}${lines}${corpus}${snippet ? `
2001
+ ${snippet}` : ""}`;
2002
+ }
2003
+ function isFolderHit(hit) {
2004
+ if (hit.retrievalSource) return FOLDER_SOURCES.has(hit.retrievalSource);
2005
+ return hit.source !== void 0 && hit.kind !== "memory";
2006
+ }
2007
+ var OVERVIEW_PREFIX = "overview:";
2008
+ var PROJECT_OVERVIEW_AREA = "::project";
2009
+ var MAX_OVERVIEW_HITS = 2;
2010
+ function overviewArea(hit) {
2011
+ if (!hit.projectId) return null;
2012
+ const prefix = `${OVERVIEW_PREFIX}${hit.projectId}:`;
2013
+ return hit.id.startsWith(prefix) ? hit.id.slice(prefix.length) : null;
2014
+ }
2015
+ function renderOverview(binding, hit, area) {
2016
+ const project = binding.info?.project;
2017
+ const workingDir = hit.projectId === project?.id ? project?.workingDir : void 0;
2018
+ const where = area === PROJECT_OVERVIEW_AREA ? workingDir ?? hit.projectName ?? "this project" : workingDir ? `${join2(workingDir, area)}${sep2}` : `${area}/`;
2019
+ const summary = hit.snippet?.replace(/\s+/g, " ").trim().slice(0, 600) ?? "";
2020
+ return `- Overview of ${where} (Gezel's summary)${summary ? `
2021
+ ${summary}` : ""}`;
2022
+ }
2023
+ var MAX_LOCATE_BYTES = 2e6;
2024
+ var SHOWN_LINES = 2;
2025
+ var SHOWN_LINE_CHARS = 140;
2026
+ var readLinesSync = (path) => {
2027
+ try {
2028
+ if (statSync(path).size > MAX_LOCATE_BYTES) return null;
2029
+ return readFileSync(path, "utf8").split(/\r?\n/);
2030
+ } catch {
2031
+ return null;
2032
+ }
2033
+ };
2034
+ function queryWords(query) {
2035
+ const words = query.toLowerCase().match(/[a-z0-9_]{4,}/g) ?? [];
2036
+ return [...new Set(words.map((w) => w.replace(/(ies|es|s|ed|ing)$/, "")))].filter(
2037
+ (w) => w.length >= 3
2038
+ );
2039
+ }
2040
+ function locateSnippet(fileLines, snippet, from, to) {
2041
+ const lines = snippet.split(/\r?\n/);
2042
+ const lo = Math.max(0, from - 1);
2043
+ const hi = Math.min(fileLines.length, Math.max(to, from));
2044
+ for (let k = 0; k < Math.min(lines.length, 12); k++) {
2045
+ const probe = lines[k].trim();
2046
+ if (probe.length < 12) continue;
2047
+ for (let i = lo; i < hi; i++) {
2048
+ if (fileLines[i].includes(probe)) return { start: i - k + 1, lines };
2049
+ }
2050
+ }
2051
+ return null;
2052
+ }
2053
+ function shownLines(located, words) {
2054
+ const candidates = located.lines.map((text2, i) => ({ n: located.start + i, text: text2.trim() })).filter((l) => l.text.length > 0 && !/^[{}()[\];,]+$/.test(l.text) && !l.text.endsWith("\u2026"));
2055
+ const score = (text2) => words.filter((w) => text2.toLowerCase().includes(w)).length;
2056
+ const ranked = [...candidates].sort((a, b) => score(b.text) - score(a.text) || a.n - b.n);
2057
+ const pool = ranked.length > 0 && score(ranked[0].text) > 0 ? ranked : candidates;
2058
+ return pool.slice(0, SHOWN_LINES).sort((a, b) => a.n - b.n);
2059
+ }
2060
+ function renderFileHit(binding, group, words = [], readLines = readLinesSync) {
2061
+ const first = group[0];
2062
+ const abs = absoluteForHit(binding, first);
2063
+ const label = abs ?? (first.projectName ? `${first.projectName}: ${first.path ?? first.title}` : first.path ?? first.title);
2064
+ const fileLines = abs && group.some((h) => h.snippet && h.line !== void 0) ? readLines(abs) : null;
2065
+ const ranges = [];
2066
+ let shown = [];
2067
+ let inside = "";
2068
+ for (const h of group) {
2069
+ if (h.line === void 0) continue;
2070
+ const located = fileLines && h.snippet ? locateSnippet(fileLines, h.snippet, h.line, h.lineEnd ?? h.line) : null;
2071
+ if (!located) {
2072
+ ranges.push(h.lineEnd && h.lineEnd !== h.line ? `${h.line}-${h.lineEnd}` : `${h.line}`);
2073
+ continue;
2074
+ }
2075
+ const end = Math.min(located.start + located.lines.length - 1, fileLines.length);
2076
+ ranges.push(end > located.start ? `${located.start}-${end}` : `${located.start}`);
2077
+ if (h === first) {
2078
+ shown = shownLines(located, words);
2079
+ const span = (h.lineEnd ?? h.line) - h.line;
2080
+ const head = fileLines[h.line - 1]?.trim();
2081
+ if (head && span > located.lines.length && h.line < located.start) {
2082
+ inside = ` (inside \`${head.slice(0, 60)}\`, ${h.line}-${h.lineEnd})`;
2083
+ }
2084
+ }
2085
+ }
2086
+ const where = ranges.length ? `:${[...new Set(ranges)].slice(0, 4).join(", ")}` : "";
2087
+ if (shown.length > 0) {
2088
+ const body = shown.map((l) => ` ${l.n}| ${l.text.slice(0, SHOWN_LINE_CHARS)}`).join("\n");
2089
+ return `- ${label}${where}${inside}
2090
+ ${body}`;
2091
+ }
2092
+ const snippet = first.snippet?.replace(/\s+/g, " ").trim().slice(0, 280) ?? "";
2093
+ return `- ${label}${where}${snippet ? `
2094
+ ${snippet}` : ""}`;
2095
+ }
2096
+ function arrangeSearchResults(binding, results, opts) {
2097
+ const words = opts.query ? queryWords(opts.query) : [];
2098
+ const fileHit = (group) => renderFileHit(binding, group, words, opts.readLines ?? readLinesSync);
2099
+ const groups = /* @__PURE__ */ new Map();
2100
+ const side = [];
2101
+ const onlyMedia = results.every((hit) => !isFolderHit(hit) || hit.media !== void 0);
2102
+ let overviews = 0;
2103
+ for (const hit of results) {
2104
+ if (isHarnessHiddenCatalog(hit.catalogId) || isHarnessHiddenCatalog(hit.uri)) continue;
2105
+ if (!isFolderHit(hit)) {
2106
+ side.push(hit);
2107
+ continue;
2108
+ }
2109
+ if (hit.media && !onlyMedia) continue;
2110
+ if (overviewArea(hit) !== null && ++overviews > MAX_OVERVIEW_HITS) continue;
2111
+ const key = (hit.path ?? hit.id).replaceAll("\\", "/");
2112
+ const group = groups.get(key);
2113
+ if (group) group.push(hit);
2114
+ else groups.set(key, [hit]);
2115
+ }
2116
+ const all = [...groups.entries()];
2117
+ const code = all.filter(([path]) => !isDocPath(path));
2118
+ const docGroups = all.filter(([path]) => isDocPath(path));
2119
+ const folder = code.slice(0, opts.maxResults).map(([, group]) => {
2120
+ const area = overviewArea(group[0]);
2121
+ return area === null ? fileHit(group) : renderOverview(binding, group[0], area);
2122
+ });
2123
+ const docs = docGroups.slice(0, folder.length === 0 ? opts.maxResults : MAX_DOC_HITS).map(([, group]) => fileHit(group));
2124
+ const anyFolder = folder.length + docs.length > 0;
2125
+ const keptSide = side.filter((hit) => opts.sideByName || !anyFolder || hit.tier === "strong").slice(0, opts.sideByName || !anyFolder ? opts.maxResults : MAX_SIDE_HITS).map((hit) => renderHit(binding, hit));
2126
+ return { folder, docs, side: keptSide };
2127
+ }
2128
+ async function indexNote(session, binding) {
2129
+ const id = boundProjectId(binding);
2130
+ if (!id) return null;
2131
+ const status = await session.run(binding, (api) => api.getProjectIndexStatus(id)).catch(() => null);
2132
+ if (!status) return null;
2133
+ if (status.state === "indexing" || status.state === "never") {
2134
+ return "Gezel is still indexing this folder, so results may be incomplete. Use your own search meanwhile.";
2135
+ }
2136
+ if (status.state === "disabled") {
2137
+ return "Gezel does not index this folder (indexing is turned off for it), so only the library, memories and knowledge were searched.";
2138
+ }
2139
+ return null;
2140
+ }
2141
+ function registerHarnessTools(server, session) {
2142
+ server.registerTool(
2143
+ "search",
2144
+ {
2145
+ description: HARNESS_TOOL_DESCRIPTIONS.search,
2146
+ inputSchema: {
2147
+ query: z2.string().trim().min(1).max(400).describe("What to look for, in plain words."),
2148
+ scopes: z2.array(z2.enum(SEARCH_SCOPES)).optional().describe(
2149
+ "Which of folder, library, memories, knowledge to search. Default: folder, library and memories. Add knowledge for installed reference catalogs."
2150
+ ),
2151
+ catalogs: z2.array(z2.string().min(1)).max(64).optional().describe("Search only these knowledge catalogs (ids from gezel_status)."),
2152
+ pathPrefix: z2.string().min(1).optional().describe(
2153
+ "Only files under this folder: an absolute path, or one relative to this folder."
2154
+ ),
2155
+ maxResults: z2.number().int().positive().max(50).optional().describe("Default 10."),
2156
+ cursor: z2.number().int().min(0).max(1e4).optional().describe("From a previous truncated search.")
2157
+ },
2158
+ annotations: { readOnlyHint: true }
2159
+ },
2160
+ async (args) => guarded(async () => {
2161
+ const query = args.query;
2162
+ const binding = await session.bind(args.pathPrefix);
2163
+ const scopes = args.catalogs ? ["knowledge"] : args.scopes?.length ? args.scopes : DEFAULT_SCOPES;
2164
+ const sources = harnessSources(binding, scopes);
2165
+ if (sources.length === 0) {
2166
+ return failure(
2167
+ "Nothing to search: this app is not working in a Gezel project and memories are off. Ask for the library or knowledge instead."
2168
+ );
2169
+ }
2170
+ let pathPrefix;
2171
+ if (args.pathPrefix) {
2172
+ const workingDir = binding.info?.project?.workingDir;
2173
+ const rel = workingDir ? relativeInside(workingDir, absoluteFromApp(binding, args.pathPrefix)) : null;
2174
+ if (rel === null)
2175
+ return failure(`pathPrefix must be inside ${whereFilesMayBe(binding)}.`);
2176
+ if (rel) pathPrefix = rel.endsWith("/") ? rel : `${rel}/`;
2177
+ }
2178
+ const catalogs = args.catalogs?.filter((id) => !isHarnessHiddenCatalog(id));
2179
+ if (args.catalogs && catalogs?.length === 0) {
2180
+ return failure("Those knowledge catalogs are not available to other apps.");
2181
+ }
2182
+ const maxResults = args.maxResults ?? 10;
2183
+ const fetched = Math.min(100, maxResults * 3);
2184
+ const res = await session.run(
2185
+ binding,
2186
+ (api) => api.toolSearch(boundProjectId(binding) ?? UNBOUND_PROJECT, {
2187
+ query,
2188
+ includeShared: sources.includes("shared"),
2189
+ sources,
2190
+ maxResults: fetched,
2191
+ ...catalogs ? { catalogs } : {},
2192
+ ...pathPrefix ? { pathPrefix } : {},
2193
+ ...args.cursor ? { offset: args.cursor } : {}
2194
+ })
2195
+ );
2196
+ const { folder, docs, side } = arrangeSearchResults(binding, res.results, {
2197
+ maxResults,
2198
+ sideByName: Boolean(args.catalogs || args.scopes?.length),
2199
+ query
2200
+ });
2201
+ const lines = [...folder];
2202
+ if (docs.length > 0) {
2203
+ if (lines.length > 0) lines.push("", "Docs in this folder that discuss it:");
2204
+ lines.push(...docs);
2205
+ }
2206
+ if (side.length > 0) {
2207
+ if (lines.length > 0) lines.push("", "Also relevant, outside this folder:");
2208
+ lines.push(...side);
2209
+ }
2210
+ const notes = [];
2211
+ if (folder.length + docs.length + side.length === 0) {
2212
+ const note = await indexNote(session, binding);
2213
+ notes.push(note ?? "No results.");
2214
+ }
2215
+ if (res.sourcesIncomplete)
2216
+ notes.push("Some sources did not answer in time; results may be partial.");
2217
+ if (res.truncated && res.results.length >= fetched) {
2218
+ notes.push(
2219
+ `More results exist: call again with cursor ${(args.cursor ?? 0) + res.results.length}.`
2220
+ );
2221
+ }
2222
+ return text([...lines, ...notes].join("\n"));
2223
+ })
2224
+ );
2225
+ server.registerTool(
2226
+ "read_doc_as_markdown",
2227
+ {
2228
+ description: HARNESS_TOOL_DESCRIPTIONS.read_doc_as_markdown,
2229
+ inputSchema: {
2230
+ path: z2.string().min(1).describe("The document: an absolute path, or one relative to this folder.")
2231
+ },
2232
+ annotations: { readOnlyHint: true }
2233
+ },
2234
+ async (args) => guarded(async () => {
2235
+ const binding = await session.bind(isAbsolute3(args.path) ? args.path : void 0);
2236
+ const where = rootedPath(binding, args.path);
2237
+ const id = boundProjectId(binding);
2238
+ if (where?.root === "workspace" && id) {
2239
+ const res = await session.run(
2240
+ binding,
2241
+ (api) => api.toolReadDocAsMarkdown(id, { path: where.rel })
2242
+ );
2243
+ if (!res.found) {
2244
+ return failure(
2245
+ `Gezel could not convert ${where.abs} (unsupported format, or the conversion failed).`
2246
+ );
2247
+ }
2248
+ return text(
2249
+ `${where.abs}${res.truncated ? " (truncated)" : ""}
2250
+ ---
2251
+ ${res.markdown ?? ""}`
2252
+ );
2253
+ }
2254
+ if (where?.root === "library") {
2255
+ const res = await session.run(
2256
+ binding,
2257
+ (api) => api.readDocument(where.rel, { as: "markdown" })
2258
+ );
2259
+ return text(`${where.abs}
2260
+ ---
2261
+ ${res.content}`);
2262
+ }
2263
+ return failure(
2264
+ `${absoluteFromApp(binding, args.path)} is outside ${whereFilesMayBe(binding)}.`
2265
+ );
2266
+ })
2267
+ );
2268
+ server.registerTool(
2269
+ "list_documents",
2270
+ {
2271
+ description: HARNESS_TOOL_DESCRIPTIONS.list_documents,
2272
+ inputSchema: {
2273
+ path: z2.string().min(1).optional().describe("A subfolder of the library to list.")
2274
+ },
2275
+ annotations: { readOnlyHint: true }
2276
+ },
2277
+ async (args) => guarded(async () => {
2278
+ const binding = await session.bind();
2279
+ const libraryDir = binding.info?.libraryDir;
2280
+ let sub;
2281
+ if (args.path) {
2282
+ const where = rootedPath(binding, args.path);
2283
+ sub = where?.root === "library" ? where.rel : args.path.replaceAll("\\", "/");
2284
+ }
2285
+ const res = await session.run(binding, (api) => api.listDocuments(sub));
2286
+ if (res.files.length === 0) return text("The shared library is empty here.");
2287
+ const lines = res.files.map((f) => {
2288
+ const shown = libraryDir ? join2(libraryDir, f.path) : f.path;
2289
+ return `- ${shown}${f.isDirectory ? "/" : ""}`;
2290
+ });
2291
+ return text(lines.join("\n"));
2292
+ })
2293
+ );
2294
+ server.registerTool(
2295
+ "read_document",
2296
+ {
2297
+ description: HARNESS_TOOL_DESCRIPTIONS.read_document,
2298
+ inputSchema: {
2299
+ path: z2.string().min(1).describe(
2300
+ "A library document (absolute, or relative to the library), or a knowledge:// address."
2301
+ )
2302
+ },
2303
+ annotations: { readOnlyHint: true }
2304
+ },
2305
+ async (args) => guarded(async () => {
2306
+ const binding = await session.bind();
2307
+ const knowledge = parseKnowledgeUri(args.path);
2308
+ if (knowledge && isHarnessHiddenCatalog(knowledge.catalogId)) {
2309
+ return failure(`${args.path} is not available to other apps.`);
2310
+ }
2311
+ if (knowledge?.fragment && "chunk" in knowledge.fragment) {
2312
+ const chunk = knowledge.fragment.chunk;
2313
+ const passage = await session.run(
2314
+ binding,
2315
+ (api) => api.readKnowledgePassage(knowledge.catalogId, knowledge.documentId, chunk)
2316
+ );
2317
+ const head = [
2318
+ `Source: ${passage.title} \u2014 ${args.path}`,
2319
+ ...passage.headingPath.length ? [`Section: ${passage.headingPath.join(" \u203A ")}`] : [],
2320
+ ...passage.sourceUrl ? [`Origin: ${passage.sourceUrl}`] : []
2321
+ ];
2322
+ return text(`${head.join("\n")}
2323
+
2324
+ ${passage.text}`);
2325
+ }
2326
+ if (knowledge) {
2327
+ const doc = await session.run(
2328
+ binding,
2329
+ (api) => api.readKnowledgeDocument(knowledge.catalogId, knowledge.documentId)
2330
+ );
2331
+ const head = [
2332
+ `Source: ${doc.title} \u2014 ${args.path.split("#")[0]}`,
2333
+ ...doc.sourceUrl ? [`Origin: ${doc.sourceUrl}`] : []
2334
+ ];
2335
+ return text(`${head.join("\n")}
2336
+
2337
+ ${doc.markdown}`);
2338
+ }
2339
+ const where = isAbsolute3(args.path) ? rootedPath(binding, args.path) : null;
2340
+ if (where && where.root !== "library") {
2341
+ return failure(
2342
+ `${where.abs} is not in the shared library. Use read_doc_as_markdown for files in this folder.`
2343
+ );
2344
+ }
2345
+ const rel = where?.rel ?? args.path.replaceAll("\\", "/");
2346
+ const res = await session.run(binding, (api) => api.readDocument(rel, { as: "markdown" }));
2347
+ return text(res.content);
2348
+ })
2349
+ );
2350
+ server.registerTool(
2351
+ "search_memory",
2352
+ {
2353
+ description: HARNESS_TOOL_DESCRIPTIONS.search_memory,
2354
+ inputSchema: {
2355
+ query: z2.string().min(1).max(400).describe("What to recall, in plain words."),
2356
+ maxResults: z2.number().int().positive().max(30).optional().describe("Default 10.")
2357
+ },
2358
+ annotations: { readOnlyHint: true }
2359
+ },
2360
+ async (args) => guarded(async () => {
2361
+ const binding = await session.bind();
2362
+ if (binding.info?.memory === "off") {
2363
+ return failure("Memory is turned off for other apps in Gezel (Settings \u2192 Integrations).");
2364
+ }
2365
+ const sources = harnessSources(binding, ["memories"]);
2366
+ const res = await session.run(
2367
+ binding,
2368
+ (api) => api.toolSearch(boundProjectId(binding) ?? UNBOUND_PROJECT, {
2369
+ query: args.query,
2370
+ includeShared: false,
2371
+ sources,
2372
+ maxResults: args.maxResults ?? 10
2373
+ })
2374
+ );
2375
+ if (res.results.length === 0) return text("No saved memories match.");
2376
+ return text(res.results.map((hit) => renderHit(binding, hit)).join("\n"));
2377
+ })
2378
+ );
2379
+ server.registerTool(
2380
+ "save_memory",
2381
+ {
2382
+ description: HARNESS_TOOL_DESCRIPTIONS.save_memory,
2383
+ inputSchema: {
2384
+ text: z2.string().min(3).max(2e3).describe("The fact, as one or two self-contained sentences."),
2385
+ kind: z2.enum(MEMORY_KINDS).optional().describe(
2386
+ "fact (default), decision, pref (a preference), status, correction, or example."
2387
+ )
2388
+ }
2389
+ },
2390
+ async (args) => guarded(async () => {
2391
+ const binding = await session.bind();
2392
+ if (binding.info?.memory !== "save") {
2393
+ return failure(
2394
+ "Saving memories is turned off for other apps in Gezel (Settings \u2192 Integrations)."
2395
+ );
2396
+ }
2397
+ const id = boundProjectId(binding);
2398
+ if (!id) {
2399
+ return failure(
2400
+ "This app isn't working in a Gezel project, so there is no project memory to save to."
2401
+ );
2402
+ }
2403
+ const res = await session.run(
2404
+ binding,
2405
+ (api) => api.saveMemory({ scope: "project", id, text: args.text, kind: args.kind ?? "fact" })
2406
+ );
2407
+ return text(res.status === "duplicate" ? "Gezel already had that memory." : "Saved.");
2408
+ })
2409
+ );
2410
+ server.registerTool(
2411
+ "describe_image",
2412
+ {
2413
+ description: HARNESS_TOOL_DESCRIPTIONS.describe_image,
2414
+ inputSchema: {
2415
+ path: z2.string().min(1).describe("The image: an absolute path, or one relative to this folder."),
2416
+ mode: z2.enum(["auto", "describe", "ocr", "ui", "extract"]).optional().describe(
2417
+ "auto (default), describe, ocr (text in the image), ui (a screenshot), extract (needs schema)."
2418
+ ),
2419
+ schema: z2.record(z2.string(), z2.unknown()).optional().describe("JSON Schema for extract mode.")
2420
+ },
2421
+ annotations: { readOnlyHint: true }
2422
+ },
2423
+ async (args) => guarded(async () => {
2424
+ const binding = await session.bind(isAbsolute3(args.path) ? args.path : void 0);
2425
+ const image = await readAllowedImage(binding, args.path);
2426
+ if ("error" in image) return failure(image.error);
2427
+ const res = await session.run(
2428
+ binding,
2429
+ (api) => api.describeImage(
2430
+ {
2431
+ data: image.data,
2432
+ mimeType: image.mimeType,
2433
+ mode: args.mode ?? "auto",
2434
+ ...args.schema ? { schema: args.schema } : {}
2435
+ },
2436
+ { projectId: boundProjectId(binding) ?? UNBOUND_PROJECT }
2437
+ )
2438
+ );
2439
+ const parts = [
2440
+ `${res.meta.format.toUpperCase()}${res.meta.width && res.meta.height ? ` ${res.meta.width}x${res.meta.height}` : ""}.`
2441
+ ];
2442
+ if (res.description) parts.push("", res.description);
2443
+ if (res.ocrText) parts.push("", "Text in the image:", res.ocrText);
2444
+ if (res.structured) parts.push("", JSON.stringify(res.structured.data, null, 2));
2445
+ if (res.status === "static-only") {
2446
+ parts.push(
2447
+ "",
2448
+ "No description: Gezel has no image reader installed (Settings \u2192 Image recognition)."
2449
+ );
2450
+ } else if (res.status === "failed") {
2451
+ parts.push(
2452
+ "",
2453
+ `Gezel could not read this image: ${res.failureReason ?? "unknown error"}.`
2454
+ );
2455
+ }
2456
+ return text(parts.join("\n"));
2457
+ })
2458
+ );
2459
+ server.registerTool(
2460
+ "generate_image",
2461
+ {
2462
+ description: HARNESS_TOOL_DESCRIPTIONS.generate_image,
2463
+ inputSchema: {
2464
+ prompt: z2.string().min(1).max(4e3).describe("What the image should show, or the edit to make to inputImages."),
2465
+ aspectRatio: z2.enum(IMAGE_ASPECT_RATIOS).optional(),
2466
+ quality: z2.enum(IMAGE_QUALITIES).optional().describe("'draft', 'standard' (default) or 'high'."),
2467
+ negativePrompt: z2.string().max(2e3).optional().describe("Things to keep out of the image."),
2468
+ inputImages: z2.array(z2.string().min(1)).max(4).optional().describe("Images to edit or combine: absolute paths, or paths relative to this folder.")
2469
+ }
2470
+ },
2471
+ async (args) => guarded(async () => {
2472
+ const binding = await session.bind();
2473
+ if (binding.info?.images === "off") {
2474
+ return failure(
2475
+ "Image generation is turned off for other apps in Gezel (Settings \u2192 Integrations)."
2476
+ );
2477
+ }
2478
+ const inputs = [];
2479
+ for (const path of args.inputImages ?? []) {
2480
+ const image = await readAllowedImage(binding, path);
2481
+ if ("error" in image) return failure(image.error);
2482
+ inputs.push(image);
2483
+ }
2484
+ const res = await session.run(
2485
+ binding,
2486
+ (api) => api.generateImage({
2487
+ prompt: args.prompt,
2488
+ projectId: boundProjectId(binding) ?? UNBOUND_PROJECT,
2489
+ inline: true,
2490
+ ...args.aspectRatio ? { aspectRatio: args.aspectRatio } : {},
2491
+ ...args.quality ? { quality: args.quality } : {},
2492
+ ...args.negativePrompt ? { negativePrompt: args.negativePrompt } : {},
2493
+ ...inputs.length > 0 ? { inputImages: inputs } : {}
2494
+ })
2495
+ );
2496
+ const artifactsDir = binding.info?.artifactsDir;
2497
+ const saved = artifactsDir ? join2(artifactsDir, res.artifactPath) : res.artifactPath;
2498
+ const content = [];
2499
+ if (res.b64Png) content.push({ type: "image", data: res.b64Png, mimeType: "image/png" });
2500
+ const skipped = res.meta.img2imgSkippedReason ? `This image engine can't edit images (${res.meta.img2imgSkippedReason}), so it ignored inputImages and made a new image from the prompt alone. To change an image, describe the whole picture you want. ` : "";
2501
+ content.push({
2502
+ type: "text",
2503
+ text: `${skipped}Saved to ${saved} (${res.meta.widthPx}x${res.meta.heightPx}, ${res.meta.model}). Copy it into the folder with your own file tools if it belongs there.`
2504
+ });
2505
+ return { content };
2506
+ })
2507
+ );
2508
+ server.registerTool(
2509
+ "gezel_status",
2510
+ {
2511
+ description: HARNESS_TOOL_DESCRIPTIONS.gezel_status,
2512
+ inputSchema: {},
2513
+ annotations: { readOnlyHint: true }
2514
+ },
2515
+ async () => guarded(async () => {
2516
+ const binding = await session.bind();
2517
+ const info = binding.info;
2518
+ const lines = [];
2519
+ if (info?.project) {
2520
+ lines.push(
2521
+ `Project: ${info.project.name}${info.project.workingDir ? ` (${info.project.workingDir})` : ""}${info.project.created ? ", added to Gezel just now" : ""}.`
2522
+ );
2523
+ const status = await session.run(binding, (api) => api.getProjectIndexStatus(info.project.id)).catch(() => null);
2524
+ if (status) lines.push(`Index: ${status.state}.`);
2525
+ } else {
2526
+ const why = info?.unboundReason === "forbidden-root" ? "Gezel never makes a project of this folder (it is too broad, like a home folder or a drive)." : info?.unboundReason === "not-in-gezel" ? "This folder is not in Gezel, and Gezel is set to add only folders the person adds themselves." : "This app has no folder for Gezel to look at.";
2527
+ lines.push(
2528
+ `No project. ${why} Search reaches the shared library, memories and knowledge.`
2529
+ );
2530
+ }
2531
+ if (info?.libraryDir) lines.push(`Shared library: ${info.libraryDir}`);
2532
+ lines.push(
2533
+ `Memories: ${info?.memory === "save" ? "search and save" : info?.memory === "read" ? "search only" : "off"}.`,
2534
+ `Images: ${info?.images === "any" ? "any image engine" : info?.images === "local" ? "on this computer only" : "off"}.`
2535
+ );
2536
+ const catalogs = await session.run(binding, (api) => api.listKnowledgeCatalogs()).then((r) => r.catalogs).catch(() => []);
2537
+ const named = catalogs.filter((c) => c.enabled && !isHarnessHiddenCatalog(c.ref.catalogId)).map((c) => `${c.ref.catalogId}${c.name ? ` (${c.name})` : ""}`);
2538
+ lines.push(
2539
+ named.length > 0 ? `Knowledge catalogs: ${named.join(", ")}.` : "Knowledge catalogs: none."
2540
+ );
2541
+ return text(lines.join("\n"));
2542
+ })
2543
+ );
2544
+ }
2545
+ async function readAllowedImage(binding, path) {
2546
+ const where = rootedPath(binding, path);
2547
+ if (!where)
2548
+ return { error: `${absoluteFromApp(binding, path)} is outside ${whereFilesMayBe(binding)}.` };
2549
+ const mimeType = IMAGE_MIME[extname(where.abs).toLowerCase()];
2550
+ if (!mimeType)
2551
+ return {
2552
+ error: `${where.abs} is not an image Gezel can read (PNG, JPEG, WebP, GIF, BMP or HEIC).`
2553
+ };
2554
+ const info = await stat(where.abs).catch(() => null);
2555
+ if (!info?.isFile()) return { error: `${where.abs} was not found.` };
2556
+ if (info.size > MAX_IMAGE_BYTES) return { error: `${where.abs} is larger than 20 MB.` };
2557
+ return { data: (await readFile(where.abs)).toString("base64"), mimeType };
2558
+ }
2559
+
2560
+ // src/harness/documents.ts
2561
+ var TOOLS = docblocks_tools_default.tools;
2562
+ var SOURCE_ARGS = {
2563
+ convert_document: ["source"],
2564
+ get_authoring_context: ["source"],
2565
+ inspect_document: ["source"],
2566
+ preview_document: ["source"]
2567
+ };
2568
+ var CALL_TIMEOUT_MS = 10 * 6e4;
2569
+ var OUTDATED = "This version of Gezel can't make documents for other apps yet. Update Gezel, then try again.";
2570
+ function appSaveSchema(schema) {
2571
+ const destination = schema.properties.destination;
2572
+ const path = destination?.anyOf?.[0]?.properties?.path;
2573
+ return {
2574
+ ...schema,
2575
+ properties: {
2576
+ ...schema.properties,
2577
+ destination: {
2578
+ type: "object",
2579
+ properties: {
2580
+ path: {
2581
+ ...path,
2582
+ description: "A file name, or a path inside Gezel's output folder, such as report.docx."
2583
+ },
2584
+ ifExists: { type: "string", enum: ["error", "replace"], default: "error" },
2585
+ expectedSha256: {
2586
+ type: "string",
2587
+ pattern: "^[a-f0-9]{64}$",
2588
+ description: "With ifExists replace: the current file's SHA-256."
2589
+ }
2590
+ },
2591
+ required: ["path"],
2592
+ additionalProperties: false
2593
+ }
2594
+ }
2595
+ };
2596
+ }
2597
+ function listedAs(json) {
2598
+ const schema = z3.object({}).loose();
2599
+ schema._zod.toJSONSchema = () => structuredClone(json);
2600
+ return schema;
2601
+ }
2602
+ var DocblocksRuntime = class _DocblocksRuntime {
2603
+ constructor(client, readRoot, outputDir, writeRootId) {
2604
+ this.client = client;
2605
+ this.readRoot = readRoot;
2606
+ this.outputDir = outputDir;
2607
+ this.writeRootId = writeRootId;
2608
+ }
2609
+ client;
2610
+ readRoot;
2611
+ outputDir;
2612
+ writeRootId;
2613
+ static async start(binding) {
2614
+ const docs = binding.info?.documents;
2615
+ if (!docs) throw new Error(OUTDATED);
2616
+ const readRoot = binding.info?.project?.workingDir ?? null;
2617
+ const outputDir = await outputDirFor(binding);
2618
+ const args = [docs.entry, "mcp"];
2619
+ if (readRoot) args.push("--allow-read", readRoot);
2620
+ args.push("--allow-write", outputDir);
2621
+ const env = {};
2622
+ if (docs.browsersPath) env.PLAYWRIGHT_BROWSERS_PATH = docs.browsersPath;
2623
+ if (process.env.SQUISQ_FFMPEG) env.SQUISQ_FFMPEG = process.env.SQUISQ_FFMPEG;
2624
+ const client = new Client({ name: "gezel-harness", version: "1.0.0" });
2625
+ await client.connect(
2626
+ new StdioClientTransport({ command: process.execPath, args, env, stderr: "ignore" })
2627
+ );
2628
+ const listed2 = await client.callTool({ name: "list_roots", arguments: {} });
2629
+ const writeRootId = writableRoot(listed2);
2630
+ if (!writeRootId) {
2631
+ await client.close().catch(() => {
2632
+ });
2633
+ throw new Error("Gezel's document tools started without a folder to save into.");
2634
+ }
2635
+ return new _DocblocksRuntime(client, readRoot, outputDir, writeRootId);
2636
+ }
2637
+ async call(name, args) {
2638
+ return await this.client.callTool({ name, arguments: args }, void 0, {
2639
+ timeout: CALL_TIMEOUT_MS,
2640
+ resetTimeoutOnProgress: true
2641
+ });
2642
+ }
2643
+ close() {
2644
+ return this.client.close().catch(() => {
2645
+ });
2646
+ }
2647
+ };
2648
+ async function outputDirFor(binding) {
2649
+ const artifactsDir = binding.info?.artifactsDir;
2650
+ if (artifactsDir) {
2651
+ const dir2 = join3(artifactsDir, "documents");
2652
+ try {
2653
+ await mkdir(dir2, { recursive: true });
2654
+ await access(dir2, constants.W_OK);
2655
+ return dir2;
2656
+ } catch {
2657
+ }
2658
+ }
2659
+ const dir = join3(tmpdir(), "gezel-documents", boundProjectId(binding) ?? "default");
2660
+ await mkdir(dir, { recursive: true });
2661
+ return dir;
2662
+ }
2663
+ function writableRoot(listed2) {
2664
+ const text2 = listed2.content.filter((c) => c.type === "text").map((c) => c.text).join("");
2665
+ const structured = listed2.structuredContent;
2666
+ let roots = structured?.roots;
2667
+ if (!Array.isArray(roots)) {
2668
+ try {
2669
+ roots = JSON.parse(text2).roots;
2670
+ } catch {
2671
+ return null;
2672
+ }
2673
+ }
2674
+ if (!Array.isArray(roots)) return null;
2675
+ const root = roots.find((r) => r.write === true);
2676
+ return typeof root?.id === "string" ? root.id : null;
2677
+ }
2678
+ function appSource(binding, runtime, source) {
2679
+ const path = typeof source === "string" && !source.startsWith("docblocks://") ? source : source && typeof source === "object" && source.kind === "file" ? source.path : void 0;
2680
+ if (typeof path !== "string") return { source };
2681
+ if (!runtime.readRoot) {
2682
+ return { error: "This app is not working in a Gezel folder, so pass Markdown, not a file." };
2683
+ }
2684
+ const rel = relativeInside(runtime.readRoot, absoluteFromApp(binding, path));
2685
+ if (!rel) return { error: `${path} is not inside ${runtime.readRoot}.` };
2686
+ const rest = typeof source === "object" ? source : {};
2687
+ const { rootId: _rootId, ...file } = rest;
2688
+ return { source: { ...file, kind: "file", path: rel } };
2689
+ }
2690
+ function appDestination(runtime, destination) {
2691
+ const given = typeof destination === "string" ? { path: destination } : destination && typeof destination === "object" ? destination : null;
2692
+ const raw = typeof given?.path === "string" ? given.path.trim() : "";
2693
+ if (!raw) return { error: 'save_artifact needs `destination: {"path": "report.docx"}`.' };
2694
+ const path = isAbsolute4(raw) ? relativeInside(runtime.outputDir, resolve3(raw)) : raw.replaceAll("\\", "/").replace(/^(\.\/)+/, "");
2695
+ if (!path) {
2696
+ return {
2697
+ error: `Gezel saves documents in its own folder (${runtime.outputDir}): pass a file name such as report.docx, then copy the file where it belongs.`
2698
+ };
2699
+ }
2700
+ const target = join3(runtime.outputDir, path);
2701
+ const replace = given?.ifExists === "replace" && existsSync(target);
2702
+ const free = replace ? path : freeName(runtime.outputDir, path);
2703
+ const expectedSha256 = !replace ? null : typeof given?.expectedSha256 === "string" ? given.expectedSha256 : createHash("sha256").update(readFileSync2(target)).digest("hex");
2704
+ return {
2705
+ destination: {
2706
+ rootId: runtime.writeRootId,
2707
+ path: free,
2708
+ ifExists: replace ? "replace" : "error",
2709
+ expectedSha256
2710
+ },
2711
+ saved: join3(runtime.outputDir, free),
2712
+ ...free !== path ? { renamedFrom: path } : {}
2713
+ };
2714
+ }
2715
+ function freeName(dir, path) {
2716
+ if (!existsSync(join3(dir, path))) return path;
2717
+ const slash = path.lastIndexOf("/");
2718
+ const base = path.slice(slash + 1);
2719
+ const dot = base.lastIndexOf(".");
2720
+ const stem = dot > 0 ? base.slice(0, dot) : base;
2721
+ const ext = dot > 0 ? base.slice(dot) : "";
2722
+ for (let n = 2; ; n++) {
2723
+ const candidate = `${path.slice(0, slash + 1)}${stem} (${n})${ext}`;
2724
+ if (!existsSync(join3(dir, candidate))) return candidate;
2725
+ }
2726
+ }
2727
+ function registerHarnessDocumentTools(server, session) {
2728
+ const runtimes = /* @__PURE__ */ new Map();
2729
+ session.onClose(async () => {
2730
+ const all = [...runtimes.values()];
2731
+ runtimes.clear();
2732
+ await Promise.all(all.map((p) => p.then((r) => r.close()).catch(() => {
2733
+ })));
2734
+ });
2735
+ const runtimeFor = (binding) => {
2736
+ let runtime = runtimes.get(binding.key);
2737
+ if (!runtime) {
2738
+ runtime = DocblocksRuntime.start(binding);
2739
+ runtimes.set(binding.key, runtime);
2740
+ runtime.catch(() => runtimes.delete(binding.key));
2741
+ }
2742
+ return runtime;
2743
+ };
2744
+ for (const name of HARNESS_DOCUMENT_TOOL_NAMES) {
2745
+ const tool = TOOLS.find((t) => t.name === name);
2746
+ if (!tool) continue;
2747
+ const inputSchema = name === "save_artifact" ? appSaveSchema(tool.inputSchema) : tool.inputSchema;
2748
+ server.registerTool(
2749
+ name,
2750
+ {
2751
+ description: `${tool.description} ${HARNESS_DOCUMENT_TOOL_NOTES[name]}`,
2752
+ inputSchema: listedAs(inputSchema),
2753
+ ...tool.annotations ? { annotations: tool.annotations } : {}
2754
+ },
2755
+ async (args) => guarded(async () => {
2756
+ if (missingArguments(inputSchema, args).length > 0) {
2757
+ return failure(argumentHelp(name, inputSchema, args));
2758
+ }
2759
+ const binding = await session.bind();
2760
+ if (!binding.info?.documents) return failure(OUTDATED);
2761
+ let runtime;
2762
+ try {
2763
+ runtime = await runtimeFor(binding);
2764
+ } catch (err) {
2765
+ const reason = err instanceof Error ? err.message : String(err);
2766
+ return failure(
2767
+ reason === OUTDATED ? reason : `Gezel could not start its document tools: ${reason}`
2768
+ );
2769
+ }
2770
+ const forwarded = { ...args };
2771
+ for (const key of SOURCE_ARGS[name] ?? []) {
2772
+ if (forwarded[key] === void 0) continue;
2773
+ const mapped = appSource(binding, runtime, forwarded[key]);
2774
+ if ("error" in mapped) return failure(mapped.error);
2775
+ forwarded[key] = mapped.source;
2776
+ }
2777
+ let saved = null;
2778
+ let renamedFrom;
2779
+ if (name === "save_artifact") {
2780
+ const mapped = appDestination(runtime, forwarded.destination);
2781
+ if ("error" in mapped) return failure(mapped.error);
2782
+ forwarded.destination = mapped.destination;
2783
+ saved = mapped.saved;
2784
+ renamedFrom = mapped.renamedFrom;
2785
+ await mkdir(dirname(saved), { recursive: true });
2786
+ }
2787
+ const { structuredContent, ...result } = await runtime.call(name, forwarded);
2788
+ const failed = result.isError === true || structuredContent?.kind === "error";
2789
+ if (failed) result.isError = true;
2790
+ if (saved && !failed) {
2791
+ const renamed = renamedFrom ? `Gezel's folder already had a ${renamedFrom}, so this one is named ${basename(saved)}. ` : "";
2792
+ result.content = [
2793
+ ...result.content,
2794
+ {
2795
+ type: "text",
2796
+ text: `${renamed}Saved to ${saved}. Copy it into the folder with your own file tools if it belongs there.`
2797
+ }
2798
+ ];
2799
+ }
2800
+ return result;
2801
+ })
2802
+ );
2803
+ }
2804
+ }
2805
+
2806
+ // src/harness/issues.ts
2807
+ import { join as join4 } from "path";
2808
+ import {
2809
+ HARNESS_PROMPTS,
2810
+ HARNESS_PROMPT_NAMES,
2811
+ HARNESS_TOOL_DESCRIPTIONS as HARNESS_TOOL_DESCRIPTIONS2,
2812
+ ISSUE_VERDICT_KINDS,
2813
+ MAX_APP_ISSUE_VERDICTS_PER_CALL,
2814
+ harnessPromptCount,
2815
+ renderEmptyIssuePrompt,
2816
+ renderHarnessIssuePrompt,
2817
+ renderIssueBatch
2818
+ } from "@bendyline/gezel";
2819
+ import { z as z4 } from "zod";
2820
+ var UPDATE_GEZEL = "This version of Gezel cannot hand issues to other apps. Update Gezel to use this tool.";
2821
+ var NO_PROJECT = "This app isn't working in a folder Gezel knows, so there are no issues to check. Start the app in a folder Gezel has added.";
2822
+ function issuesBlocked(binding, need) {
2823
+ const mode = binding.info?.issues;
2824
+ if (mode === void 0) return UPDATE_GEZEL;
2825
+ if (mode === "off")
2826
+ return "Gezel's issues are turned off for other apps (Settings \u2192 Integrations).";
2827
+ if (need === "triage" && mode !== "triage") {
2828
+ return "Reporting verdicts is turned off for other apps in Gezel (Settings \u2192 Integrations); you can still list issues.";
2829
+ }
2830
+ return boundProjectId(binding) ? null : NO_PROJECT;
2831
+ }
2832
+ async function fetchBatch(session, binding, req) {
2833
+ const id = boundProjectId(binding);
2834
+ const queue = await session.run(binding, (api) => api.issueTriage.handoffQueue(id, req));
2835
+ const workingDir = binding.info?.project?.workingDir;
2836
+ return {
2837
+ text: renderIssueBatch(queue, (rel) => workingDir ? join4(workingDir, rel) : rel),
2838
+ empty: queue.count === 0
2839
+ };
2840
+ }
2841
+ function registerHarnessIssueTools(server, session) {
2842
+ server.registerTool(
2843
+ "list_issues",
2844
+ {
2845
+ description: HARNESS_TOOL_DESCRIPTIONS2.list_issues,
2846
+ inputSchema: {
2847
+ limit: z4.number().int().positive().max(50).optional().describe("Default 20."),
2848
+ severity: z4.enum(["major", "minor", "info"]).optional(),
2849
+ pathPrefix: z4.string().min(1).optional().describe(
2850
+ "Only issues under this folder: an absolute path, or one relative to this folder."
2851
+ ),
2852
+ includeInfo: z4.boolean().optional().describe("Include info-level leads. Default false.")
2853
+ },
2854
+ annotations: { readOnlyHint: true }
2855
+ },
2856
+ async (args) => guarded(async () => {
2857
+ const binding = await session.bind(args.pathPrefix);
2858
+ const blocked = issuesBlocked(binding, "read");
2859
+ if (blocked) return failure(blocked);
2860
+ let pathPrefix;
2861
+ if (args.pathPrefix) {
2862
+ const workingDir = binding.info?.project?.workingDir;
2863
+ const rel = workingDir ? relativeInside(workingDir, absoluteFromApp(binding, args.pathPrefix)) : null;
2864
+ if (rel === null)
2865
+ return failure(`pathPrefix must be inside ${whereFilesMayBe(binding)}.`);
2866
+ if (rel) pathPrefix = rel;
2867
+ }
2868
+ const batch = await fetchBatch(session, binding, {
2869
+ ...args.limit ? { limit: args.limit } : {},
2870
+ ...args.severity ? { severity: args.severity } : {},
2871
+ ...pathPrefix ? { pathPrefix } : {},
2872
+ ...args.includeInfo ? { includeInfo: true } : {}
2873
+ });
2874
+ return text(batch.text);
2875
+ })
2876
+ );
2877
+ server.registerTool(
2878
+ "report_issue_verdicts",
2879
+ {
2880
+ description: HARNESS_TOOL_DESCRIPTIONS2.report_issue_verdicts,
2881
+ inputSchema: {
2882
+ verdicts: z4.array(
2883
+ z4.object({
2884
+ ref: z4.string().regex(/^BW-[1-9]\d*$/).describe("The issue code, e.g. BW-17."),
2885
+ verdict: z4.enum(ISSUE_VERDICT_KINDS),
2886
+ reason: z4.enum(["incorrect", "handled_elsewhere", "intended"]).optional().describe("Only for not_a_bug."),
2887
+ note: z4.string().min(3).max(2e3).describe(
2888
+ "Your evidence in a sentence: a file:line, a test, the caller that handles it."
2889
+ ),
2890
+ duplicateOf: z4.string().regex(/^BW-[1-9]\d*$/).optional().describe("Only for duplicate: the issue this one repeats.")
2891
+ })
2892
+ ).min(1).max(MAX_APP_ISSUE_VERDICTS_PER_CALL)
2893
+ }
2894
+ },
2895
+ async (args) => guarded(async () => {
2896
+ const binding = await session.bind();
2897
+ const blocked = issuesBlocked(binding, "triage");
2898
+ if (blocked) return failure(blocked);
2899
+ const id = boundProjectId(binding);
2900
+ const res = await session.run(
2901
+ binding,
2902
+ (api) => api.issueTriage.applyVerdicts(id, {
2903
+ verdicts: args.verdicts.map((v) => ({
2904
+ ref: v.ref,
2905
+ kind: v.verdict,
2906
+ ...v.verdict === "not_a_bug" && v.reason ? { reason: v.reason } : {},
2907
+ note: v.note,
2908
+ ...v.duplicateOf ? { duplicateOf: v.duplicateOf } : {}
2909
+ }))
2910
+ })
2911
+ );
2912
+ const lines = [
2913
+ `Gezel recorded ${res.applied} verdict${res.applied === 1 ? "" : "s"}${res.refused ? `; ${res.refused} refused` : ""}.`,
2914
+ ...res.results.filter((r) => r.outcome === "refused").map((r) => `- ${r.ref}: ${r.message}`),
2915
+ ...res.results.filter((r) => r.outcome === "applied" && /can't confirm/.test(r.message)).map((r) => `- ${r.message}`)
2916
+ ];
2917
+ return text(lines.join("\n"));
2918
+ })
2919
+ );
2920
+ }
2921
+ function registerHarnessPrompts(server, session) {
2922
+ for (const name of HARNESS_PROMPT_NAMES) {
2923
+ const prompt = HARNESS_PROMPTS[name];
2924
+ server.registerPrompt(
2925
+ name,
2926
+ {
2927
+ title: prompt.title,
2928
+ description: prompt.description,
2929
+ argsSchema: {
2930
+ count: z4.string().optional().describe(`How many issues to take on (default ${prompt.defaultCount}, at most 50).`)
2931
+ }
2932
+ },
2933
+ async (args) => {
2934
+ let body;
2935
+ try {
2936
+ const binding = await session.bind();
2937
+ const blocked = issuesBlocked(binding, name === "fix_issues" ? "triage" : "read");
2938
+ if (blocked) {
2939
+ body = blocked;
2940
+ } else {
2941
+ const batch = await fetchBatch(session, binding, {
2942
+ limit: harnessPromptCount(name, args.count),
2943
+ ...name === "fix_issues" ? { mode: "fix" } : {}
2944
+ });
2945
+ body = batch.empty ? renderEmptyIssuePrompt(batch.text) : renderHarnessIssuePrompt(name, batch.text);
2946
+ }
2947
+ } catch (err) {
2948
+ body = err instanceof Error ? err.message : String(err);
2949
+ }
2950
+ return {
2951
+ messages: [{ role: "user", content: { type: "text", text: body } }]
2952
+ };
2953
+ }
2954
+ );
2955
+ }
2956
+ }
2957
+
2958
+ // src/harness/index.ts
2959
+ var ROOTS_TIMEOUT_MS = 5e3;
2960
+ function packageVersion() {
2961
+ try {
2962
+ return createRequire(import.meta.url)("../package.json").version ?? "0.0.0";
2963
+ } catch {
2964
+ return "0.0.0";
2965
+ }
2966
+ }
2967
+ function parseHarnessArgs(argv) {
2968
+ const value = (flag) => {
2969
+ const at = argv.indexOf(flag);
2970
+ const raw = at >= 0 ? argv[at + 1] : void 0;
2971
+ if (!raw || raw.startsWith("--") || raw.includes("${")) return void 0;
2972
+ return raw;
2973
+ };
2974
+ const client = HarnessClientIdSchema.safeParse(value("--harness"));
2975
+ if (!client.success) {
2976
+ throw new Error(
2977
+ `gezel-mcp: --harness needs one of ${HarnessClientIdSchema.options.join(", ")}.`
2978
+ );
2979
+ }
2980
+ const projectId = value("--project");
2981
+ const folder = value("--folder");
2982
+ const home = process.env.GEZEL_HOME;
2983
+ return {
2984
+ client: client.data,
2985
+ ...projectId ? { projectId } : {},
2986
+ ...folder ? { folder } : {},
2987
+ ...home ? { home } : {}
2988
+ };
2989
+ }
2990
+ function createHarnessServer(session) {
2991
+ const server = new McpServer(
2992
+ { name: "gezel", version: packageVersion() },
2993
+ { instructions: HARNESS_SERVER_INSTRUCTIONS }
2994
+ );
2995
+ registerHarnessTools(server, session);
2996
+ registerHarnessDocumentTools(server, session);
2997
+ registerHarnessIssueTools(server, session);
2998
+ registerHarnessPrompts(server, session);
2999
+ teachInvalidArguments(server);
3000
+ session.setRootsProvider(async () => {
3001
+ if (!server.server.getClientCapabilities()?.roots) return null;
3002
+ const { roots } = await server.server.listRoots(void 0, { timeout: ROOTS_TIMEOUT_MS });
3003
+ return roots.filter((root) => root.uri.startsWith("file:")).map((root) => fileURLToPath(root.uri));
3004
+ });
3005
+ server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
3006
+ session.invalidateRoots();
3007
+ });
3008
+ return server;
3009
+ }
3010
+ async function runHarness(argv) {
3011
+ const session = new HarnessSession(parseHarnessArgs(argv));
3012
+ const server = createHarnessServer(session);
3013
+ const transport = new StdioServerTransport();
3014
+ transport.onclose = () => {
3015
+ void session.close();
3016
+ };
3017
+ await server.connect(transport);
3018
+ }
3019
+
3020
+ // src/harness-main.ts
3021
+ try {
3022
+ await runHarness(process.argv.slice(2));
3023
+ } catch (err) {
3024
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}
3025
+ `);
3026
+ process.exit(1);
3027
+ }