@mcpc-tech/plugin-markdown-loader 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs ADDED
@@ -0,0 +1,3961 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ const require = createRequire(import.meta.url);
4
+
5
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/compose.js
6
+ import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
+
8
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
9
+ var schemaSymbol = Symbol.for("mcpc.schema");
10
+ var vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
11
+ var validatorSymbol = Symbol.for("mcpc.validator");
12
+ function jsonSchema(schema, options = {}) {
13
+ if (isWrappedSchema(schema)) {
14
+ return schema;
15
+ }
16
+ return {
17
+ [schemaSymbol]: true,
18
+ [validatorSymbol]: true,
19
+ _type: void 0,
20
+ jsonSchema: schema,
21
+ validate: options.validate
22
+ };
23
+ }
24
+ function isWrappedSchema(value) {
25
+ return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
26
+ }
27
+ function extractJsonSchema(schema) {
28
+ if (isWrappedSchema(schema)) {
29
+ return schema.jsonSchema;
30
+ }
31
+ return schema;
32
+ }
33
+
34
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/compose.js
35
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
36
+
37
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/json.js
38
+ import { jsonrepair } from "jsonrepair";
39
+
40
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/ai.js
41
+ var p = (template, options = {}) => {
42
+ const { missingVariableHandling = "warn" } = options;
43
+ const names = /* @__PURE__ */ new Set();
44
+ const regex = /\{((\w|\.)+)\}/g;
45
+ let match;
46
+ while ((match = regex.exec(template)) !== null) {
47
+ names.add(match[1]);
48
+ }
49
+ const required = Array.from(names);
50
+ return (input) => {
51
+ let result = template;
52
+ for (const name of required) {
53
+ const key = name;
54
+ const value = input[key];
55
+ const re = new RegExp(`\\{${String(name)}\\}`, "g");
56
+ if (value !== void 0 && value !== null) {
57
+ result = result.replace(re, String(value));
58
+ } else {
59
+ switch (missingVariableHandling) {
60
+ case "error":
61
+ throw new Error(`Missing variable "${String(name)}" in input for template.`);
62
+ case "empty":
63
+ result = result.replace(re, "");
64
+ break;
65
+ case "warn":
66
+ case "ignore":
67
+ default:
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ return result;
73
+ };
74
+ };
75
+
76
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
77
+ import { load } from "cheerio";
78
+
79
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__utils/src/transport/sse.js
80
+ import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
81
+
82
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__http/server_sent_event_stream.js
83
+ var NEWLINE_REGEXP = /\r\n|\r|\n/;
84
+ var encoder = new TextEncoder();
85
+ function assertHasNoNewline(value, varName, errPrefix) {
86
+ if (value.match(NEWLINE_REGEXP) !== null) {
87
+ throw new SyntaxError(`${errPrefix}: ${varName} cannot contain a newline`);
88
+ }
89
+ }
90
+ function stringify(message) {
91
+ const lines = [];
92
+ if (message.comment) {
93
+ assertHasNoNewline(message.comment, "`message.comment`", "Cannot serialize message");
94
+ lines.push(`:${message.comment}`);
95
+ }
96
+ if (message.event) {
97
+ assertHasNoNewline(message.event, "`message.event`", "Cannot serialize message");
98
+ lines.push(`event:${message.event}`);
99
+ }
100
+ if (message.data) {
101
+ message.data.split(NEWLINE_REGEXP).forEach((line) => lines.push(`data:${line}`));
102
+ }
103
+ if (message.id) {
104
+ assertHasNoNewline(message.id.toString(), "`message.id`", "Cannot serialize message");
105
+ lines.push(`id:${message.id}`);
106
+ }
107
+ if (message.retry) lines.push(`retry:${message.retry}`);
108
+ return encoder.encode(lines.join("\n") + "\n\n");
109
+ }
110
+ var ServerSentEventStream = class extends TransformStream {
111
+ constructor() {
112
+ super({
113
+ transform: (message, controller) => {
114
+ controller.enqueue(stringify(message));
115
+ }
116
+ });
117
+ }
118
+ };
119
+
120
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
121
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
122
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
123
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
124
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
125
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
126
+
127
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
128
+ import process from "node:process";
129
+ var GEMINI_PREFERRED_FORMAT = process.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
130
+
131
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
132
+ import { jsonrepair as jsonrepair2 } from "jsonrepair";
133
+
134
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
135
+ var createModelCompatibleJSONSchema = (schema) => {
136
+ const validatorOnlyKeys = [
137
+ "errorMessage"
138
+ ];
139
+ const geminiRestrictedKeys = GEMINI_PREFERRED_FORMAT ? [
140
+ "additionalProperties"
141
+ ] : [];
142
+ const keysToRemove = /* @__PURE__ */ new Set([
143
+ ...validatorOnlyKeys,
144
+ ...geminiRestrictedKeys
145
+ ]);
146
+ let cleanSchema = schema;
147
+ if (GEMINI_PREFERRED_FORMAT) {
148
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest } = schema;
149
+ cleanSchema = rest;
150
+ }
151
+ const cleanRecursively = (obj) => {
152
+ if (Array.isArray(obj)) {
153
+ return obj.map(cleanRecursively);
154
+ }
155
+ if (obj && typeof obj === "object") {
156
+ const result = {};
157
+ for (const [key, value] of Object.entries(obj)) {
158
+ if (!keysToRemove.has(key)) {
159
+ result[key] = cleanRecursively(value);
160
+ }
161
+ }
162
+ return result;
163
+ }
164
+ return obj;
165
+ };
166
+ return cleanRecursively(cleanSchema);
167
+ };
168
+ var INTERNAL_SCHEMA_KEYS = /* @__PURE__ */ new Set([
169
+ "$schema",
170
+ "_originalName",
171
+ "_type",
172
+ "annotations"
173
+ ]);
174
+ var cleanToolSchema = (schema) => {
175
+ const cleanRecursively = (obj) => {
176
+ if (Array.isArray(obj)) {
177
+ return obj.map(cleanRecursively);
178
+ }
179
+ if (obj && typeof obj === "object") {
180
+ const record = obj;
181
+ if ("jsonSchema" in record && typeof record.jsonSchema === "object" && record.jsonSchema !== null) {
182
+ return cleanRecursively(record.jsonSchema);
183
+ }
184
+ const result = {};
185
+ for (const [key, value] of Object.entries(record)) {
186
+ if (!INTERNAL_SCHEMA_KEYS.has(key)) {
187
+ result[key] = cleanRecursively(value);
188
+ }
189
+ }
190
+ return result;
191
+ }
192
+ return obj;
193
+ };
194
+ return cleanRecursively(schema);
195
+ };
196
+
197
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
198
+ import process2 from "node:process";
199
+ var mcpClientPool = /* @__PURE__ */ new Map();
200
+ var cleanupAllPooledClients = async () => {
201
+ const entries = Array.from(mcpClientPool.entries());
202
+ mcpClientPool.clear();
203
+ await Promise.all(entries.map(async ([, { client }]) => {
204
+ try {
205
+ await client.close();
206
+ } catch (err) {
207
+ console.error("Error closing MCP client:", err);
208
+ }
209
+ }));
210
+ };
211
+ process2.once?.("exit", () => {
212
+ cleanupAllPooledClients();
213
+ });
214
+ process2.once?.("SIGINT", () => {
215
+ cleanupAllPooledClients().finally(() => process2.exit(0));
216
+ });
217
+
218
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
219
+ var createConfigPlugin = () => ({
220
+ name: "built-in-config",
221
+ version: "1.0.0",
222
+ enforce: "pre",
223
+ transformTool: (tool2, context2) => {
224
+ const server = context2.server;
225
+ const config = server.findToolConfig?.(context2.toolName);
226
+ if (config?.description) {
227
+ tool2.description = config.description;
228
+ }
229
+ return tool2;
230
+ }
231
+ });
232
+ var config_plugin_default = createConfigPlugin();
233
+
234
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
235
+ var createToolNameMappingPlugin = () => ({
236
+ name: "built-in-tool-name-mapping",
237
+ version: "1.0.0",
238
+ enforce: "pre",
239
+ transformTool: (tool2, context2) => {
240
+ const server = context2.server;
241
+ const toolName = context2.toolName;
242
+ const originalName = tool2._originalName || toolName;
243
+ const dotNotation = originalName.replace(/_/g, ".");
244
+ const underscoreNotation = originalName.replace(/\./g, "_");
245
+ if (dotNotation !== originalName && server.toolNameMapping) {
246
+ server.toolNameMapping.set(dotNotation, toolName);
247
+ }
248
+ if (underscoreNotation !== originalName && server.toolNameMapping) {
249
+ server.toolNameMapping.set(underscoreNotation, toolName);
250
+ }
251
+ if (originalName !== toolName && server.toolNameMapping) {
252
+ server.toolNameMapping.set(originalName, toolName);
253
+ }
254
+ return tool2;
255
+ }
256
+ });
257
+ var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
258
+
259
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
260
+ var LOG_LEVELS = {
261
+ debug: 0,
262
+ info: 1,
263
+ notice: 2,
264
+ warning: 3,
265
+ error: 4,
266
+ critical: 5,
267
+ alert: 6,
268
+ emergency: 7
269
+ };
270
+ var MCPLogger = class _MCPLogger {
271
+ server;
272
+ loggerName;
273
+ minLevel = "debug";
274
+ constructor(loggerName = "mcpc", server) {
275
+ this.loggerName = loggerName;
276
+ this.server = server;
277
+ }
278
+ setServer(server) {
279
+ this.server = server;
280
+ }
281
+ setLevel(level) {
282
+ this.minLevel = level;
283
+ }
284
+ async log(level, data) {
285
+ if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
286
+ return;
287
+ }
288
+ this.logToConsole(level, data);
289
+ if (this.server) {
290
+ try {
291
+ await this.server.sendLoggingMessage({
292
+ level,
293
+ logger: this.loggerName,
294
+ data
295
+ });
296
+ } catch {
297
+ }
298
+ }
299
+ }
300
+ logToConsole(level, data) {
301
+ const message = typeof data === "string" ? data : JSON.stringify(data);
302
+ const prefix = `[${this.loggerName}:${level}]`;
303
+ console.error(prefix, message);
304
+ }
305
+ debug(data) {
306
+ return this.log("debug", data);
307
+ }
308
+ info(data) {
309
+ return this.log("info", data);
310
+ }
311
+ notice(data) {
312
+ return this.log("notice", data);
313
+ }
314
+ warning(data) {
315
+ return this.log("warning", data);
316
+ }
317
+ error(data) {
318
+ return this.log("error", data);
319
+ }
320
+ critical(data) {
321
+ return this.log("critical", data);
322
+ }
323
+ alert(data) {
324
+ return this.log("alert", data);
325
+ }
326
+ emergency(data) {
327
+ return this.log("emergency", data);
328
+ }
329
+ child(name) {
330
+ const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
331
+ child.setLevel(this.minLevel);
332
+ return child;
333
+ }
334
+ };
335
+ var logger = new MCPLogger("mcpc");
336
+ function createLogger(name, server) {
337
+ return new MCPLogger(name, server);
338
+ }
339
+
340
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
341
+ var createLoggingPlugin = (options = {}) => {
342
+ const { enabled = true, verbose = false, compact = true } = options;
343
+ return {
344
+ name: "built-in-logging",
345
+ version: "1.0.0",
346
+ composeEnd: async (context2) => {
347
+ if (!enabled) return;
348
+ const logger2 = createLogger("mcpc.plugin.logging", context2.server);
349
+ if (compact) {
350
+ const pluginCount = context2.pluginNames.length;
351
+ const { stats } = context2;
352
+ await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
353
+ } else if (verbose) {
354
+ await logger2.info(`[${context2.toolName}] Composition complete`);
355
+ await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
356
+ const { stats } = context2;
357
+ const server = context2.server;
358
+ const publicTools = Array.from(new Set(server.getPublicToolNames().map(String)));
359
+ const internalTools = Array.from(new Set(server.getInternalToolNames().map(String)));
360
+ const hiddenTools = Array.from(new Set(server.getHiddenToolNames().map(String)));
361
+ const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
362
+ if (publicTools.length > 0) {
363
+ await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
364
+ }
365
+ if (internalTools.length > 0) {
366
+ const parts = [];
367
+ if (normalInternal.length > 0) {
368
+ parts.push(normalInternal.join(", "));
369
+ }
370
+ if (hiddenTools.length > 0) {
371
+ parts.push(`(${hiddenTools.join(", ")})`);
372
+ }
373
+ await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
374
+ }
375
+ await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
376
+ }
377
+ }
378
+ };
379
+ };
380
+ var logging_plugin_default = createLoggingPlugin({
381
+ verbose: true,
382
+ compact: false
383
+ });
384
+
385
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
386
+ var SystemPrompts = {
387
+ /**
388
+ * Base system prompt for autonomous MCP execution
389
+ *
390
+ * Uses simplified Unix-style interface:
391
+ * - `tool` + `args` for clean, consistent structure
392
+ * - `man` command for fetching tool schemas (like Unix manual)
393
+ * - No `hasDefinitions` - trusts model's context memory
394
+ */
395
+ AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools.
396
+
397
+ You must follow the <manual/>, obey the <rules/>, and use the <format/>.
398
+
399
+ <manual>
400
+ {description}
401
+ </manual>
402
+
403
+ <parameters>
404
+ \`tool\` - Which tool to execute: "man" to get schemas, or a tool name to execute
405
+ \`args\` - For "man": { tools: ["tool1", "tool2"] }. For other tools: tool parameters that strictly adhere to the tool's JSON schema.
406
+ </parameters>
407
+
408
+ <rules>
409
+ 1. **First call**: Use \`man\` to get tool schemas you need
410
+ 2. **Execute tools**: Use tool name in \`tool\` and parameters in \`args\`
411
+ 3. **Parallel calls**: If your client supports it, call \`man\` and execute tools simultaneously
412
+ 4. Note: You are an agent exposed as an MCP tool
413
+ </rules>
414
+
415
+ <format>
416
+ Get tool schemas:
417
+ \`\`\`json
418
+ {
419
+ "tool": "man",
420
+ "args": { "tools": ["tool1", "tool2"] }
421
+ }
422
+ \`\`\`
423
+
424
+ Execute a tool:
425
+ \`\`\`json
426
+ {
427
+ "tool": "tool_name",
428
+ "args": { /* tool parameters */ }
429
+ }
430
+ \`\`\`
431
+ </format>`,
432
+ /**
433
+ * Tool description for sampling tools (shown in MCP tools list)
434
+ * Explains how to use prompt and context parameters
435
+ */
436
+ SAMPLING_TOOL_DESCRIPTION: `Subagent tool \`{toolName}\` that executes complex tasks.
437
+
438
+ You must follow the <manual/>, obey the <rules/>, and use the <format/>.
439
+
440
+ <manual>
441
+ {description}
442
+ </manual>
443
+
444
+ <format>
445
+ \`prompt\` - The task to be completed (e.g., "organize my desktop files")
446
+ \`context\` - Execution context object (e.g., { cwd: "/path/to/dir" })
447
+ </format>
448
+
449
+ <rules>
450
+ 1. Always provide both \`prompt\` and \`context\` parameters
451
+ 2. \`prompt\` must be a clear, actionable description
452
+ 3. \`context\` must include relevant environment info (e.g., working directory)
453
+ </rules>`,
454
+ /**
455
+ * System prompt for AI sampling loop (ai_sampling/ai_acp modes)
456
+ * Used inside the execution loop when AI calls native tools.
457
+ * Note: Tool schemas are passed via AI SDK native tool calling, not in prompt.
458
+ */
459
+ AI_LOOP_SYSTEM: `Agent \`{toolName}\` that completes tasks by calling tools.
460
+
461
+ <manual>
462
+ {description}
463
+ </manual>
464
+
465
+ <rules>
466
+ {rules}
467
+ </rules>{context}`
468
+ };
469
+ var ResponseTemplates = {
470
+ /**
471
+ * Success response for action execution
472
+ */
473
+ ACTION_SUCCESS: `Action \`{currentAction}\` completed.
474
+
475
+ Next: Execute \`{nextAction}\` by calling \`{toolName}\` again.`,
476
+ /**
477
+ * Planning prompt when no next action is specified
478
+ */
479
+ PLANNING_PROMPT: `Action \`{currentAction}\` completed. Determine next step:
480
+
481
+ 1. Analyze results from \`{currentAction}\`
482
+ 2. Decide: Continue with another action or Complete?
483
+ 3. Call \`{toolName}\` with chosen action or \`decision: "complete"\``,
484
+ /**
485
+ * Error response templates
486
+ */
487
+ ERROR_RESPONSE: `Validation failed: {errorMessage}
488
+
489
+ Adjust parameters and retry.`,
490
+ /**
491
+ * Completion message
492
+ */
493
+ COMPLETION_MESSAGE: `Task completed.`,
494
+ /**
495
+ * Security validation messages
496
+ */
497
+ SECURITY_VALIDATION: {
498
+ PASSED: `Security check passed: {operation} on {path}`,
499
+ FAILED: `Security check failed: {operation} on {path}`
500
+ },
501
+ /**
502
+ * Audit log messages
503
+ */
504
+ AUDIT_LOG: `[{timestamp}] {level}: {action} on {resource}{userInfo}`
505
+ };
506
+ var CompiledPrompts = {
507
+ autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
508
+ samplingToolDescription: p(SystemPrompts.SAMPLING_TOOL_DESCRIPTION),
509
+ aiLoopSystem: p(SystemPrompts.AI_LOOP_SYSTEM),
510
+ actionSuccess: p(ResponseTemplates.ACTION_SUCCESS),
511
+ planningPrompt: p(ResponseTemplates.PLANNING_PROMPT),
512
+ errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
513
+ securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
514
+ securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
515
+ auditLog: p(ResponseTemplates.AUDIT_LOG),
516
+ completionMessage: () => ResponseTemplates.COMPLETION_MESSAGE
517
+ };
518
+
519
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
520
+ function createArgsDefFactory(_name, _allToolNames, _depGroups, _predefinedSteps, _ensureStepActions) {
521
+ return {
522
+ forSampling: function() {
523
+ return {
524
+ type: "object",
525
+ description: "Provide prompt for autonomous tool execution",
526
+ properties: {
527
+ prompt: {
528
+ type: "string",
529
+ description: "The task to be completed autonomously by the agentic system using available tools"
530
+ },
531
+ context: {
532
+ type: "object",
533
+ description: "Execution context, e.g., { cwd: '/path/to/dir' }. Any relevant fields allowed.",
534
+ additionalProperties: true
535
+ }
536
+ },
537
+ required: [
538
+ "prompt",
539
+ "context"
540
+ ],
541
+ errorMessage: {
542
+ required: {
543
+ prompt: "Missing required field 'prompt'. Please provide a clear task description.",
544
+ context: "Missing required field 'context'. Please provide relevant context (e.g., { cwd: '...' })."
545
+ }
546
+ }
547
+ };
548
+ },
549
+ /**
550
+ * Agentic schema - simplified Unix-style interface
551
+ *
552
+ * Only two fields:
553
+ * - `tool`: which tool to execute (enum includes "man" + all tool names)
554
+ * - `args`: object with parameters. For "man": { tools: ["a", "b"] }. For others: tool parameters.
555
+ */
556
+ forAgentic: function(allToolNames) {
557
+ const toolEnum = [
558
+ "man",
559
+ ...allToolNames
560
+ ];
561
+ return {
562
+ type: "object",
563
+ properties: {
564
+ tool: {
565
+ type: "string",
566
+ enum: toolEnum,
567
+ description: 'Which tool to execute. Use "man" to get tool schemas, or a tool name to execute.',
568
+ errorMessage: {
569
+ enum: `Invalid tool. Available: ${toolEnum.join(", ")}`
570
+ }
571
+ },
572
+ args: {
573
+ type: "object",
574
+ description: `For "man": { tools: ["tool1", "tool2"] }. For other tools: tool parameters that strictly adhere to the tool's JSON schema.`
575
+ }
576
+ },
577
+ required: [
578
+ "tool"
579
+ ],
580
+ additionalProperties: false
581
+ };
582
+ },
583
+ /**
584
+ * Schema for "man" command args validation
585
+ * Expected format: { tools: ["tool1", "tool2"] }
586
+ */
587
+ forMan: function(allToolNames) {
588
+ return {
589
+ type: "object",
590
+ properties: {
591
+ tools: {
592
+ type: "array",
593
+ items: {
594
+ type: "string",
595
+ enum: allToolNames,
596
+ errorMessage: {
597
+ enum: `Invalid tool name. Available: ${allToolNames.join(", ")}`
598
+ }
599
+ },
600
+ minItems: 1,
601
+ errorMessage: {
602
+ minItems: "At least one tool name is required"
603
+ }
604
+ }
605
+ },
606
+ required: [
607
+ "tools"
608
+ ],
609
+ errorMessage: {
610
+ required: {
611
+ tools: 'Missing "tools" field. Expected: { tools: ["tool1", "tool2"] }'
612
+ }
613
+ }
614
+ };
615
+ }
616
+ };
617
+ }
618
+
619
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/schema-validator.js
620
+ import { Ajv } from "ajv";
621
+ import addFormats from "ajv-formats";
622
+ import ajvErrors from "ajv-errors";
623
+ import { AggregateAjvError } from "@segment/ajv-human-errors";
624
+ var ajv = new Ajv({
625
+ allErrors: true,
626
+ verbose: true,
627
+ strict: false
628
+ });
629
+ addFormats.default(ajv);
630
+ ajvErrors.default(ajv);
631
+ function validateSchema(data, schema) {
632
+ const validate = ajv.compile(schema);
633
+ if (!validate(data)) {
634
+ const errors = validate.errors;
635
+ const customErrors = errors.filter((err) => err.keyword === "errorMessage");
636
+ if (customErrors.length > 0) {
637
+ const messages = [
638
+ ...new Set(customErrors.map((err) => err.message))
639
+ ];
640
+ return {
641
+ valid: false,
642
+ error: messages.join("; ")
643
+ };
644
+ }
645
+ const aggregateError = new AggregateAjvError(errors);
646
+ return {
647
+ valid: false,
648
+ error: aggregateError.message
649
+ };
650
+ }
651
+ return {
652
+ valid: true
653
+ };
654
+ }
655
+
656
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/tracing.js
657
+ import { context, SpanStatusCode, trace } from "@opentelemetry/api";
658
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
659
+ import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
660
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
661
+ import { Resource } from "@opentelemetry/resources";
662
+ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
663
+ var tracerProvider = null;
664
+ var tracer = null;
665
+ var isInitialized = false;
666
+ function initializeTracing(config = {}) {
667
+ if (isInitialized) {
668
+ return;
669
+ }
670
+ const { enabled = true, serviceName = "mcpc-sampling", serviceVersion = "0.2.0", exportTo = "console", otlpEndpoint = "http://localhost:4318/v1/traces", otlpHeaders = {} } = config;
671
+ if (!enabled) {
672
+ isInitialized = true;
673
+ return;
674
+ }
675
+ const resource = Resource.default().merge(new Resource({
676
+ [ATTR_SERVICE_NAME]: serviceName,
677
+ [ATTR_SERVICE_VERSION]: serviceVersion
678
+ }));
679
+ tracerProvider = new NodeTracerProvider({
680
+ resource
681
+ });
682
+ if (exportTo === "console") {
683
+ tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
684
+ } else if (exportTo === "otlp") {
685
+ const otlpExporter = new OTLPTraceExporter({
686
+ url: otlpEndpoint,
687
+ headers: otlpHeaders
688
+ });
689
+ tracerProvider.addSpanProcessor(new BatchSpanProcessor(otlpExporter));
690
+ }
691
+ tracerProvider.register();
692
+ tracer = trace.getTracer(serviceName, serviceVersion);
693
+ isInitialized = true;
694
+ }
695
+ function getTracer() {
696
+ if (!isInitialized) {
697
+ initializeTracing();
698
+ }
699
+ return tracer;
700
+ }
701
+ function startSpan(name, attributes, parent) {
702
+ const tracer2 = getTracer();
703
+ const ctx = parent ? trace.setSpan(context.active(), parent) : void 0;
704
+ return tracer2.startSpan(name, {
705
+ attributes
706
+ }, ctx);
707
+ }
708
+ function endSpan(span, error) {
709
+ if (error) {
710
+ span.setStatus({
711
+ code: SpanStatusCode.ERROR,
712
+ message: error.message
713
+ });
714
+ span.recordException(error);
715
+ } else {
716
+ span.setStatus({
717
+ code: SpanStatusCode.OK
718
+ });
719
+ }
720
+ span.end();
721
+ }
722
+
723
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
724
+ import process3 from "node:process";
725
+ var AgenticExecutor = class {
726
+ name;
727
+ allToolNames;
728
+ toolNameToDetailList;
729
+ server;
730
+ logger;
731
+ tracingEnabled;
732
+ toolSchemaMap;
733
+ constructor(name, allToolNames, toolNameToDetailList, server) {
734
+ this.name = name;
735
+ this.allToolNames = allToolNames;
736
+ this.toolNameToDetailList = toolNameToDetailList;
737
+ this.server = server;
738
+ this.tracingEnabled = false;
739
+ this.logger = createLogger(`mcpc.agentic.${name}`, server);
740
+ this.toolSchemaMap = new Map(toolNameToDetailList);
741
+ try {
742
+ this.tracingEnabled = process3.env.MCPC_TRACING_ENABLED === "true";
743
+ if (this.tracingEnabled) {
744
+ initializeTracing({
745
+ enabled: true,
746
+ serviceName: `mcpc-agentic-${name}`,
747
+ exportTo: process3.env.MCPC_TRACING_EXPORT ?? "otlp",
748
+ otlpEndpoint: process3.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
749
+ });
750
+ }
751
+ } catch {
752
+ this.tracingEnabled = false;
753
+ }
754
+ }
755
+ async execute(args, schema, parentSpan) {
756
+ const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
757
+ agent: this.name,
758
+ tool: String(args.tool ?? "unknown"),
759
+ args: JSON.stringify(args)
760
+ }, parentSpan ?? void 0) : null;
761
+ try {
762
+ const validationResult = this.validate(args, schema);
763
+ if (!validationResult.valid) {
764
+ if (executeSpan) {
765
+ executeSpan.setAttributes({
766
+ validationError: true,
767
+ errorMessage: validationResult.error || "Validation failed"
768
+ });
769
+ endSpan(executeSpan);
770
+ }
771
+ this.logger.warning({
772
+ message: "Validation failed",
773
+ tool: args.tool,
774
+ error: validationResult.error
775
+ });
776
+ return {
777
+ content: [
778
+ {
779
+ type: "text",
780
+ text: CompiledPrompts.errorResponse({
781
+ errorMessage: validationResult.error || "Validation failed"
782
+ })
783
+ }
784
+ ],
785
+ isError: true
786
+ };
787
+ }
788
+ const tool2 = args.tool;
789
+ if (tool2 === "man") {
790
+ const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, {});
791
+ const manSchema = createArgsDef.forMan(this.allToolNames);
792
+ const manValidation = validateSchema(args.args ?? {}, manSchema);
793
+ if (!manValidation.valid) {
794
+ return {
795
+ content: [
796
+ {
797
+ type: "text",
798
+ text: `Invalid args for "man": ${manValidation.error}`
799
+ }
800
+ ],
801
+ isError: true
802
+ };
803
+ }
804
+ const argsObj = args.args;
805
+ return this.handleManCommand(argsObj.tools, executeSpan);
806
+ }
807
+ const toolArgs = args.args || {};
808
+ return await this.executeTool(tool2, toolArgs, executeSpan);
809
+ } catch (error) {
810
+ if (executeSpan) {
811
+ endSpan(executeSpan, error);
812
+ }
813
+ this.logger.error({
814
+ message: "Unexpected error in execute",
815
+ error: String(error)
816
+ });
817
+ return {
818
+ content: [
819
+ {
820
+ type: "text",
821
+ text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
822
+ }
823
+ ],
824
+ isError: true
825
+ };
826
+ }
827
+ }
828
+ /**
829
+ * Handle `man` command - return schemas for requested tools
830
+ * @param requestedTools - Array of tool names (already validated via JSON Schema)
831
+ */
832
+ handleManCommand(requestedTools, executeSpan) {
833
+ if (executeSpan) {
834
+ executeSpan.setAttributes({
835
+ toolType: "man",
836
+ requestedTools: requestedTools.join(",")
837
+ });
838
+ }
839
+ const schemas = requestedTools.map((toolName) => {
840
+ const toolDetail = this.toolSchemaMap.get(toolName);
841
+ if (toolDetail) {
842
+ const cleanedSchema = cleanToolSchema(toolDetail);
843
+ return `<tool_definition name="${toolName}">
844
+ ${JSON.stringify(cleanedSchema, null, 2)}
845
+ </tool_definition>`;
846
+ }
847
+ return null;
848
+ }).filter(Boolean);
849
+ if (executeSpan) {
850
+ executeSpan.setAttributes({
851
+ schemasReturned: schemas.length,
852
+ success: true
853
+ });
854
+ endSpan(executeSpan);
855
+ }
856
+ return {
857
+ content: [
858
+ {
859
+ type: "text",
860
+ text: schemas.length > 0 ? schemas.join("\n\n") : "No schemas found for requested tools."
861
+ }
862
+ ]
863
+ };
864
+ }
865
+ /**
866
+ * Execute a tool with runtime validation
867
+ */
868
+ async executeTool(tool2, toolArgs, executeSpan) {
869
+ const externalTool = this.toolNameToDetailList.find(([name]) => name === tool2);
870
+ if (externalTool) {
871
+ const [, toolDetail] = externalTool;
872
+ if (executeSpan) {
873
+ executeSpan.setAttributes({
874
+ toolType: "external",
875
+ selectedTool: tool2
876
+ });
877
+ }
878
+ if (toolDetail.inputSchema) {
879
+ const rawSchema = extractJsonSchema(toolDetail.inputSchema);
880
+ const validation = validateSchema(toolArgs, rawSchema);
881
+ if (!validation.valid) {
882
+ if (executeSpan) {
883
+ executeSpan.setAttributes({
884
+ validationError: true,
885
+ errorMessage: validation.error
886
+ });
887
+ endSpan(executeSpan);
888
+ }
889
+ return {
890
+ content: [
891
+ {
892
+ type: "text",
893
+ text: `Parameter validation failed for "${tool2}": ${validation.error}`
894
+ }
895
+ ],
896
+ isError: true
897
+ };
898
+ }
899
+ }
900
+ this.logger.debug({
901
+ message: "Executing external tool",
902
+ tool: tool2
903
+ });
904
+ const result = await toolDetail.execute(toolArgs);
905
+ if (executeSpan) {
906
+ executeSpan.setAttributes({
907
+ success: true,
908
+ isError: !!result.isError,
909
+ resultContentLength: result.content?.length || 0
910
+ });
911
+ endSpan(executeSpan);
912
+ }
913
+ return result;
914
+ }
915
+ if (this.allToolNames.includes(tool2)) {
916
+ if (executeSpan) {
917
+ executeSpan.setAttributes({
918
+ toolType: "internal",
919
+ selectedTool: tool2
920
+ });
921
+ }
922
+ this.logger.debug({
923
+ message: "Executing internal tool",
924
+ tool: tool2
925
+ });
926
+ try {
927
+ const result = await this.server.callTool(tool2, toolArgs);
928
+ const callToolResult = result ?? {
929
+ content: []
930
+ };
931
+ if (executeSpan) {
932
+ executeSpan.setAttributes({
933
+ success: true,
934
+ isError: !!callToolResult.isError,
935
+ resultContentLength: callToolResult.content?.length || 0
936
+ });
937
+ endSpan(executeSpan);
938
+ }
939
+ return callToolResult;
940
+ } catch (error) {
941
+ if (executeSpan) {
942
+ endSpan(executeSpan, error);
943
+ }
944
+ this.logger.error({
945
+ message: "Error executing internal tool",
946
+ tool: tool2,
947
+ error: String(error)
948
+ });
949
+ return {
950
+ content: [
951
+ {
952
+ type: "text",
953
+ text: `Error executing tool "${tool2}": ${error instanceof Error ? error.message : String(error)}`
954
+ }
955
+ ],
956
+ isError: true
957
+ };
958
+ }
959
+ }
960
+ if (executeSpan) {
961
+ executeSpan.setAttributes({
962
+ toolType: "not_found",
963
+ tool: tool2
964
+ });
965
+ endSpan(executeSpan);
966
+ }
967
+ return {
968
+ content: [
969
+ {
970
+ type: "text",
971
+ text: `Tool "${tool2}" not found. Available tools: ${this.allToolNames.join(", ")}`
972
+ }
973
+ ],
974
+ isError: true
975
+ };
976
+ }
977
+ validate(args, schema) {
978
+ return validateSchema(args, schema);
979
+ }
980
+ };
981
+
982
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
983
+ function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
984
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
985
+ const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
986
+ description = CompiledPrompts.autonomousExecution({
987
+ toolName: name,
988
+ description
989
+ });
990
+ const agenticArgsDef = createArgsDef.forAgentic(allToolNames);
991
+ const argsDef = agenticArgsDef;
992
+ const schema = allToolNames.length > 0 ? argsDef : {
993
+ type: "object",
994
+ properties: {}
995
+ };
996
+ server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
997
+ return await agenticExecutor.execute(args, schema);
998
+ });
999
+ }
1000
+
1001
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-plugin.js
1002
+ var createAgenticModePlugin = () => ({
1003
+ name: "mode-agentic",
1004
+ version: "2.0.0",
1005
+ // Only apply to agentic mode
1006
+ apply: "agentic",
1007
+ // Register the agent tool
1008
+ registerAgentTool: (context2) => {
1009
+ registerAgenticTool(context2.server, {
1010
+ description: context2.description,
1011
+ name: context2.name,
1012
+ allToolNames: context2.allToolNames,
1013
+ depGroups: context2.depGroups,
1014
+ toolNameToDetailList: context2.toolNameToDetailList
1015
+ });
1016
+ }
1017
+ });
1018
+ var mode_agentic_plugin_default = createAgenticModePlugin();
1019
+
1020
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/utils.js
1021
+ function convertAISDKToMCPMessages(prompt) {
1022
+ const messages = [];
1023
+ for (const msg of prompt) {
1024
+ if (msg.role === "system") continue;
1025
+ const role = msg.role === "assistant" ? "assistant" : "user";
1026
+ const textParts = msg.content.filter((c) => c.type === "text");
1027
+ const toolCalls = msg.content.filter((c) => c.type === "tool-call");
1028
+ const toolResults = msg.content.filter((c) => c.type === "tool-result");
1029
+ const parts = [];
1030
+ if (textParts.length > 0) {
1031
+ parts.push(textParts.map((c) => c.text).join("\n"));
1032
+ }
1033
+ if (toolCalls.length > 0) {
1034
+ const calls = toolCalls.map((c) => {
1035
+ const call = c;
1036
+ const toolArgs = call.args ?? call.input ?? {};
1037
+ return `<use_tool tool="${call.toolName}">
1038
+ ${JSON.stringify(toolArgs)}
1039
+ </use_tool>`;
1040
+ });
1041
+ parts.push(calls.join("\n"));
1042
+ }
1043
+ if (toolResults.length > 0) {
1044
+ const results = toolResults.map((c) => {
1045
+ const result = c;
1046
+ const resultValue = result.result ?? result.output ?? "undefined";
1047
+ const output = JSON.stringify(resultValue);
1048
+ return `Tool "${result.toolName}" result:
1049
+ ${output}`;
1050
+ });
1051
+ parts.push(results.join("\n\n"));
1052
+ }
1053
+ const text = parts.join("\n\n");
1054
+ if (text) {
1055
+ messages.push({
1056
+ role,
1057
+ content: {
1058
+ type: "text",
1059
+ text
1060
+ }
1061
+ });
1062
+ }
1063
+ }
1064
+ return messages;
1065
+ }
1066
+ function convertMCPStopReasonToAISDK(stopReason) {
1067
+ if (stopReason === "endTurn" || stopReason === "stopSequence") {
1068
+ return "stop";
1069
+ }
1070
+ if (stopReason === "maxTokens") return "length";
1071
+ return stopReason ?? "unknown";
1072
+ }
1073
+
1074
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/language-model.js
1075
+ var DEFAULT_MAX_TOKENS = 128e3;
1076
+ var MCPSamplingLanguageModel = class {
1077
+ specificationVersion = "v2";
1078
+ provider;
1079
+ modelId;
1080
+ supportedUrls = {};
1081
+ server;
1082
+ modelPreferences;
1083
+ maxTokens;
1084
+ constructor(config) {
1085
+ this.server = config.server;
1086
+ this.modelId = "";
1087
+ this.provider = "mcp-client";
1088
+ this.modelPreferences = config.modelPreferences;
1089
+ this.maxTokens = config.maxTokens ?? DEFAULT_MAX_TOKENS;
1090
+ }
1091
+ /**
1092
+ * Generate a response using MCP's createMessage capability
1093
+ */
1094
+ async doGenerate(options) {
1095
+ const useNativeTools = this.supportsSamplingTools();
1096
+ this.server.sendLoggingMessage({
1097
+ level: "info",
1098
+ data: `Client supports native tools: ${useNativeTools}`
1099
+ });
1100
+ const messages = this.convertMessages(options.prompt, useNativeTools);
1101
+ this.server.sendLoggingMessage({
1102
+ level: "info",
1103
+ data: `Converted messages for MCP: ${JSON.stringify(messages)}`
1104
+ });
1105
+ let systemPrompt;
1106
+ for (const msg of options.prompt) {
1107
+ if (msg.role === "system") {
1108
+ systemPrompt = msg.content;
1109
+ break;
1110
+ }
1111
+ }
1112
+ this.server.sendLoggingMessage({
1113
+ level: "info",
1114
+ data: `Client supports native tools: ${useNativeTools}`
1115
+ });
1116
+ systemPrompt = this.injectResponseFormatInstructions(systemPrompt, options.responseFormat, useNativeTools);
1117
+ systemPrompt = this.injectToolInstructions(systemPrompt, options.tools, useNativeTools);
1118
+ const createMessageParams = {
1119
+ systemPrompt,
1120
+ messages,
1121
+ maxTokens: options.maxOutputTokens ?? this.maxTokens,
1122
+ modelPreferences: this.modelPreferences
1123
+ };
1124
+ if (useNativeTools && options.tools && options.tools.length > 0) {
1125
+ createMessageParams.tools = this.convertAISDKToolsToMCP(options.tools);
1126
+ createMessageParams.toolChoice = {
1127
+ mode: "auto"
1128
+ };
1129
+ this.server.sendLoggingMessage({
1130
+ level: "info",
1131
+ data: `Converted ${options.tools.length} tools to MCP format: ${JSON.stringify(createMessageParams.tools?.map((t) => t.name))}`
1132
+ });
1133
+ } else if (options.tools && options.tools.length > 0) {
1134
+ this.server.sendLoggingMessage({
1135
+ level: "info",
1136
+ data: `Tools provided but not using native mode - injecting into system prompt instead`
1137
+ });
1138
+ }
1139
+ this.server.sendLoggingMessage({
1140
+ level: "info",
1141
+ data: `Calling createMessage with params: ${JSON.stringify({
1142
+ hasSystemPrompt: !!systemPrompt,
1143
+ hasTools: !!createMessageParams.tools,
1144
+ toolCount: createMessageParams.tools?.length || 0,
1145
+ createMessageParams
1146
+ }, null, 2)}`
1147
+ });
1148
+ const result = await this.server.createMessage(createMessageParams);
1149
+ this.server.sendLoggingMessage({
1150
+ level: "info",
1151
+ data: `createMessage result: ${JSON.stringify({
1152
+ contentType: result.content.type,
1153
+ stopReason: result.stopReason,
1154
+ text: result.content
1155
+ })}`
1156
+ });
1157
+ const content = [];
1158
+ if (useNativeTools) {
1159
+ const contentArray = Array.isArray(result.content) ? result.content : [
1160
+ result.content
1161
+ ];
1162
+ for (const block of contentArray) {
1163
+ if (block.type === "text" && "text" in block) {
1164
+ content.push({
1165
+ type: "text",
1166
+ text: block.text
1167
+ });
1168
+ } else if (block.type === "tool_use" && "id" in block && "name" in block) {
1169
+ const toolInput = block.input || {};
1170
+ content.push({
1171
+ type: "tool-call",
1172
+ toolCallId: block.id,
1173
+ toolName: block.name,
1174
+ input: JSON.stringify(toolInput)
1175
+ });
1176
+ }
1177
+ }
1178
+ } else {
1179
+ if (result.content.type === "text" && result.content.text) {
1180
+ const { text, toolCalls } = this.extractToolCalls(result.content.text, options.tools);
1181
+ if (text.trim()) {
1182
+ const textContent = {
1183
+ type: "text",
1184
+ text
1185
+ };
1186
+ content.push(textContent);
1187
+ }
1188
+ content.push(...toolCalls);
1189
+ }
1190
+ }
1191
+ const finishReason = this.mapStopReason(result.stopReason);
1192
+ return {
1193
+ content,
1194
+ finishReason,
1195
+ usage: {
1196
+ inputTokens: void 0,
1197
+ outputTokens: void 0,
1198
+ totalTokens: 0
1199
+ },
1200
+ request: {
1201
+ body: JSON.stringify({
1202
+ systemPrompt,
1203
+ messages
1204
+ })
1205
+ },
1206
+ response: {
1207
+ modelId: result.model
1208
+ },
1209
+ warnings: []
1210
+ };
1211
+ }
1212
+ /**
1213
+ * Stream a response using MCP's createMessage capability
1214
+ *
1215
+ * Since MCP doesn't support native streaming, we generate the full response
1216
+ * and emit it as stream events following AI SDK's protocol.
1217
+ */
1218
+ async doStream(options) {
1219
+ const result = await this.doGenerate(options);
1220
+ const stream = new ReadableStream({
1221
+ start(controller) {
1222
+ if (result.response?.modelId) {
1223
+ controller.enqueue({
1224
+ type: "response-metadata",
1225
+ modelId: result.response.modelId,
1226
+ ...result.response.headers && {
1227
+ headers: result.response.headers
1228
+ }
1229
+ });
1230
+ }
1231
+ let textIndex = 0;
1232
+ for (const part of result.content) {
1233
+ if (part.type === "text") {
1234
+ const id = `text-${++textIndex}`;
1235
+ controller.enqueue({
1236
+ type: "text-start",
1237
+ id
1238
+ });
1239
+ controller.enqueue({
1240
+ type: "text-delta",
1241
+ id,
1242
+ delta: part.text
1243
+ });
1244
+ controller.enqueue({
1245
+ type: "text-end",
1246
+ id
1247
+ });
1248
+ } else if (part.type === "tool-call") {
1249
+ controller.enqueue({
1250
+ type: "tool-call",
1251
+ toolCallId: part.toolCallId,
1252
+ toolName: part.toolName,
1253
+ input: part.input
1254
+ });
1255
+ }
1256
+ }
1257
+ controller.enqueue({
1258
+ type: "finish",
1259
+ finishReason: result.finishReason,
1260
+ usage: result.usage
1261
+ });
1262
+ controller.close();
1263
+ }
1264
+ });
1265
+ return {
1266
+ stream,
1267
+ request: result.request,
1268
+ warnings: result.warnings
1269
+ };
1270
+ }
1271
+ /**
1272
+ * Convert AI SDK messages to MCP sampling format
1273
+ */
1274
+ convertMessages(prompt, useNativeTools) {
1275
+ if (!useNativeTools) {
1276
+ return convertAISDKToMCPMessages(prompt);
1277
+ }
1278
+ const messages = [];
1279
+ for (const msg of prompt) {
1280
+ if (msg.role === "system") continue;
1281
+ const role = msg.role === "assistant" ? "assistant" : "user";
1282
+ const contentBlocks = [];
1283
+ for (const part of msg.content) {
1284
+ if (part.type === "text") {
1285
+ contentBlocks.push({
1286
+ type: "text",
1287
+ text: part.text
1288
+ });
1289
+ } else if (part.type === "tool-call") {
1290
+ const call = part;
1291
+ contentBlocks.push({
1292
+ type: "tool_use",
1293
+ id: call.toolCallId,
1294
+ name: call.toolName,
1295
+ input: call.args ?? call.input ?? {}
1296
+ });
1297
+ } else if (part.type === "tool-result") {
1298
+ const result = part;
1299
+ contentBlocks.push({
1300
+ type: "tool_result",
1301
+ toolUseId: result.toolCallId,
1302
+ // TODO: Handle different result types properly
1303
+ content: [
1304
+ {
1305
+ type: "text",
1306
+ text: result.output.type === "text" ? result.output.value?.toString() : JSON.stringify(result.output)
1307
+ }
1308
+ ]
1309
+ });
1310
+ }
1311
+ }
1312
+ if (contentBlocks.length > 0) {
1313
+ messages.push({
1314
+ role,
1315
+ content: contentBlocks
1316
+ });
1317
+ }
1318
+ }
1319
+ return messages;
1320
+ }
1321
+ /**
1322
+ * Map MCP stop reason to AI SDK finish reason
1323
+ */
1324
+ mapStopReason(stopReason) {
1325
+ return convertMCPStopReasonToAISDK(stopReason);
1326
+ }
1327
+ /**
1328
+ * Check if client supports native tool use in sampling
1329
+ */
1330
+ supportsSamplingTools() {
1331
+ const capabilities = this.server.getClientCapabilities();
1332
+ const supportsTools = !!capabilities?.sampling?.tools;
1333
+ this.server.sendLoggingMessage({
1334
+ level: "info",
1335
+ data: `Client capabilities check: sampling=${!!capabilities?.sampling}, tools=${supportsTools}`
1336
+ });
1337
+ return supportsTools;
1338
+ }
1339
+ /**
1340
+ * Convert AI SDK tools to MCP Tool format
1341
+ */
1342
+ convertAISDKToolsToMCP(tools) {
1343
+ if (!tools || tools.length === 0) return [];
1344
+ return tools.filter((tool2) => tool2.type === "function").map((tool2) => {
1345
+ const toolAny = tool2;
1346
+ return {
1347
+ name: tool2.name,
1348
+ description: toolAny.description || `Tool: ${tool2.name}`,
1349
+ inputSchema: {
1350
+ type: "object",
1351
+ ...toolAny.inputSchema || toolAny.parameters
1352
+ }
1353
+ };
1354
+ });
1355
+ }
1356
+ /**
1357
+ * Inject response format instructions into system prompt
1358
+ *
1359
+ * Only injects formatting instructions in JSON fallback mode.
1360
+ * In native tools mode, structured output is handled by the provider.
1361
+ */
1362
+ injectResponseFormatInstructions(systemPrompt, responseFormat, useNativeTools) {
1363
+ if (!responseFormat) {
1364
+ return systemPrompt;
1365
+ }
1366
+ if (useNativeTools) {
1367
+ return systemPrompt;
1368
+ }
1369
+ let enhanced = systemPrompt || "";
1370
+ if (responseFormat.type === "json") {
1371
+ const jsonPrompt = `
1372
+
1373
+ IMPORTANT: You MUST respond with valid JSON only. Do not include any text before or after the JSON.
1374
+ - Your response must be a valid JSON object
1375
+ - Do not wrap the JSON in markdown code blocks
1376
+ - Do not include explanations or comments
1377
+ - Ensure all JSON is properly formatted and parseable`;
1378
+ enhanced = enhanced ? `${enhanced}${jsonPrompt}` : jsonPrompt.trim();
1379
+ if (responseFormat.schema) {
1380
+ const schemaInfo = `
1381
+ - Follow this JSON schema structure: ${JSON.stringify(responseFormat.schema)}`;
1382
+ enhanced += schemaInfo;
1383
+ }
1384
+ }
1385
+ return enhanced || void 0;
1386
+ }
1387
+ /**
1388
+ * Inject tool definitions into system prompt
1389
+ *
1390
+ * WORKAROUND: MCP sampling currently doesn't support native tools parameter.
1391
+ * This method injects tool descriptions and usage instructions into the system prompt.
1392
+ *
1393
+ * TODO: Remove this workaround when MCP protocol adds native support for:
1394
+ * - tools parameter in createMessage
1395
+ * - Tool calling and function execution
1396
+ * - Structured tool responses
1397
+ */
1398
+ injectToolInstructions(systemPrompt, tools, useNativeTools) {
1399
+ if (!tools || tools.length === 0) {
1400
+ return systemPrompt;
1401
+ }
1402
+ if (useNativeTools) {
1403
+ this.server.sendLoggingMessage({
1404
+ level: "info",
1405
+ data: `Using native tools mode - skipping XML tool injection`
1406
+ });
1407
+ return systemPrompt;
1408
+ }
1409
+ this.server.sendLoggingMessage({
1410
+ level: "info",
1411
+ data: `Injecting ${tools.length} tools into system prompt (fallback mode)`
1412
+ });
1413
+ let enhanced = systemPrompt || "";
1414
+ const toolsPrompt = `
1415
+
1416
+ AVAILABLE TOOLS:
1417
+ You have access to the following tools. To use a tool, respond with this XML format:
1418
+ <use_tool tool="tool_name">
1419
+ {"param1": "value1", "param2": "value2"}
1420
+ </use_tool>
1421
+
1422
+ Follow the JSON schema definition for each tool's parameters.
1423
+ You can use multiple tools in one response. DO NOT include text before or after tool calls - wait for the tool results first.
1424
+
1425
+ Tools:`;
1426
+ const toolDescriptions = tools.map((tool2) => {
1427
+ if (tool2.type === "function") {
1428
+ const toolAny = tool2;
1429
+ const description = toolAny.description || "No description provided";
1430
+ const schema = toolAny.inputSchema || toolAny.parameters;
1431
+ const params = schema ? `
1432
+ JSON Schema: ${JSON.stringify(schema, null, 2)}` : "";
1433
+ return `
1434
+ - ${tool2.name}: ${description}${params}`;
1435
+ } else if (tool2.type === "provider-defined") {
1436
+ return `
1437
+ - ${tool2.name}: ${tool2.id || "No description provided"}`;
1438
+ }
1439
+ return "";
1440
+ }).filter(Boolean).join("");
1441
+ enhanced = enhanced ? `${enhanced}${toolsPrompt}${toolDescriptions}` : `${toolsPrompt}${toolDescriptions}`.trim();
1442
+ return enhanced || void 0;
1443
+ }
1444
+ /**
1445
+ * Extract tool calls from LLM response text
1446
+ *
1447
+ * Parses XML-style tool call tags from the response:
1448
+ * <use_tool tool="tool_name">{"arg": "value"}</use_tool>
1449
+ */
1450
+ extractToolCalls(responseText, tools) {
1451
+ if (!tools || tools.length === 0) {
1452
+ return {
1453
+ text: responseText,
1454
+ toolCalls: []
1455
+ };
1456
+ }
1457
+ const toolCalls = [];
1458
+ const toolCallRegex = /<use_tool\s+tool="([^"]+)">([\s\S]*?)<\/use_tool>/g;
1459
+ let match;
1460
+ let lastIndex = 0;
1461
+ const textParts = [];
1462
+ let callIndex = 0;
1463
+ while ((match = toolCallRegex.exec(responseText)) !== null) {
1464
+ textParts.push(responseText.slice(lastIndex, match.index));
1465
+ const toolName = match[1];
1466
+ const argsText = match[2].trim?.();
1467
+ toolCalls.push({
1468
+ type: "tool-call",
1469
+ toolCallId: `call_${Date.now()}_${callIndex++}`,
1470
+ toolName,
1471
+ input: argsText
1472
+ });
1473
+ lastIndex = match.index + match[0].length;
1474
+ }
1475
+ textParts.push(responseText.slice(lastIndex));
1476
+ const text = textParts.join("").trim();
1477
+ return {
1478
+ text,
1479
+ toolCalls
1480
+ };
1481
+ }
1482
+ };
1483
+
1484
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/provider.js
1485
+ var MCPSamplingProvider = class {
1486
+ config;
1487
+ constructor(config) {
1488
+ this.config = config;
1489
+ }
1490
+ /**
1491
+ * Create a language model instance for a specific MCP tool/agent
1492
+ *
1493
+ * @param options - Optional configuration overrides
1494
+ * @returns A LanguageModelV2 instance
1495
+ */
1496
+ languageModel(options) {
1497
+ return new MCPSamplingLanguageModel({
1498
+ server: this.config.server,
1499
+ modelPreferences: options?.modelPreferences,
1500
+ maxTokens: this.config.maxTokens
1501
+ });
1502
+ }
1503
+ /**
1504
+ * Shorthand for creating a language model
1505
+ */
1506
+ call(options) {
1507
+ return this.languageModel(options);
1508
+ }
1509
+ };
1510
+
1511
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/client-sampling.js
1512
+ import { CreateMessageRequestSchema } from "@modelcontextprotocol/sdk/types.js";
1513
+
1514
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/base-ai-executor.js
1515
+ import { trace as trace2 } from "@opentelemetry/api";
1516
+ import { jsonSchema as jsonSchema2, stepCountIs, streamText, tool } from "ai";
1517
+ var BaseAIExecutor = class {
1518
+ config;
1519
+ tracer;
1520
+ logger;
1521
+ constructor(config, server) {
1522
+ this.config = {
1523
+ maxSteps: 50,
1524
+ tracingEnabled: true,
1525
+ ...config
1526
+ };
1527
+ this.tracer = trace2.getTracer(`mcpc.ai.${config.name}`);
1528
+ this.logger = createLogger(`mcpc.ai.${config.name}`, server);
1529
+ }
1530
+ execute(args) {
1531
+ if (this.config.tracingEnabled) {
1532
+ return this.executeWithTracing(args);
1533
+ }
1534
+ return this.executeCore(args);
1535
+ }
1536
+ executeWithTracing(args) {
1537
+ return this.tracer.startActiveSpan(`mcpc.ai.${this.config.name}`, async (span) => {
1538
+ try {
1539
+ span.setAttributes({
1540
+ "mcpc.executor": this.config.name,
1541
+ "mcpc.type": this.getExecutorType()
1542
+ });
1543
+ const result = await this.executeCore(args, span);
1544
+ span.setAttributes({
1545
+ "mcpc.error": !!result.isError
1546
+ });
1547
+ return result;
1548
+ } catch (error) {
1549
+ span.recordException(error);
1550
+ throw error;
1551
+ } finally {
1552
+ span.end();
1553
+ }
1554
+ });
1555
+ }
1556
+ async executeCore(args, span) {
1557
+ try {
1558
+ const result = streamText({
1559
+ model: this.getModel(),
1560
+ system: this.buildSystemPrompt(args),
1561
+ messages: [
1562
+ {
1563
+ role: "user",
1564
+ content: args.prompt
1565
+ }
1566
+ ],
1567
+ tools: this.buildTools(),
1568
+ stopWhen: stepCountIs(this.config.maxSteps),
1569
+ experimental_telemetry: this.config.tracingEnabled ? {
1570
+ isEnabled: true,
1571
+ functionId: `mcpc.${this.config.name}`,
1572
+ tracer: this.tracer
1573
+ } : void 0,
1574
+ onStepFinish: (step) => {
1575
+ if (span) {
1576
+ span.addEvent("step", {
1577
+ tools: step.toolCalls?.length ?? 0,
1578
+ reason: step.finishReason ?? ""
1579
+ });
1580
+ }
1581
+ }
1582
+ });
1583
+ return {
1584
+ content: [
1585
+ {
1586
+ type: "text",
1587
+ text: await result.text || `Completed in ${(await result.steps)?.length ?? "unknown"} step(s).`
1588
+ }
1589
+ ],
1590
+ isError: false
1591
+ };
1592
+ } catch (error) {
1593
+ this.logger.error({
1594
+ message: "Execution error",
1595
+ error
1596
+ });
1597
+ return {
1598
+ content: [
1599
+ {
1600
+ type: "text",
1601
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
1602
+ }
1603
+ ],
1604
+ isError: true
1605
+ };
1606
+ }
1607
+ }
1608
+ buildSystemPrompt(args) {
1609
+ return CompiledPrompts.aiLoopSystem({
1610
+ toolName: this.config.name,
1611
+ description: this.config.description,
1612
+ rules: this.getRules(),
1613
+ context: this.formatContext(args.context)
1614
+ });
1615
+ }
1616
+ getRules() {
1617
+ return `1. Use tools to complete the user's request
1618
+ 2. Review results after each tool call
1619
+ 3. Adapt your approach based on outcomes
1620
+ 4. Continue until task is complete
1621
+ 5. When complete, provide a summary WITHOUT calling more tools`;
1622
+ }
1623
+ formatContext(context2) {
1624
+ if (!context2 || Object.keys(context2).length === 0) {
1625
+ return "";
1626
+ }
1627
+ return `
1628
+
1629
+ <context>
1630
+ ${JSON.stringify(context2, null, 2)}
1631
+ </context>`;
1632
+ }
1633
+ convertToAISDKTool(name, toolDetail, execute) {
1634
+ const cleanedSchema = toolDetail.inputSchema ? cleanToolSchema(toolDetail.inputSchema) : {
1635
+ type: "object"
1636
+ };
1637
+ return tool({
1638
+ description: toolDetail.description || `Tool: ${name}`,
1639
+ inputSchema: jsonSchema2(cleanedSchema),
1640
+ execute
1641
+ });
1642
+ }
1643
+ };
1644
+
1645
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-executor.js
1646
+ var AISamplingExecutor = class extends BaseAIExecutor {
1647
+ server;
1648
+ tools;
1649
+ providerOptions;
1650
+ maxTokens;
1651
+ model = null;
1652
+ constructor(config) {
1653
+ super(config, "callTool" in config.server ? config.server : void 0);
1654
+ this.server = config.server;
1655
+ this.tools = config.tools;
1656
+ this.providerOptions = config.providerOptions;
1657
+ this.maxTokens = config.maxTokens;
1658
+ }
1659
+ initProvider() {
1660
+ if (!this.model) {
1661
+ const provider = new MCPSamplingProvider({
1662
+ server: this.server,
1663
+ maxTokens: this.maxTokens
1664
+ });
1665
+ this.model = provider.languageModel(this.providerOptions);
1666
+ }
1667
+ return this.model;
1668
+ }
1669
+ getModel() {
1670
+ if (!this.model) throw new Error("Model not initialized");
1671
+ return this.model;
1672
+ }
1673
+ getExecutorType() {
1674
+ return "mcp";
1675
+ }
1676
+ buildTools() {
1677
+ const aiTools = {};
1678
+ for (const [name, detail] of this.tools) {
1679
+ aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
1680
+ const result = await this.callTool(name, input);
1681
+ return this.formatResult(result);
1682
+ });
1683
+ }
1684
+ return aiTools;
1685
+ }
1686
+ async callTool(name, input) {
1687
+ if ("callTool" in this.server) {
1688
+ return await this.server.callTool(name, input);
1689
+ }
1690
+ const detail = this.tools.find(([n]) => n === name)?.[1];
1691
+ if (detail?.execute) return await detail.execute(input);
1692
+ throw new Error(`Cannot call tool "${name}"`);
1693
+ }
1694
+ formatResult(result) {
1695
+ const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
1696
+ return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
1697
+ }
1698
+ execute(args) {
1699
+ this.initProvider();
1700
+ return super.execute(args);
1701
+ }
1702
+ };
1703
+
1704
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-registrar.js
1705
+ function registerAISamplingTool(server, params) {
1706
+ const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false, maxTokens } = params;
1707
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1708
+ const executor = new AISamplingExecutor({
1709
+ name,
1710
+ description,
1711
+ server,
1712
+ tools: toolNameToDetailList,
1713
+ providerOptions,
1714
+ maxSteps,
1715
+ tracingEnabled,
1716
+ maxTokens
1717
+ });
1718
+ const toolDescription = CompiledPrompts.samplingToolDescription({
1719
+ toolName: name,
1720
+ description,
1721
+ toolList: allToolNames.map((n) => `- ${n}`).join("\n")
1722
+ });
1723
+ const argsDef = createArgsDef.forSampling();
1724
+ const schema = allToolNames.length > 0 ? argsDef : {
1725
+ type: "object",
1726
+ properties: {}
1727
+ };
1728
+ server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
1729
+ const validationResult = validateSchema(args, schema);
1730
+ if (!validationResult.valid) {
1731
+ return {
1732
+ content: [
1733
+ {
1734
+ type: "text",
1735
+ text: CompiledPrompts.errorResponse({
1736
+ errorMessage: validationResult.error || "Validation failed"
1737
+ })
1738
+ }
1739
+ ],
1740
+ isError: true
1741
+ };
1742
+ }
1743
+ const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
1744
+ return executor.execute({
1745
+ prompt,
1746
+ context: args.context
1747
+ });
1748
+ });
1749
+ }
1750
+
1751
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-ai-sampling-plugin.js
1752
+ var createAISamplingModePlugin = () => ({
1753
+ name: "mode-ai-sampling",
1754
+ version: "1.0.0",
1755
+ apply: "ai_sampling",
1756
+ registerAgentTool: (context2) => {
1757
+ const opts = context2.options;
1758
+ registerAISamplingTool(context2.server, {
1759
+ description: context2.description,
1760
+ name: context2.name,
1761
+ allToolNames: context2.allToolNames,
1762
+ depGroups: context2.depGroups,
1763
+ toolNameToDetailList: context2.toolNameToDetailList,
1764
+ providerOptions: opts.providerOptions,
1765
+ maxSteps: opts.maxSteps,
1766
+ tracingEnabled: opts.tracingEnabled,
1767
+ maxTokens: opts.maxTokens
1768
+ });
1769
+ }
1770
+ });
1771
+ var mode_ai_sampling_plugin_default = createAISamplingModePlugin();
1772
+
1773
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-executor.js
1774
+ import { acpTools, createACPProvider } from "@mcpc-tech/acp-ai-provider";
1775
+ var AIACPExecutor = class extends BaseAIExecutor {
1776
+ acpSettings;
1777
+ tools;
1778
+ provider = null;
1779
+ model = null;
1780
+ constructor(config) {
1781
+ super(config);
1782
+ this.acpSettings = config.acpSettings;
1783
+ this.tools = config.tools;
1784
+ }
1785
+ initProvider() {
1786
+ if (!this.model) {
1787
+ this.provider = createACPProvider(this.acpSettings);
1788
+ this.model = this.provider.languageModel();
1789
+ }
1790
+ return this.model;
1791
+ }
1792
+ getModel() {
1793
+ if (!this.model) throw new Error("Model not initialized");
1794
+ return this.model;
1795
+ }
1796
+ getExecutorType() {
1797
+ return "acp";
1798
+ }
1799
+ buildTools() {
1800
+ const aiTools = {};
1801
+ for (const [name, detail] of this.tools) {
1802
+ if (!detail.execute) continue;
1803
+ aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
1804
+ const result = await detail.execute(input);
1805
+ return this.formatResult(result);
1806
+ });
1807
+ }
1808
+ return acpTools(aiTools);
1809
+ }
1810
+ formatResult(result) {
1811
+ const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
1812
+ return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
1813
+ }
1814
+ execute(args) {
1815
+ this.initProvider();
1816
+ return super.execute(args);
1817
+ }
1818
+ cleanup() {
1819
+ if (this.provider && typeof this.provider.cleanup === "function") {
1820
+ this.provider.cleanup();
1821
+ }
1822
+ this.model = null;
1823
+ this.provider = null;
1824
+ }
1825
+ };
1826
+
1827
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-registrar.js
1828
+ function registerAIACPTool(server, params) {
1829
+ const { name, description, allToolNames, depGroups, toolNameToDetailList, acpSettings, maxSteps = 50, tracingEnabled = false } = params;
1830
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1831
+ const executor = new AIACPExecutor({
1832
+ name,
1833
+ description,
1834
+ acpSettings,
1835
+ tools: toolNameToDetailList,
1836
+ maxSteps,
1837
+ tracingEnabled
1838
+ });
1839
+ const toolDescription = CompiledPrompts.samplingToolDescription({
1840
+ toolName: name,
1841
+ description,
1842
+ toolList: allToolNames.length > 0 ? allToolNames.map((n) => `- ${n}`).join("\n") : "Agent has its own tools"
1843
+ });
1844
+ const argsDef = createArgsDef.forSampling();
1845
+ const schema = allToolNames.length > 0 ? argsDef : {
1846
+ type: "object",
1847
+ properties: {}
1848
+ };
1849
+ server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
1850
+ const validationResult = validateSchema(args, schema);
1851
+ if (!validationResult.valid) {
1852
+ return {
1853
+ content: [
1854
+ {
1855
+ type: "text",
1856
+ text: CompiledPrompts.errorResponse({
1857
+ errorMessage: validationResult.error || "Validation failed"
1858
+ })
1859
+ }
1860
+ ],
1861
+ isError: true
1862
+ };
1863
+ }
1864
+ const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
1865
+ return executor.execute({
1866
+ prompt,
1867
+ context: args.context
1868
+ });
1869
+ });
1870
+ return executor;
1871
+ }
1872
+
1873
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-ai-acp-plugin.js
1874
+ var createAIACPModePlugin = () => ({
1875
+ name: "mode-ai-acp",
1876
+ version: "1.0.0",
1877
+ apply: "ai_acp",
1878
+ registerAgentTool: (context2) => {
1879
+ const opts = context2.options;
1880
+ if (!opts.acpSettings) {
1881
+ throw new Error("ai_acp mode requires acpSettings in options");
1882
+ }
1883
+ registerAIACPTool(context2.server, {
1884
+ description: context2.description,
1885
+ name: context2.name,
1886
+ allToolNames: context2.allToolNames,
1887
+ depGroups: context2.depGroups,
1888
+ toolNameToDetailList: context2.toolNameToDetailList,
1889
+ acpSettings: opts.acpSettings,
1890
+ maxSteps: opts.maxSteps,
1891
+ tracingEnabled: opts.tracingEnabled
1892
+ });
1893
+ }
1894
+ });
1895
+ var mode_ai_acp_plugin_default = createAIACPModePlugin();
1896
+
1897
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
1898
+ import traverse from "json-schema-traverse";
1899
+
1900
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
1901
+ import process4 from "node:process";
1902
+ var isSCF = () => Boolean(process4.env.SCF_RUNTIME || process4.env.PROD_SCF);
1903
+ if (isSCF()) {
1904
+ console.log({
1905
+ isSCF: isSCF(),
1906
+ SCF_RUNTIME: process4.env.SCF_RUNTIME
1907
+ });
1908
+ }
1909
+
1910
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/mcpc__core/src/set-up-mcp-compose.js
1911
+ var markdownAgentLoader = null;
1912
+ function setMarkdownAgentLoader(loader) {
1913
+ markdownAgentLoader = loader;
1914
+ }
1915
+ function isMarkdownFile(path) {
1916
+ return path.endsWith(".md") || path.endsWith(".markdown");
1917
+ }
1918
+
1919
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@mcpc/plugin-markdown-loader/src/markdown-loader.js
1920
+ import { readFile } from "node:fs/promises";
1921
+
1922
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_chars.js
1923
+ var TAB = 9;
1924
+ var LINE_FEED = 10;
1925
+ var CARRIAGE_RETURN = 13;
1926
+ var SPACE = 32;
1927
+ var EXCLAMATION = 33;
1928
+ var DOUBLE_QUOTE = 34;
1929
+ var SHARP = 35;
1930
+ var PERCENT = 37;
1931
+ var AMPERSAND = 38;
1932
+ var SINGLE_QUOTE = 39;
1933
+ var ASTERISK = 42;
1934
+ var PLUS = 43;
1935
+ var COMMA = 44;
1936
+ var MINUS = 45;
1937
+ var DOT = 46;
1938
+ var COLON = 58;
1939
+ var SMALLER_THAN = 60;
1940
+ var GREATER_THAN = 62;
1941
+ var QUESTION = 63;
1942
+ var COMMERCIAL_AT = 64;
1943
+ var LEFT_SQUARE_BRACKET = 91;
1944
+ var BACKSLASH = 92;
1945
+ var RIGHT_SQUARE_BRACKET = 93;
1946
+ var GRAVE_ACCENT = 96;
1947
+ var LEFT_CURLY_BRACKET = 123;
1948
+ var VERTICAL_LINE = 124;
1949
+ var RIGHT_CURLY_BRACKET = 125;
1950
+ function isEOL(c) {
1951
+ return c === LINE_FEED || c === CARRIAGE_RETURN;
1952
+ }
1953
+ function isWhiteSpace(c) {
1954
+ return c === TAB || c === SPACE;
1955
+ }
1956
+ function isWhiteSpaceOrEOL(c) {
1957
+ return isWhiteSpace(c) || isEOL(c);
1958
+ }
1959
+ function isFlowIndicator(c) {
1960
+ return c === COMMA || c === LEFT_SQUARE_BRACKET || c === RIGHT_SQUARE_BRACKET || c === LEFT_CURLY_BRACKET || c === RIGHT_CURLY_BRACKET;
1961
+ }
1962
+
1963
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/binary.js
1964
+ var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
1965
+ function resolveYamlBinary(data) {
1966
+ if (data === null) return false;
1967
+ let code;
1968
+ let bitlen = 0;
1969
+ const max = data.length;
1970
+ const map2 = BASE64_MAP;
1971
+ for (let idx = 0; idx < max; idx++) {
1972
+ code = map2.indexOf(data.charAt(idx));
1973
+ if (code > 64) continue;
1974
+ if (code < 0) return false;
1975
+ bitlen += 6;
1976
+ }
1977
+ return bitlen % 8 === 0;
1978
+ }
1979
+ function constructYamlBinary(data) {
1980
+ const input = data.replace(/[\r\n=]/g, "");
1981
+ const max = input.length;
1982
+ const map2 = BASE64_MAP;
1983
+ const result = [];
1984
+ let bits = 0;
1985
+ for (let idx = 0; idx < max; idx++) {
1986
+ if (idx % 4 === 0 && idx) {
1987
+ result.push(bits >> 16 & 255);
1988
+ result.push(bits >> 8 & 255);
1989
+ result.push(bits & 255);
1990
+ }
1991
+ bits = bits << 6 | map2.indexOf(input.charAt(idx));
1992
+ }
1993
+ const tailbits = max % 4 * 6;
1994
+ if (tailbits === 0) {
1995
+ result.push(bits >> 16 & 255);
1996
+ result.push(bits >> 8 & 255);
1997
+ result.push(bits & 255);
1998
+ } else if (tailbits === 18) {
1999
+ result.push(bits >> 10 & 255);
2000
+ result.push(bits >> 2 & 255);
2001
+ } else if (tailbits === 12) {
2002
+ result.push(bits >> 4 & 255);
2003
+ }
2004
+ return new Uint8Array(result);
2005
+ }
2006
+ function representYamlBinary(object) {
2007
+ const max = object.length;
2008
+ const map2 = BASE64_MAP;
2009
+ let result = "";
2010
+ let bits = 0;
2011
+ for (let idx = 0; idx < max; idx++) {
2012
+ if (idx % 3 === 0 && idx) {
2013
+ result += map2[bits >> 18 & 63];
2014
+ result += map2[bits >> 12 & 63];
2015
+ result += map2[bits >> 6 & 63];
2016
+ result += map2[bits & 63];
2017
+ }
2018
+ bits = (bits << 8) + object[idx];
2019
+ }
2020
+ const tail = max % 3;
2021
+ if (tail === 0) {
2022
+ result += map2[bits >> 18 & 63];
2023
+ result += map2[bits >> 12 & 63];
2024
+ result += map2[bits >> 6 & 63];
2025
+ result += map2[bits & 63];
2026
+ } else if (tail === 2) {
2027
+ result += map2[bits >> 10 & 63];
2028
+ result += map2[bits >> 4 & 63];
2029
+ result += map2[bits << 2 & 63];
2030
+ result += map2[64];
2031
+ } else if (tail === 1) {
2032
+ result += map2[bits >> 2 & 63];
2033
+ result += map2[bits << 4 & 63];
2034
+ result += map2[64];
2035
+ result += map2[64];
2036
+ }
2037
+ return result;
2038
+ }
2039
+ function isBinary(obj) {
2040
+ return obj instanceof Uint8Array;
2041
+ }
2042
+ var binary = {
2043
+ tag: "tag:yaml.org,2002:binary",
2044
+ construct: constructYamlBinary,
2045
+ kind: "scalar",
2046
+ predicate: isBinary,
2047
+ represent: representYamlBinary,
2048
+ resolve: resolveYamlBinary
2049
+ };
2050
+
2051
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/bool.js
2052
+ var YAML_TRUE_BOOLEANS = [
2053
+ "true",
2054
+ "True",
2055
+ "TRUE"
2056
+ ];
2057
+ var YAML_FALSE_BOOLEANS = [
2058
+ "false",
2059
+ "False",
2060
+ "FALSE"
2061
+ ];
2062
+ var YAML_BOOLEANS = [
2063
+ ...YAML_TRUE_BOOLEANS,
2064
+ ...YAML_FALSE_BOOLEANS
2065
+ ];
2066
+ var bool = {
2067
+ tag: "tag:yaml.org,2002:bool",
2068
+ kind: "scalar",
2069
+ defaultStyle: "lowercase",
2070
+ predicate: (value) => typeof value === "boolean" || value instanceof Boolean,
2071
+ construct: (data) => YAML_TRUE_BOOLEANS.includes(data),
2072
+ resolve: (data) => YAML_BOOLEANS.includes(data),
2073
+ represent: {
2074
+ // deno-lint-ignore ban-types
2075
+ lowercase: (object) => {
2076
+ const value = object instanceof Boolean ? object.valueOf() : object;
2077
+ return value ? "true" : "false";
2078
+ },
2079
+ // deno-lint-ignore ban-types
2080
+ uppercase: (object) => {
2081
+ const value = object instanceof Boolean ? object.valueOf() : object;
2082
+ return value ? "TRUE" : "FALSE";
2083
+ },
2084
+ // deno-lint-ignore ban-types
2085
+ camelcase: (object) => {
2086
+ const value = object instanceof Boolean ? object.valueOf() : object;
2087
+ return value ? "True" : "False";
2088
+ }
2089
+ }
2090
+ };
2091
+
2092
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_utils.js
2093
+ function isObject(value) {
2094
+ return value !== null && typeof value === "object";
2095
+ }
2096
+ function isNegativeZero(i) {
2097
+ return i === 0 && Number.NEGATIVE_INFINITY === 1 / i;
2098
+ }
2099
+ function isPlainObject(object) {
2100
+ return Object.prototype.toString.call(object) === "[object Object]";
2101
+ }
2102
+
2103
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/float.js
2104
+ var YAML_FLOAT_PATTERN = new RegExp(
2105
+ // 2.5e4, 2.5 and integers
2106
+ "^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
2107
+ );
2108
+ function resolveYamlFloat(data) {
2109
+ if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
2110
+ // Probably should update regexp & check speed
2111
+ data[data.length - 1] === "_") {
2112
+ return false;
2113
+ }
2114
+ return true;
2115
+ }
2116
+ function constructYamlFloat(data) {
2117
+ let value = data.replace(/_/g, "").toLowerCase();
2118
+ const sign = value[0] === "-" ? -1 : 1;
2119
+ if (value[0] && "+-".includes(value[0])) {
2120
+ value = value.slice(1);
2121
+ }
2122
+ if (value === ".inf") {
2123
+ return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
2124
+ }
2125
+ if (value === ".nan") {
2126
+ return NaN;
2127
+ }
2128
+ return sign * parseFloat(value);
2129
+ }
2130
+ var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
2131
+ function representYamlFloat(object, style) {
2132
+ const value = object instanceof Number ? object.valueOf() : object;
2133
+ if (isNaN(value)) {
2134
+ switch (style) {
2135
+ case "lowercase":
2136
+ return ".nan";
2137
+ case "uppercase":
2138
+ return ".NAN";
2139
+ case "camelcase":
2140
+ return ".NaN";
2141
+ }
2142
+ } else if (Number.POSITIVE_INFINITY === value) {
2143
+ switch (style) {
2144
+ case "lowercase":
2145
+ return ".inf";
2146
+ case "uppercase":
2147
+ return ".INF";
2148
+ case "camelcase":
2149
+ return ".Inf";
2150
+ }
2151
+ } else if (Number.NEGATIVE_INFINITY === value) {
2152
+ switch (style) {
2153
+ case "lowercase":
2154
+ return "-.inf";
2155
+ case "uppercase":
2156
+ return "-.INF";
2157
+ case "camelcase":
2158
+ return "-.Inf";
2159
+ }
2160
+ } else if (isNegativeZero(value)) {
2161
+ return "-0.0";
2162
+ }
2163
+ const res = value.toString(10);
2164
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
2165
+ }
2166
+ function isFloat(object) {
2167
+ if (object instanceof Number) object = object.valueOf();
2168
+ return typeof object === "number" && (object % 1 !== 0 || isNegativeZero(object));
2169
+ }
2170
+ var float = {
2171
+ tag: "tag:yaml.org,2002:float",
2172
+ construct: constructYamlFloat,
2173
+ defaultStyle: "lowercase",
2174
+ kind: "scalar",
2175
+ predicate: isFloat,
2176
+ represent: representYamlFloat,
2177
+ resolve: resolveYamlFloat
2178
+ };
2179
+
2180
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/int.js
2181
+ function isCharCodeInRange(c, lower, upper) {
2182
+ return lower <= c && c <= upper;
2183
+ }
2184
+ function isHexCode(c) {
2185
+ return isCharCodeInRange(c, 48, 57) || // 0-9
2186
+ isCharCodeInRange(c, 65, 70) || // A-F
2187
+ isCharCodeInRange(c, 97, 102);
2188
+ }
2189
+ function isOctCode(c) {
2190
+ return isCharCodeInRange(c, 48, 55);
2191
+ }
2192
+ function isDecCode(c) {
2193
+ return isCharCodeInRange(c, 48, 57);
2194
+ }
2195
+ function resolveYamlInteger(data) {
2196
+ const max = data.length;
2197
+ let index = 0;
2198
+ let hasDigits = false;
2199
+ if (!max) return false;
2200
+ let ch = data[index];
2201
+ if (ch === "-" || ch === "+") {
2202
+ ch = data[++index];
2203
+ }
2204
+ if (ch === "0") {
2205
+ if (index + 1 === max) return true;
2206
+ ch = data[++index];
2207
+ if (ch === "b") {
2208
+ index++;
2209
+ for (; index < max; index++) {
2210
+ ch = data[index];
2211
+ if (ch === "_") continue;
2212
+ if (ch !== "0" && ch !== "1") return false;
2213
+ hasDigits = true;
2214
+ }
2215
+ return hasDigits && ch !== "_";
2216
+ }
2217
+ if (ch === "x") {
2218
+ index++;
2219
+ for (; index < max; index++) {
2220
+ ch = data[index];
2221
+ if (ch === "_") continue;
2222
+ if (!isHexCode(data.charCodeAt(index))) return false;
2223
+ hasDigits = true;
2224
+ }
2225
+ return hasDigits && ch !== "_";
2226
+ }
2227
+ for (; index < max; index++) {
2228
+ ch = data[index];
2229
+ if (ch === "_") continue;
2230
+ if (!isOctCode(data.charCodeAt(index))) return false;
2231
+ hasDigits = true;
2232
+ }
2233
+ return hasDigits && ch !== "_";
2234
+ }
2235
+ if (ch === "_") return false;
2236
+ for (; index < max; index++) {
2237
+ ch = data[index];
2238
+ if (ch === "_") continue;
2239
+ if (!isDecCode(data.charCodeAt(index))) {
2240
+ return false;
2241
+ }
2242
+ hasDigits = true;
2243
+ }
2244
+ if (!hasDigits || ch === "_") return false;
2245
+ return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
2246
+ }
2247
+ function constructYamlInteger(data) {
2248
+ let value = data;
2249
+ if (value.includes("_")) {
2250
+ value = value.replace(/_/g, "");
2251
+ }
2252
+ let sign = 1;
2253
+ let ch = value[0];
2254
+ if (ch === "-" || ch === "+") {
2255
+ if (ch === "-") sign = -1;
2256
+ value = value.slice(1);
2257
+ ch = value[0];
2258
+ }
2259
+ if (value === "0") return 0;
2260
+ if (ch === "0") {
2261
+ if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
2262
+ if (value[1] === "x") return sign * parseInt(value, 16);
2263
+ return sign * parseInt(value, 8);
2264
+ }
2265
+ return sign * parseInt(value, 10);
2266
+ }
2267
+ function isInteger(object) {
2268
+ if (object instanceof Number) object = object.valueOf();
2269
+ return typeof object === "number" && object % 1 === 0 && !isNegativeZero(object);
2270
+ }
2271
+ var int = {
2272
+ tag: "tag:yaml.org,2002:int",
2273
+ construct: constructYamlInteger,
2274
+ defaultStyle: "decimal",
2275
+ kind: "scalar",
2276
+ predicate: isInteger,
2277
+ represent: {
2278
+ // deno-lint-ignore ban-types
2279
+ binary(object) {
2280
+ const value = object instanceof Number ? object.valueOf() : object;
2281
+ return value >= 0 ? `0b${value.toString(2)}` : `-0b${value.toString(2).slice(1)}`;
2282
+ },
2283
+ // deno-lint-ignore ban-types
2284
+ octal(object) {
2285
+ const value = object instanceof Number ? object.valueOf() : object;
2286
+ return value >= 0 ? `0${value.toString(8)}` : `-0${value.toString(8).slice(1)}`;
2287
+ },
2288
+ // deno-lint-ignore ban-types
2289
+ decimal(object) {
2290
+ const value = object instanceof Number ? object.valueOf() : object;
2291
+ return value.toString(10);
2292
+ },
2293
+ // deno-lint-ignore ban-types
2294
+ hexadecimal(object) {
2295
+ const value = object instanceof Number ? object.valueOf() : object;
2296
+ return value >= 0 ? `0x${value.toString(16).toUpperCase()}` : `-0x${value.toString(16).toUpperCase().slice(1)}`;
2297
+ }
2298
+ },
2299
+ resolve: resolveYamlInteger
2300
+ };
2301
+
2302
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/map.js
2303
+ var map = {
2304
+ tag: "tag:yaml.org,2002:map",
2305
+ resolve() {
2306
+ return true;
2307
+ },
2308
+ construct(data) {
2309
+ return data !== null ? data : {};
2310
+ },
2311
+ kind: "mapping"
2312
+ };
2313
+
2314
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/merge.js
2315
+ var merge = {
2316
+ tag: "tag:yaml.org,2002:merge",
2317
+ kind: "scalar",
2318
+ resolve: (data) => data === "<<" || data === null,
2319
+ construct: (data) => data
2320
+ };
2321
+
2322
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/nil.js
2323
+ var nil = {
2324
+ tag: "tag:yaml.org,2002:null",
2325
+ kind: "scalar",
2326
+ defaultStyle: "lowercase",
2327
+ predicate: (object) => object === null,
2328
+ construct: () => null,
2329
+ resolve: (data) => {
2330
+ return data === "~" || data === "null" || data === "Null" || data === "NULL";
2331
+ },
2332
+ represent: {
2333
+ lowercase: () => "null",
2334
+ uppercase: () => "NULL",
2335
+ camelcase: () => "Null"
2336
+ }
2337
+ };
2338
+
2339
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/omap.js
2340
+ function resolveYamlOmap(data) {
2341
+ const objectKeys = /* @__PURE__ */ new Set();
2342
+ for (const object of data) {
2343
+ if (!isPlainObject(object)) return false;
2344
+ const keys = Object.keys(object);
2345
+ if (keys.length !== 1) return false;
2346
+ for (const key of keys) {
2347
+ if (objectKeys.has(key)) return false;
2348
+ objectKeys.add(key);
2349
+ }
2350
+ }
2351
+ return true;
2352
+ }
2353
+ var omap = {
2354
+ tag: "tag:yaml.org,2002:omap",
2355
+ kind: "sequence",
2356
+ resolve: resolveYamlOmap,
2357
+ construct(data) {
2358
+ return data;
2359
+ }
2360
+ };
2361
+
2362
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/pairs.js
2363
+ function resolveYamlPairs(data) {
2364
+ if (data === null) return true;
2365
+ return data.every((it) => isPlainObject(it) && Object.keys(it).length === 1);
2366
+ }
2367
+ var pairs = {
2368
+ tag: "tag:yaml.org,2002:pairs",
2369
+ construct(data) {
2370
+ return data?.flatMap(Object.entries) ?? [];
2371
+ },
2372
+ kind: "sequence",
2373
+ resolve: resolveYamlPairs
2374
+ };
2375
+
2376
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/regexp.js
2377
+ var REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/;
2378
+ var regexp = {
2379
+ tag: "tag:yaml.org,2002:js/regexp",
2380
+ kind: "scalar",
2381
+ resolve(data) {
2382
+ if (data === null || !data.length) return false;
2383
+ if (data.charAt(0) === "/") {
2384
+ const groups = data.match(REGEXP)?.groups;
2385
+ if (!groups) return false;
2386
+ const modifiers = groups.modifiers ?? "";
2387
+ if (new Set(modifiers).size < modifiers.length) return false;
2388
+ }
2389
+ return true;
2390
+ },
2391
+ construct(data) {
2392
+ const { regexp: regexp2 = data, modifiers = "" } = data.match(REGEXP)?.groups ?? {};
2393
+ return new RegExp(regexp2, modifiers);
2394
+ },
2395
+ predicate: (object) => object instanceof RegExp,
2396
+ represent: (object) => object.toString()
2397
+ };
2398
+
2399
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/seq.js
2400
+ var seq = {
2401
+ tag: "tag:yaml.org,2002:seq",
2402
+ kind: "sequence",
2403
+ resolve: () => true,
2404
+ construct: (data) => data !== null ? data : []
2405
+ };
2406
+
2407
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/set.js
2408
+ var set = {
2409
+ tag: "tag:yaml.org,2002:set",
2410
+ kind: "mapping",
2411
+ construct: (data) => data !== null ? data : {},
2412
+ resolve: (data) => {
2413
+ if (data === null) return true;
2414
+ return Object.values(data).every((it) => it === null);
2415
+ }
2416
+ };
2417
+
2418
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/str.js
2419
+ var str = {
2420
+ tag: "tag:yaml.org,2002:str",
2421
+ kind: "scalar",
2422
+ resolve: () => true,
2423
+ construct: (data) => data !== null ? data : ""
2424
+ };
2425
+
2426
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/timestamp.js
2427
+ var YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
2428
+ var YAML_TIMESTAMP_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
2429
+ function resolveYamlTimestamp(data) {
2430
+ if (data === null) return false;
2431
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
2432
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
2433
+ return false;
2434
+ }
2435
+ function constructYamlTimestamp(data) {
2436
+ let match = YAML_DATE_REGEXP.exec(data);
2437
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
2438
+ if (match === null) {
2439
+ throw new Error("Cannot construct YAML timestamp: date resolve error");
2440
+ }
2441
+ const year = +match[1];
2442
+ const month = +match[2] - 1;
2443
+ const day = +match[3];
2444
+ if (!match[4]) {
2445
+ return new Date(Date.UTC(year, month, day));
2446
+ }
2447
+ const hour = +match[4];
2448
+ const minute = +match[5];
2449
+ const second = +match[6];
2450
+ let fraction = 0;
2451
+ if (match[7]) {
2452
+ let partFraction = match[7].slice(0, 3);
2453
+ while (partFraction.length < 3) {
2454
+ partFraction += "0";
2455
+ }
2456
+ fraction = +partFraction;
2457
+ }
2458
+ let delta = null;
2459
+ if (match[9] && match[10]) {
2460
+ const tzHour = +match[10];
2461
+ const tzMinute = +(match[11] || 0);
2462
+ delta = (tzHour * 60 + tzMinute) * 6e4;
2463
+ if (match[9] === "-") delta = -delta;
2464
+ }
2465
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
2466
+ if (delta) date.setTime(date.getTime() - delta);
2467
+ return date;
2468
+ }
2469
+ function representYamlTimestamp(date) {
2470
+ return date.toISOString();
2471
+ }
2472
+ var timestamp = {
2473
+ tag: "tag:yaml.org,2002:timestamp",
2474
+ construct: constructYamlTimestamp,
2475
+ predicate(object) {
2476
+ return object instanceof Date;
2477
+ },
2478
+ kind: "scalar",
2479
+ represent: representYamlTimestamp,
2480
+ resolve: resolveYamlTimestamp
2481
+ };
2482
+
2483
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_type/undefined.js
2484
+ var undefinedType = {
2485
+ tag: "tag:yaml.org,2002:js/undefined",
2486
+ kind: "scalar",
2487
+ resolve() {
2488
+ return true;
2489
+ },
2490
+ construct() {
2491
+ return void 0;
2492
+ },
2493
+ predicate(object) {
2494
+ return typeof object === "undefined";
2495
+ },
2496
+ represent() {
2497
+ return "";
2498
+ }
2499
+ };
2500
+
2501
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_schema.js
2502
+ function createTypeMap(implicitTypes, explicitTypes) {
2503
+ const result = {
2504
+ fallback: /* @__PURE__ */ new Map(),
2505
+ mapping: /* @__PURE__ */ new Map(),
2506
+ scalar: /* @__PURE__ */ new Map(),
2507
+ sequence: /* @__PURE__ */ new Map()
2508
+ };
2509
+ const fallbackMap = result.fallback;
2510
+ for (const type of [
2511
+ ...implicitTypes,
2512
+ ...explicitTypes
2513
+ ]) {
2514
+ const map2 = result[type.kind];
2515
+ map2.set(type.tag, type);
2516
+ fallbackMap.set(type.tag, type);
2517
+ }
2518
+ return result;
2519
+ }
2520
+ function createSchema({ explicitTypes = [], implicitTypes = [], include }) {
2521
+ if (include) {
2522
+ implicitTypes.push(...include.implicitTypes);
2523
+ explicitTypes.push(...include.explicitTypes);
2524
+ }
2525
+ const typeMap = createTypeMap(implicitTypes, explicitTypes);
2526
+ return {
2527
+ implicitTypes,
2528
+ explicitTypes,
2529
+ typeMap
2530
+ };
2531
+ }
2532
+ var FAILSAFE_SCHEMA = createSchema({
2533
+ explicitTypes: [
2534
+ str,
2535
+ seq,
2536
+ map
2537
+ ]
2538
+ });
2539
+ var JSON_SCHEMA = createSchema({
2540
+ implicitTypes: [
2541
+ nil,
2542
+ bool,
2543
+ int,
2544
+ float
2545
+ ],
2546
+ include: FAILSAFE_SCHEMA
2547
+ });
2548
+ var CORE_SCHEMA = createSchema({
2549
+ include: JSON_SCHEMA
2550
+ });
2551
+ var DEFAULT_SCHEMA = createSchema({
2552
+ explicitTypes: [
2553
+ binary,
2554
+ omap,
2555
+ pairs,
2556
+ set
2557
+ ],
2558
+ implicitTypes: [
2559
+ timestamp,
2560
+ merge
2561
+ ],
2562
+ include: CORE_SCHEMA
2563
+ });
2564
+ var EXTENDED_SCHEMA = createSchema({
2565
+ explicitTypes: [
2566
+ regexp,
2567
+ undefinedType
2568
+ ],
2569
+ include: DEFAULT_SCHEMA
2570
+ });
2571
+ var SCHEMA_MAP = /* @__PURE__ */ new Map([
2572
+ [
2573
+ "core",
2574
+ CORE_SCHEMA
2575
+ ],
2576
+ [
2577
+ "default",
2578
+ DEFAULT_SCHEMA
2579
+ ],
2580
+ [
2581
+ "failsafe",
2582
+ FAILSAFE_SCHEMA
2583
+ ],
2584
+ [
2585
+ "json",
2586
+ JSON_SCHEMA
2587
+ ],
2588
+ [
2589
+ "extended",
2590
+ EXTENDED_SCHEMA
2591
+ ]
2592
+ ]);
2593
+
2594
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/_loader_state.js
2595
+ var CONTEXT_FLOW_IN = 1;
2596
+ var CONTEXT_FLOW_OUT = 2;
2597
+ var CONTEXT_BLOCK_IN = 3;
2598
+ var CONTEXT_BLOCK_OUT = 4;
2599
+ var CHOMPING_CLIP = 1;
2600
+ var CHOMPING_STRIP = 2;
2601
+ var CHOMPING_KEEP = 3;
2602
+ var PATTERN_NON_PRINTABLE = (
2603
+ // deno-lint-ignore no-control-regex
2604
+ /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/
2605
+ );
2606
+ var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
2607
+ var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
2608
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
2609
+ var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
2610
+ var ESCAPED_HEX_LENGTHS = /* @__PURE__ */ new Map([
2611
+ [
2612
+ 120,
2613
+ 2
2614
+ ],
2615
+ [
2616
+ 117,
2617
+ 4
2618
+ ],
2619
+ [
2620
+ 85,
2621
+ 8
2622
+ ]
2623
+ ]);
2624
+ var SIMPLE_ESCAPE_SEQUENCES = /* @__PURE__ */ new Map([
2625
+ [
2626
+ 48,
2627
+ "\0"
2628
+ ],
2629
+ [
2630
+ 97,
2631
+ "\x07"
2632
+ ],
2633
+ [
2634
+ 98,
2635
+ "\b"
2636
+ ],
2637
+ [
2638
+ 116,
2639
+ " "
2640
+ ],
2641
+ [
2642
+ 9,
2643
+ " "
2644
+ ],
2645
+ [
2646
+ 110,
2647
+ "\n"
2648
+ ],
2649
+ [
2650
+ 118,
2651
+ "\v"
2652
+ ],
2653
+ [
2654
+ 102,
2655
+ "\f"
2656
+ ],
2657
+ [
2658
+ 114,
2659
+ "\r"
2660
+ ],
2661
+ [
2662
+ 101,
2663
+ "\x1B"
2664
+ ],
2665
+ [
2666
+ 32,
2667
+ " "
2668
+ ],
2669
+ [
2670
+ 34,
2671
+ '"'
2672
+ ],
2673
+ [
2674
+ 47,
2675
+ "/"
2676
+ ],
2677
+ [
2678
+ 92,
2679
+ "\\"
2680
+ ],
2681
+ [
2682
+ 78,
2683
+ "\x85"
2684
+ ],
2685
+ [
2686
+ 95,
2687
+ "\xA0"
2688
+ ],
2689
+ [
2690
+ 76,
2691
+ "\u2028"
2692
+ ],
2693
+ [
2694
+ 80,
2695
+ "\u2029"
2696
+ ]
2697
+ ]);
2698
+ function hexCharCodeToNumber(charCode) {
2699
+ if (48 <= charCode && charCode <= 57) return charCode - 48;
2700
+ const lc = charCode | 32;
2701
+ if (97 <= lc && lc <= 102) return lc - 97 + 10;
2702
+ return -1;
2703
+ }
2704
+ function decimalCharCodeToNumber(charCode) {
2705
+ if (48 <= charCode && charCode <= 57) return charCode - 48;
2706
+ return -1;
2707
+ }
2708
+ function codepointToChar(codepoint) {
2709
+ if (codepoint <= 65535) return String.fromCharCode(codepoint);
2710
+ return String.fromCharCode((codepoint - 65536 >> 10) + 55296, (codepoint - 65536 & 1023) + 56320);
2711
+ }
2712
+ var INDENT = 4;
2713
+ var MAX_LENGTH = 75;
2714
+ var DELIMITERS = "\0\r\n\x85\u2028\u2029";
2715
+ function getSnippet(buffer, position) {
2716
+ if (!buffer) return null;
2717
+ let start = position;
2718
+ let end = position;
2719
+ let head = "";
2720
+ let tail = "";
2721
+ while (start > 0 && !DELIMITERS.includes(buffer.charAt(start - 1))) {
2722
+ start--;
2723
+ if (position - start > MAX_LENGTH / 2 - 1) {
2724
+ head = " ... ";
2725
+ start += 5;
2726
+ break;
2727
+ }
2728
+ }
2729
+ while (end < buffer.length && !DELIMITERS.includes(buffer.charAt(end))) {
2730
+ end++;
2731
+ if (end - position > MAX_LENGTH / 2 - 1) {
2732
+ tail = " ... ";
2733
+ end -= 5;
2734
+ break;
2735
+ }
2736
+ }
2737
+ const snippet = buffer.slice(start, end);
2738
+ const indent = " ".repeat(INDENT);
2739
+ const caretIndent = " ".repeat(INDENT + position - start + head.length);
2740
+ return `${indent + head + snippet + tail}
2741
+ ${caretIndent}^`;
2742
+ }
2743
+ function markToString(buffer, position, line, column) {
2744
+ let where = `at line ${line + 1}, column ${column + 1}`;
2745
+ const snippet = getSnippet(buffer, position);
2746
+ if (snippet) where += `:
2747
+ ${snippet}`;
2748
+ return where;
2749
+ }
2750
+ function getIndentStatus(lineIndent, parentIndent) {
2751
+ if (lineIndent > parentIndent) return 1;
2752
+ if (lineIndent < parentIndent) return -1;
2753
+ return 0;
2754
+ }
2755
+ function writeFoldedLines(count) {
2756
+ if (count === 1) return " ";
2757
+ if (count > 1) return "\n".repeat(count - 1);
2758
+ return "";
2759
+ }
2760
+ var LoaderState = class {
2761
+ input;
2762
+ length;
2763
+ lineIndent = 0;
2764
+ lineStart = 0;
2765
+ position = 0;
2766
+ line = 0;
2767
+ onWarning;
2768
+ allowDuplicateKeys;
2769
+ implicitTypes;
2770
+ typeMap;
2771
+ checkLineBreaks = false;
2772
+ tagMap = /* @__PURE__ */ new Map();
2773
+ anchorMap = /* @__PURE__ */ new Map();
2774
+ constructor(input, { schema = DEFAULT_SCHEMA, onWarning, allowDuplicateKeys = false }) {
2775
+ this.input = input;
2776
+ this.onWarning = onWarning;
2777
+ this.allowDuplicateKeys = allowDuplicateKeys;
2778
+ this.implicitTypes = schema.implicitTypes;
2779
+ this.typeMap = schema.typeMap;
2780
+ this.length = input.length;
2781
+ this.readIndent();
2782
+ }
2783
+ skipWhitespaces() {
2784
+ let ch = this.peek();
2785
+ while (isWhiteSpace(ch)) {
2786
+ ch = this.next();
2787
+ }
2788
+ }
2789
+ skipComment() {
2790
+ let ch = this.peek();
2791
+ if (ch !== SHARP) return;
2792
+ ch = this.next();
2793
+ while (ch !== 0 && !isEOL(ch)) {
2794
+ ch = this.next();
2795
+ }
2796
+ }
2797
+ readIndent() {
2798
+ let char = this.peek();
2799
+ while (char === SPACE) {
2800
+ this.lineIndent += 1;
2801
+ char = this.next();
2802
+ }
2803
+ }
2804
+ peek(offset = 0) {
2805
+ return this.input.charCodeAt(this.position + offset);
2806
+ }
2807
+ next() {
2808
+ this.position += 1;
2809
+ return this.peek();
2810
+ }
2811
+ #createError(message) {
2812
+ const mark = markToString(this.input, this.position, this.line, this.position - this.lineStart);
2813
+ return new SyntaxError(`${message} ${mark}`);
2814
+ }
2815
+ dispatchWarning(message) {
2816
+ const error = this.#createError(message);
2817
+ this.onWarning?.(error);
2818
+ }
2819
+ yamlDirectiveHandler(args) {
2820
+ if (args.length !== 1) {
2821
+ throw this.#createError("Cannot handle YAML directive: YAML directive accepts exactly one argument");
2822
+ }
2823
+ const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
2824
+ if (match === null) {
2825
+ throw this.#createError("Cannot handle YAML directive: ill-formed argument");
2826
+ }
2827
+ const major = parseInt(match[1], 10);
2828
+ const minor = parseInt(match[2], 10);
2829
+ if (major !== 1) {
2830
+ throw this.#createError("Cannot handle YAML directive: unacceptable YAML version");
2831
+ }
2832
+ this.checkLineBreaks = minor < 2;
2833
+ if (minor !== 1 && minor !== 2) {
2834
+ this.dispatchWarning("Cannot handle YAML directive: unsupported YAML version");
2835
+ }
2836
+ return args[0] ?? null;
2837
+ }
2838
+ tagDirectiveHandler(args) {
2839
+ if (args.length !== 2) {
2840
+ throw this.#createError(`Cannot handle tag directive: directive accepts exactly two arguments, received ${args.length}`);
2841
+ }
2842
+ const handle = args[0];
2843
+ const prefix = args[1];
2844
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
2845
+ throw this.#createError(`Cannot handle tag directive: ill-formed handle (first argument) in "${handle}"`);
2846
+ }
2847
+ if (this.tagMap.has(handle)) {
2848
+ throw this.#createError(`Cannot handle tag directive: previously declared suffix for "${handle}" tag handle`);
2849
+ }
2850
+ if (!PATTERN_TAG_URI.test(prefix)) {
2851
+ throw this.#createError("Cannot handle tag directive: ill-formed tag prefix (second argument) of the TAG directive");
2852
+ }
2853
+ this.tagMap.set(handle, prefix);
2854
+ }
2855
+ captureSegment(start, end, checkJson) {
2856
+ if (start < end) {
2857
+ const result = this.input.slice(start, end);
2858
+ if (checkJson) {
2859
+ for (let position = 0; position < result.length; position++) {
2860
+ const character = result.charCodeAt(position);
2861
+ if (!(character === 9 || 32 <= character && character <= 1114111)) {
2862
+ throw this.#createError(`Expected valid JSON character: received "${character}"`);
2863
+ }
2864
+ }
2865
+ } else if (PATTERN_NON_PRINTABLE.test(result)) {
2866
+ throw this.#createError("Stream contains non-printable characters");
2867
+ }
2868
+ return result;
2869
+ }
2870
+ }
2871
+ readBlockSequence(tag, anchor, nodeIndent) {
2872
+ let detected = false;
2873
+ const result = [];
2874
+ if (anchor !== null) this.anchorMap.set(anchor, result);
2875
+ let ch = this.peek();
2876
+ while (ch !== 0) {
2877
+ if (ch !== MINUS) {
2878
+ break;
2879
+ }
2880
+ const following = this.peek(1);
2881
+ if (!isWhiteSpaceOrEOL(following)) {
2882
+ break;
2883
+ }
2884
+ detected = true;
2885
+ this.position++;
2886
+ if (this.skipSeparationSpace(true, -1)) {
2887
+ if (this.lineIndent <= nodeIndent) {
2888
+ result.push(null);
2889
+ ch = this.peek();
2890
+ continue;
2891
+ }
2892
+ }
2893
+ const line = this.line;
2894
+ const newState = this.composeNode({
2895
+ parentIndent: nodeIndent,
2896
+ nodeContext: CONTEXT_BLOCK_IN,
2897
+ allowToSeek: false,
2898
+ allowCompact: true
2899
+ });
2900
+ if (newState) result.push(newState.result);
2901
+ this.skipSeparationSpace(true, -1);
2902
+ ch = this.peek();
2903
+ if ((this.line === line || this.lineIndent > nodeIndent) && ch !== 0) {
2904
+ throw this.#createError("Cannot read block sequence: bad indentation of a sequence entry");
2905
+ } else if (this.lineIndent < nodeIndent) {
2906
+ break;
2907
+ }
2908
+ }
2909
+ if (detected) return {
2910
+ tag,
2911
+ anchor,
2912
+ kind: "sequence",
2913
+ result
2914
+ };
2915
+ }
2916
+ mergeMappings(destination, source, overridableKeys) {
2917
+ if (!isObject(source)) {
2918
+ throw this.#createError("Cannot merge mappings: the provided source object is unacceptable");
2919
+ }
2920
+ for (const [key, value] of Object.entries(source)) {
2921
+ if (Object.hasOwn(destination, key)) continue;
2922
+ Object.defineProperty(destination, key, {
2923
+ value,
2924
+ writable: true,
2925
+ enumerable: true,
2926
+ configurable: true
2927
+ });
2928
+ overridableKeys.add(key);
2929
+ }
2930
+ }
2931
+ storeMappingPair(result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
2932
+ if (Array.isArray(keyNode)) {
2933
+ keyNode = Array.prototype.slice.call(keyNode);
2934
+ for (let index = 0; index < keyNode.length; index++) {
2935
+ if (Array.isArray(keyNode[index])) {
2936
+ throw this.#createError("Cannot store mapping pair: nested arrays are not supported inside keys");
2937
+ }
2938
+ if (typeof keyNode === "object" && isPlainObject(keyNode[index])) {
2939
+ keyNode[index] = "[object Object]";
2940
+ }
2941
+ }
2942
+ }
2943
+ if (typeof keyNode === "object" && isPlainObject(keyNode)) {
2944
+ keyNode = "[object Object]";
2945
+ }
2946
+ keyNode = String(keyNode);
2947
+ if (keyTag === "tag:yaml.org,2002:merge") {
2948
+ if (Array.isArray(valueNode)) {
2949
+ for (let index = 0; index < valueNode.length; index++) {
2950
+ this.mergeMappings(result, valueNode[index], overridableKeys);
2951
+ }
2952
+ } else {
2953
+ this.mergeMappings(result, valueNode, overridableKeys);
2954
+ }
2955
+ } else {
2956
+ if (!this.allowDuplicateKeys && !overridableKeys.has(keyNode) && Object.hasOwn(result, keyNode)) {
2957
+ this.line = startLine || this.line;
2958
+ this.position = startPos || this.position;
2959
+ throw this.#createError("Cannot store mapping pair: duplicated key");
2960
+ }
2961
+ Object.defineProperty(result, keyNode, {
2962
+ value: valueNode,
2963
+ writable: true,
2964
+ enumerable: true,
2965
+ configurable: true
2966
+ });
2967
+ overridableKeys.delete(keyNode);
2968
+ }
2969
+ return result;
2970
+ }
2971
+ readLineBreak() {
2972
+ const ch = this.peek();
2973
+ if (ch === LINE_FEED) {
2974
+ this.position++;
2975
+ } else if (ch === CARRIAGE_RETURN) {
2976
+ this.position++;
2977
+ if (this.peek() === LINE_FEED) {
2978
+ this.position++;
2979
+ }
2980
+ } else {
2981
+ throw this.#createError("Cannot read line: line break not found");
2982
+ }
2983
+ this.line += 1;
2984
+ this.lineStart = this.position;
2985
+ }
2986
+ skipSeparationSpace(allowComments, checkIndent) {
2987
+ let lineBreaks = 0;
2988
+ let ch = this.peek();
2989
+ while (ch !== 0) {
2990
+ this.skipWhitespaces();
2991
+ ch = this.peek();
2992
+ if (allowComments) {
2993
+ this.skipComment();
2994
+ ch = this.peek();
2995
+ }
2996
+ if (isEOL(ch)) {
2997
+ this.readLineBreak();
2998
+ ch = this.peek();
2999
+ lineBreaks++;
3000
+ this.lineIndent = 0;
3001
+ this.readIndent();
3002
+ ch = this.peek();
3003
+ } else {
3004
+ break;
3005
+ }
3006
+ }
3007
+ if (checkIndent !== -1 && lineBreaks !== 0 && this.lineIndent < checkIndent) {
3008
+ this.dispatchWarning("deficient indentation");
3009
+ }
3010
+ return lineBreaks;
3011
+ }
3012
+ testDocumentSeparator() {
3013
+ let ch = this.peek();
3014
+ if ((ch === MINUS || ch === DOT) && ch === this.peek(1) && ch === this.peek(2)) {
3015
+ ch = this.peek(3);
3016
+ if (ch === 0 || isWhiteSpaceOrEOL(ch)) {
3017
+ return true;
3018
+ }
3019
+ }
3020
+ return false;
3021
+ }
3022
+ readPlainScalar(tag, anchor, nodeIndent, withinFlowCollection) {
3023
+ let ch = this.peek();
3024
+ if (isWhiteSpaceOrEOL(ch) || isFlowIndicator(ch) || ch === SHARP || ch === AMPERSAND || ch === ASTERISK || ch === EXCLAMATION || ch === VERTICAL_LINE || ch === GREATER_THAN || ch === SINGLE_QUOTE || ch === DOUBLE_QUOTE || ch === PERCENT || ch === COMMERCIAL_AT || ch === GRAVE_ACCENT) {
3025
+ return;
3026
+ }
3027
+ let following;
3028
+ if (ch === QUESTION || ch === MINUS) {
3029
+ following = this.peek(1);
3030
+ if (isWhiteSpaceOrEOL(following) || withinFlowCollection && isFlowIndicator(following)) {
3031
+ return;
3032
+ }
3033
+ }
3034
+ let result = "";
3035
+ let captureEnd = this.position;
3036
+ let captureStart = this.position;
3037
+ let hasPendingContent = false;
3038
+ let line = 0;
3039
+ while (ch !== 0) {
3040
+ if (ch === COLON) {
3041
+ following = this.peek(1);
3042
+ if (isWhiteSpaceOrEOL(following) || withinFlowCollection && isFlowIndicator(following)) {
3043
+ break;
3044
+ }
3045
+ } else if (ch === SHARP) {
3046
+ const preceding = this.peek(-1);
3047
+ if (isWhiteSpaceOrEOL(preceding)) {
3048
+ break;
3049
+ }
3050
+ } else if (this.position === this.lineStart && this.testDocumentSeparator() || withinFlowCollection && isFlowIndicator(ch)) {
3051
+ break;
3052
+ } else if (isEOL(ch)) {
3053
+ line = this.line;
3054
+ const lineStart = this.lineStart;
3055
+ const lineIndent = this.lineIndent;
3056
+ this.skipSeparationSpace(false, -1);
3057
+ if (this.lineIndent >= nodeIndent) {
3058
+ hasPendingContent = true;
3059
+ ch = this.peek();
3060
+ continue;
3061
+ } else {
3062
+ this.position = captureEnd;
3063
+ this.line = line;
3064
+ this.lineStart = lineStart;
3065
+ this.lineIndent = lineIndent;
3066
+ break;
3067
+ }
3068
+ }
3069
+ if (hasPendingContent) {
3070
+ const segment2 = this.captureSegment(captureStart, captureEnd, false);
3071
+ if (segment2) result += segment2;
3072
+ result += writeFoldedLines(this.line - line);
3073
+ captureStart = captureEnd = this.position;
3074
+ hasPendingContent = false;
3075
+ }
3076
+ if (!isWhiteSpace(ch)) {
3077
+ captureEnd = this.position + 1;
3078
+ }
3079
+ ch = this.next();
3080
+ }
3081
+ const segment = this.captureSegment(captureStart, captureEnd, false);
3082
+ if (segment) result += segment;
3083
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3084
+ if (result) return {
3085
+ tag,
3086
+ anchor,
3087
+ kind: "scalar",
3088
+ result
3089
+ };
3090
+ }
3091
+ readSingleQuotedScalar(tag, anchor, nodeIndent) {
3092
+ let ch = this.peek();
3093
+ if (ch !== SINGLE_QUOTE) return;
3094
+ let result = "";
3095
+ this.position++;
3096
+ let captureStart = this.position;
3097
+ let captureEnd = this.position;
3098
+ ch = this.peek();
3099
+ while (ch !== 0) {
3100
+ if (ch === SINGLE_QUOTE) {
3101
+ const segment = this.captureSegment(captureStart, this.position, true);
3102
+ if (segment) result += segment;
3103
+ ch = this.next();
3104
+ if (ch === SINGLE_QUOTE) {
3105
+ captureStart = this.position;
3106
+ this.position++;
3107
+ captureEnd = this.position;
3108
+ } else {
3109
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3110
+ return {
3111
+ tag,
3112
+ anchor,
3113
+ kind: "scalar",
3114
+ result
3115
+ };
3116
+ }
3117
+ } else if (isEOL(ch)) {
3118
+ const segment = this.captureSegment(captureStart, captureEnd, true);
3119
+ if (segment) result += segment;
3120
+ result += writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
3121
+ captureStart = captureEnd = this.position;
3122
+ } else if (this.position === this.lineStart && this.testDocumentSeparator()) {
3123
+ throw this.#createError("Unexpected end of the document within a single quoted scalar");
3124
+ } else {
3125
+ this.position++;
3126
+ captureEnd = this.position;
3127
+ }
3128
+ ch = this.peek();
3129
+ }
3130
+ throw this.#createError("Unexpected end of the stream within a single quoted scalar");
3131
+ }
3132
+ readDoubleQuotedScalar(tag, anchor, nodeIndent) {
3133
+ let ch = this.peek();
3134
+ if (ch !== DOUBLE_QUOTE) return;
3135
+ let result = "";
3136
+ this.position++;
3137
+ let captureEnd = this.position;
3138
+ let captureStart = this.position;
3139
+ let tmp;
3140
+ ch = this.peek();
3141
+ while (ch !== 0) {
3142
+ if (ch === DOUBLE_QUOTE) {
3143
+ const segment = this.captureSegment(captureStart, this.position, true);
3144
+ if (segment) result += segment;
3145
+ this.position++;
3146
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3147
+ return {
3148
+ tag,
3149
+ anchor,
3150
+ kind: "scalar",
3151
+ result
3152
+ };
3153
+ }
3154
+ if (ch === BACKSLASH) {
3155
+ const segment = this.captureSegment(captureStart, this.position, true);
3156
+ if (segment) result += segment;
3157
+ ch = this.next();
3158
+ if (isEOL(ch)) {
3159
+ this.skipSeparationSpace(false, nodeIndent);
3160
+ } else if (ch < 256 && SIMPLE_ESCAPE_SEQUENCES.has(ch)) {
3161
+ result += SIMPLE_ESCAPE_SEQUENCES.get(ch);
3162
+ this.position++;
3163
+ } else if ((tmp = ESCAPED_HEX_LENGTHS.get(ch) ?? 0) > 0) {
3164
+ let hexLength = tmp;
3165
+ let hexResult = 0;
3166
+ for (; hexLength > 0; hexLength--) {
3167
+ ch = this.next();
3168
+ if ((tmp = hexCharCodeToNumber(ch)) >= 0) {
3169
+ hexResult = (hexResult << 4) + tmp;
3170
+ } else {
3171
+ throw this.#createError("Cannot read double quoted scalar: expected hexadecimal character");
3172
+ }
3173
+ }
3174
+ result += codepointToChar(hexResult);
3175
+ this.position++;
3176
+ } else {
3177
+ throw this.#createError("Cannot read double quoted scalar: unknown escape sequence");
3178
+ }
3179
+ captureStart = captureEnd = this.position;
3180
+ } else if (isEOL(ch)) {
3181
+ const segment = this.captureSegment(captureStart, captureEnd, true);
3182
+ if (segment) result += segment;
3183
+ result += writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
3184
+ captureStart = captureEnd = this.position;
3185
+ } else if (this.position === this.lineStart && this.testDocumentSeparator()) {
3186
+ throw this.#createError("Unexpected end of the document within a double quoted scalar");
3187
+ } else {
3188
+ this.position++;
3189
+ captureEnd = this.position;
3190
+ }
3191
+ ch = this.peek();
3192
+ }
3193
+ throw this.#createError("Unexpected end of the stream within a double quoted scalar");
3194
+ }
3195
+ readFlowCollection(tag, anchor, nodeIndent) {
3196
+ let ch = this.peek();
3197
+ let terminator;
3198
+ let isMapping = true;
3199
+ let result = {};
3200
+ if (ch === LEFT_SQUARE_BRACKET) {
3201
+ terminator = RIGHT_SQUARE_BRACKET;
3202
+ isMapping = false;
3203
+ result = [];
3204
+ } else if (ch === LEFT_CURLY_BRACKET) {
3205
+ terminator = RIGHT_CURLY_BRACKET;
3206
+ } else {
3207
+ return;
3208
+ }
3209
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3210
+ ch = this.next();
3211
+ let readNext = true;
3212
+ let valueNode = null;
3213
+ let keyNode = null;
3214
+ let keyTag = null;
3215
+ let isExplicitPair = false;
3216
+ let isPair = false;
3217
+ let following = 0;
3218
+ let line = 0;
3219
+ const overridableKeys = /* @__PURE__ */ new Set();
3220
+ while (ch !== 0) {
3221
+ this.skipSeparationSpace(true, nodeIndent);
3222
+ ch = this.peek();
3223
+ if (ch === terminator) {
3224
+ this.position++;
3225
+ const kind = isMapping ? "mapping" : "sequence";
3226
+ return {
3227
+ tag,
3228
+ anchor,
3229
+ kind,
3230
+ result
3231
+ };
3232
+ }
3233
+ if (!readNext) {
3234
+ throw this.#createError("Cannot read flow collection: missing comma between flow collection entries");
3235
+ }
3236
+ keyTag = keyNode = valueNode = null;
3237
+ isPair = isExplicitPair = false;
3238
+ if (ch === QUESTION) {
3239
+ following = this.peek(1);
3240
+ if (isWhiteSpaceOrEOL(following)) {
3241
+ isPair = isExplicitPair = true;
3242
+ this.position++;
3243
+ this.skipSeparationSpace(true, nodeIndent);
3244
+ }
3245
+ }
3246
+ line = this.line;
3247
+ const newState = this.composeNode({
3248
+ parentIndent: nodeIndent,
3249
+ nodeContext: CONTEXT_FLOW_IN,
3250
+ allowToSeek: false,
3251
+ allowCompact: true
3252
+ });
3253
+ if (newState) {
3254
+ keyTag = newState.tag || null;
3255
+ keyNode = newState.result;
3256
+ }
3257
+ this.skipSeparationSpace(true, nodeIndent);
3258
+ ch = this.peek();
3259
+ if ((isExplicitPair || this.line === line) && ch === COLON) {
3260
+ isPair = true;
3261
+ ch = this.next();
3262
+ this.skipSeparationSpace(true, nodeIndent);
3263
+ const newState2 = this.composeNode({
3264
+ parentIndent: nodeIndent,
3265
+ nodeContext: CONTEXT_FLOW_IN,
3266
+ allowToSeek: false,
3267
+ allowCompact: true
3268
+ });
3269
+ if (newState2) valueNode = newState2.result;
3270
+ }
3271
+ if (isMapping) {
3272
+ this.storeMappingPair(result, overridableKeys, keyTag, keyNode, valueNode);
3273
+ } else if (isPair) {
3274
+ result.push(this.storeMappingPair({}, overridableKeys, keyTag, keyNode, valueNode));
3275
+ } else {
3276
+ result.push(keyNode);
3277
+ }
3278
+ this.skipSeparationSpace(true, nodeIndent);
3279
+ ch = this.peek();
3280
+ if (ch === COMMA) {
3281
+ readNext = true;
3282
+ ch = this.next();
3283
+ } else {
3284
+ readNext = false;
3285
+ }
3286
+ }
3287
+ throw this.#createError("Cannot read flow collection: unexpected end of the stream within a flow collection");
3288
+ }
3289
+ // Handles block scaler styles: e.g. '|', '>', '|-' and '>-'.
3290
+ // https://yaml.org/spec/1.2.2/#81-block-scalar-styles
3291
+ readBlockScalar(tag, anchor, nodeIndent) {
3292
+ let chomping = CHOMPING_CLIP;
3293
+ let didReadContent = false;
3294
+ let detectedIndent = false;
3295
+ let textIndent = nodeIndent;
3296
+ let emptyLines = 0;
3297
+ let atMoreIndented = false;
3298
+ let ch = this.peek();
3299
+ let folding = false;
3300
+ if (ch === VERTICAL_LINE) {
3301
+ folding = false;
3302
+ } else if (ch === GREATER_THAN) {
3303
+ folding = true;
3304
+ } else {
3305
+ return;
3306
+ }
3307
+ let result = "";
3308
+ let tmp = 0;
3309
+ while (ch !== 0) {
3310
+ ch = this.next();
3311
+ if (ch === PLUS || ch === MINUS) {
3312
+ if (CHOMPING_CLIP === chomping) {
3313
+ chomping = ch === PLUS ? CHOMPING_KEEP : CHOMPING_STRIP;
3314
+ } else {
3315
+ throw this.#createError("Cannot read block: chomping mode identifier repeated");
3316
+ }
3317
+ } else if ((tmp = decimalCharCodeToNumber(ch)) >= 0) {
3318
+ if (tmp === 0) {
3319
+ throw this.#createError("Cannot read block: indentation width must be greater than 0");
3320
+ } else if (!detectedIndent) {
3321
+ textIndent = nodeIndent + tmp - 1;
3322
+ detectedIndent = true;
3323
+ } else {
3324
+ throw this.#createError("Cannot read block: indentation width identifier repeated");
3325
+ }
3326
+ } else {
3327
+ break;
3328
+ }
3329
+ }
3330
+ if (isWhiteSpace(ch)) {
3331
+ this.skipWhitespaces();
3332
+ this.skipComment();
3333
+ ch = this.peek();
3334
+ }
3335
+ while (ch !== 0) {
3336
+ this.readLineBreak();
3337
+ this.lineIndent = 0;
3338
+ ch = this.peek();
3339
+ while ((!detectedIndent || this.lineIndent < textIndent) && ch === SPACE) {
3340
+ this.lineIndent++;
3341
+ ch = this.next();
3342
+ }
3343
+ if (!detectedIndent && this.lineIndent > textIndent) {
3344
+ textIndent = this.lineIndent;
3345
+ }
3346
+ if (isEOL(ch)) {
3347
+ emptyLines++;
3348
+ continue;
3349
+ }
3350
+ if (this.lineIndent < textIndent) {
3351
+ if (chomping === CHOMPING_KEEP) {
3352
+ result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
3353
+ } else if (chomping === CHOMPING_CLIP) {
3354
+ if (didReadContent) {
3355
+ result += "\n";
3356
+ }
3357
+ }
3358
+ break;
3359
+ }
3360
+ if (folding) {
3361
+ if (isWhiteSpace(ch)) {
3362
+ atMoreIndented = true;
3363
+ result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
3364
+ } else if (atMoreIndented) {
3365
+ atMoreIndented = false;
3366
+ result += "\n".repeat(emptyLines + 1);
3367
+ } else if (emptyLines === 0) {
3368
+ if (didReadContent) {
3369
+ result += " ";
3370
+ }
3371
+ } else {
3372
+ result += "\n".repeat(emptyLines);
3373
+ }
3374
+ } else {
3375
+ result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
3376
+ }
3377
+ didReadContent = true;
3378
+ detectedIndent = true;
3379
+ emptyLines = 0;
3380
+ const captureStart = this.position;
3381
+ while (!isEOL(ch) && ch !== 0) {
3382
+ ch = this.next();
3383
+ }
3384
+ const segment = this.captureSegment(captureStart, this.position, false);
3385
+ if (segment) result += segment;
3386
+ }
3387
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3388
+ return {
3389
+ tag,
3390
+ anchor,
3391
+ kind: "scalar",
3392
+ result
3393
+ };
3394
+ }
3395
+ readBlockMapping(tag, anchor, nodeIndent, flowIndent) {
3396
+ const result = {};
3397
+ const overridableKeys = /* @__PURE__ */ new Set();
3398
+ let allowCompact = false;
3399
+ let line;
3400
+ let pos;
3401
+ let keyTag = null;
3402
+ let keyNode = null;
3403
+ let valueNode = null;
3404
+ let atExplicitKey = false;
3405
+ let detected = false;
3406
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3407
+ let ch = this.peek();
3408
+ while (ch !== 0) {
3409
+ const following = this.peek(1);
3410
+ line = this.line;
3411
+ pos = this.position;
3412
+ if ((ch === QUESTION || ch === COLON) && isWhiteSpaceOrEOL(following)) {
3413
+ if (ch === QUESTION) {
3414
+ if (atExplicitKey) {
3415
+ this.storeMappingPair(result, overridableKeys, keyTag, keyNode, null);
3416
+ keyTag = null;
3417
+ keyNode = null;
3418
+ valueNode = null;
3419
+ }
3420
+ detected = true;
3421
+ atExplicitKey = true;
3422
+ allowCompact = true;
3423
+ } else if (atExplicitKey) {
3424
+ atExplicitKey = false;
3425
+ allowCompact = true;
3426
+ } else {
3427
+ throw this.#createError("Cannot read block as explicit mapping pair is incomplete: a key node is missed or followed by a non-tabulated empty line");
3428
+ }
3429
+ this.position += 1;
3430
+ ch = following;
3431
+ } else {
3432
+ const newState = this.composeNode({
3433
+ parentIndent: flowIndent,
3434
+ nodeContext: CONTEXT_FLOW_OUT,
3435
+ allowToSeek: false,
3436
+ allowCompact: true
3437
+ });
3438
+ if (!newState) break;
3439
+ if (this.line === line) {
3440
+ ch = this.peek();
3441
+ this.skipWhitespaces();
3442
+ ch = this.peek();
3443
+ if (ch === COLON) {
3444
+ ch = this.next();
3445
+ if (!isWhiteSpaceOrEOL(ch)) {
3446
+ throw this.#createError("Cannot read block: a whitespace character is expected after the key-value separator within a block mapping");
3447
+ }
3448
+ if (atExplicitKey) {
3449
+ this.storeMappingPair(result, overridableKeys, keyTag, keyNode, null);
3450
+ keyTag = null;
3451
+ keyNode = null;
3452
+ valueNode = null;
3453
+ }
3454
+ detected = true;
3455
+ atExplicitKey = false;
3456
+ allowCompact = false;
3457
+ keyTag = newState.tag;
3458
+ keyNode = newState.result;
3459
+ } else if (detected) {
3460
+ throw this.#createError("Cannot read an implicit mapping pair: missing colon");
3461
+ } else {
3462
+ const { kind, result: result2 } = newState;
3463
+ return {
3464
+ tag,
3465
+ anchor,
3466
+ kind,
3467
+ result: result2
3468
+ };
3469
+ }
3470
+ } else if (detected) {
3471
+ throw this.#createError("Cannot read a block mapping entry: a multiline key may not be an implicit key");
3472
+ } else {
3473
+ const { kind, result: result2 } = newState;
3474
+ return {
3475
+ tag,
3476
+ anchor,
3477
+ kind,
3478
+ result: result2
3479
+ };
3480
+ }
3481
+ }
3482
+ if (this.line === line || this.lineIndent > nodeIndent) {
3483
+ const newState = this.composeNode({
3484
+ parentIndent: nodeIndent,
3485
+ nodeContext: CONTEXT_BLOCK_OUT,
3486
+ allowToSeek: true,
3487
+ allowCompact
3488
+ });
3489
+ if (newState) {
3490
+ if (atExplicitKey) {
3491
+ keyNode = newState.result;
3492
+ } else {
3493
+ valueNode = newState.result;
3494
+ }
3495
+ }
3496
+ if (!atExplicitKey) {
3497
+ this.storeMappingPair(result, overridableKeys, keyTag, keyNode, valueNode, line, pos);
3498
+ keyTag = keyNode = valueNode = null;
3499
+ }
3500
+ this.skipSeparationSpace(true, -1);
3501
+ ch = this.peek();
3502
+ }
3503
+ if (this.lineIndent > nodeIndent && ch !== 0) {
3504
+ throw this.#createError("Cannot read block: bad indentation of a mapping entry");
3505
+ } else if (this.lineIndent < nodeIndent) {
3506
+ break;
3507
+ }
3508
+ }
3509
+ if (atExplicitKey) {
3510
+ this.storeMappingPair(result, overridableKeys, keyTag, keyNode, null);
3511
+ }
3512
+ if (detected) return {
3513
+ tag,
3514
+ anchor,
3515
+ kind: "mapping",
3516
+ result
3517
+ };
3518
+ }
3519
+ readTagProperty(tag) {
3520
+ let isVerbatim = false;
3521
+ let isNamed = false;
3522
+ let tagHandle = "";
3523
+ let tagName;
3524
+ let ch = this.peek();
3525
+ if (ch !== EXCLAMATION) return;
3526
+ if (tag !== null) {
3527
+ throw this.#createError("Cannot read tag property: duplication of a tag property");
3528
+ }
3529
+ ch = this.next();
3530
+ if (ch === SMALLER_THAN) {
3531
+ isVerbatim = true;
3532
+ ch = this.next();
3533
+ } else if (ch === EXCLAMATION) {
3534
+ isNamed = true;
3535
+ tagHandle = "!!";
3536
+ ch = this.next();
3537
+ } else {
3538
+ tagHandle = "!";
3539
+ }
3540
+ let position = this.position;
3541
+ if (isVerbatim) {
3542
+ do {
3543
+ ch = this.next();
3544
+ } while (ch !== 0 && ch !== GREATER_THAN);
3545
+ if (this.position < this.length) {
3546
+ tagName = this.input.slice(position, this.position);
3547
+ ch = this.next();
3548
+ } else {
3549
+ throw this.#createError("Cannot read tag property: unexpected end of stream");
3550
+ }
3551
+ } else {
3552
+ while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
3553
+ if (ch === EXCLAMATION) {
3554
+ if (!isNamed) {
3555
+ tagHandle = this.input.slice(position - 1, this.position + 1);
3556
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
3557
+ throw this.#createError("Cannot read tag property: named tag handle contains invalid characters");
3558
+ }
3559
+ isNamed = true;
3560
+ position = this.position + 1;
3561
+ } else {
3562
+ throw this.#createError("Cannot read tag property: tag suffix cannot contain an exclamation mark");
3563
+ }
3564
+ }
3565
+ ch = this.next();
3566
+ }
3567
+ tagName = this.input.slice(position, this.position);
3568
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
3569
+ throw this.#createError("Cannot read tag property: tag suffix cannot contain flow indicator characters");
3570
+ }
3571
+ }
3572
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
3573
+ throw this.#createError(`Cannot read tag property: invalid characters in tag name "${tagName}"`);
3574
+ }
3575
+ if (isVerbatim) {
3576
+ return tagName;
3577
+ } else if (this.tagMap.has(tagHandle)) {
3578
+ return this.tagMap.get(tagHandle) + tagName;
3579
+ } else if (tagHandle === "!") {
3580
+ return `!${tagName}`;
3581
+ } else if (tagHandle === "!!") {
3582
+ return `tag:yaml.org,2002:${tagName}`;
3583
+ }
3584
+ throw this.#createError(`Cannot read tag property: undeclared tag handle "${tagHandle}"`);
3585
+ }
3586
+ readAnchorProperty(anchor) {
3587
+ let ch = this.peek();
3588
+ if (ch !== AMPERSAND) return;
3589
+ if (anchor !== null) {
3590
+ throw this.#createError("Cannot read anchor property: duplicate anchor property");
3591
+ }
3592
+ ch = this.next();
3593
+ const position = this.position;
3594
+ while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) {
3595
+ ch = this.next();
3596
+ }
3597
+ if (this.position === position) {
3598
+ throw this.#createError("Cannot read anchor property: name of an anchor node must contain at least one character");
3599
+ }
3600
+ return this.input.slice(position, this.position);
3601
+ }
3602
+ readAlias() {
3603
+ if (this.peek() !== ASTERISK) return;
3604
+ let ch = this.next();
3605
+ const position = this.position;
3606
+ while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) {
3607
+ ch = this.next();
3608
+ }
3609
+ if (this.position === position) {
3610
+ throw this.#createError("Cannot read alias: alias name must contain at least one character");
3611
+ }
3612
+ const alias = this.input.slice(position, this.position);
3613
+ if (!this.anchorMap.has(alias)) {
3614
+ throw this.#createError(`Cannot read alias: unidentified alias "${alias}"`);
3615
+ }
3616
+ this.skipSeparationSpace(true, -1);
3617
+ return this.anchorMap.get(alias);
3618
+ }
3619
+ resolveTag(state) {
3620
+ switch (state.tag) {
3621
+ case null:
3622
+ case "!":
3623
+ return state;
3624
+ case "?": {
3625
+ for (const type2 of this.implicitTypes) {
3626
+ if (!type2.resolve(state.result)) continue;
3627
+ const result2 = type2.construct(state.result);
3628
+ state.result = result2;
3629
+ state.tag = type2.tag;
3630
+ const { anchor: anchor2 } = state;
3631
+ if (anchor2 !== null) this.anchorMap.set(anchor2, result2);
3632
+ return state;
3633
+ }
3634
+ return state;
3635
+ }
3636
+ }
3637
+ const kind = state.kind ?? "fallback";
3638
+ const map2 = this.typeMap[kind];
3639
+ const type = map2.get(state.tag);
3640
+ if (!type) {
3641
+ throw this.#createError(`Cannot resolve unknown tag !<${state.tag}>`);
3642
+ }
3643
+ if (state.result !== null && type.kind !== state.kind) {
3644
+ throw this.#createError(`Unacceptable node kind for !<${state.tag}> tag: it should be "${type.kind}", not "${state.kind}"`);
3645
+ }
3646
+ if (!type.resolve(state.result)) {
3647
+ throw this.#createError(`Cannot resolve a node with !<${state.tag}> explicit tag`);
3648
+ }
3649
+ const result = type.construct(state.result);
3650
+ state.result = result;
3651
+ const { anchor } = state;
3652
+ if (anchor !== null) this.anchorMap.set(anchor, result);
3653
+ return state;
3654
+ }
3655
+ composeNode({ parentIndent, nodeContext, allowToSeek, allowCompact }) {
3656
+ let indentStatus = 1;
3657
+ let atNewLine = false;
3658
+ const allowBlockScalars = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
3659
+ let allowBlockCollections = allowBlockScalars;
3660
+ const allowBlockStyles = allowBlockScalars;
3661
+ if (allowToSeek) {
3662
+ if (this.skipSeparationSpace(true, -1)) {
3663
+ atNewLine = true;
3664
+ indentStatus = getIndentStatus(this.lineIndent, parentIndent);
3665
+ }
3666
+ }
3667
+ let tag = null;
3668
+ let anchor = null;
3669
+ if (indentStatus === 1) {
3670
+ while (true) {
3671
+ const newTag = this.readTagProperty(tag);
3672
+ if (newTag) {
3673
+ tag = newTag;
3674
+ } else {
3675
+ const newAnchor = this.readAnchorProperty(anchor);
3676
+ if (!newAnchor) break;
3677
+ anchor = newAnchor;
3678
+ }
3679
+ if (this.skipSeparationSpace(true, -1)) {
3680
+ atNewLine = true;
3681
+ allowBlockCollections = allowBlockStyles;
3682
+ indentStatus = getIndentStatus(this.lineIndent, parentIndent);
3683
+ } else {
3684
+ allowBlockCollections = false;
3685
+ }
3686
+ }
3687
+ }
3688
+ if (allowBlockCollections) {
3689
+ allowBlockCollections = atNewLine || allowCompact;
3690
+ }
3691
+ if (indentStatus === 1) {
3692
+ const cond = CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext;
3693
+ const flowIndent = cond ? parentIndent : parentIndent + 1;
3694
+ if (allowBlockCollections) {
3695
+ const blockIndent = this.position - this.lineStart;
3696
+ const blockSequenceState = this.readBlockSequence(tag, anchor, blockIndent);
3697
+ if (blockSequenceState) return this.resolveTag(blockSequenceState);
3698
+ const blockMappingState = this.readBlockMapping(tag, anchor, blockIndent, flowIndent);
3699
+ if (blockMappingState) return this.resolveTag(blockMappingState);
3700
+ }
3701
+ const flowCollectionState = this.readFlowCollection(tag, anchor, flowIndent);
3702
+ if (flowCollectionState) return this.resolveTag(flowCollectionState);
3703
+ if (allowBlockScalars) {
3704
+ const blockScalarState = this.readBlockScalar(tag, anchor, flowIndent);
3705
+ if (blockScalarState) return this.resolveTag(blockScalarState);
3706
+ }
3707
+ const singleQuoteState = this.readSingleQuotedScalar(tag, anchor, flowIndent);
3708
+ if (singleQuoteState) return this.resolveTag(singleQuoteState);
3709
+ const doubleQuoteState = this.readDoubleQuotedScalar(tag, anchor, flowIndent);
3710
+ if (doubleQuoteState) return this.resolveTag(doubleQuoteState);
3711
+ const alias = this.readAlias();
3712
+ if (alias) {
3713
+ if (tag !== null || anchor !== null) {
3714
+ throw this.#createError("Cannot compose node: alias node should not have any properties");
3715
+ }
3716
+ return this.resolveTag({
3717
+ tag,
3718
+ anchor,
3719
+ kind: null,
3720
+ result: alias
3721
+ });
3722
+ }
3723
+ const plainScalarState = this.readPlainScalar(tag, anchor, flowIndent, CONTEXT_FLOW_IN === nodeContext);
3724
+ if (plainScalarState) {
3725
+ plainScalarState.tag ??= "?";
3726
+ return this.resolveTag(plainScalarState);
3727
+ }
3728
+ } else if (indentStatus === 0 && CONTEXT_BLOCK_OUT === nodeContext && allowBlockCollections) {
3729
+ const blockIndent = this.position - this.lineStart;
3730
+ const newState2 = this.readBlockSequence(tag, anchor, blockIndent);
3731
+ if (newState2) return this.resolveTag(newState2);
3732
+ }
3733
+ const newState = this.resolveTag({
3734
+ tag,
3735
+ anchor,
3736
+ kind: null,
3737
+ result: null
3738
+ });
3739
+ if (newState.tag !== null || newState.anchor !== null) return newState;
3740
+ }
3741
+ readDirectives() {
3742
+ let hasDirectives = false;
3743
+ let version = null;
3744
+ let ch = this.peek();
3745
+ while (ch !== 0) {
3746
+ this.skipSeparationSpace(true, -1);
3747
+ ch = this.peek();
3748
+ if (this.lineIndent > 0 || ch !== PERCENT) {
3749
+ break;
3750
+ }
3751
+ hasDirectives = true;
3752
+ ch = this.next();
3753
+ let position = this.position;
3754
+ while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
3755
+ ch = this.next();
3756
+ }
3757
+ const directiveName = this.input.slice(position, this.position);
3758
+ const directiveArgs = [];
3759
+ if (directiveName.length < 1) {
3760
+ throw this.#createError("Cannot read document: directive name length must be greater than zero");
3761
+ }
3762
+ while (ch !== 0) {
3763
+ this.skipWhitespaces();
3764
+ this.skipComment();
3765
+ ch = this.peek();
3766
+ if (isEOL(ch)) break;
3767
+ position = this.position;
3768
+ while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
3769
+ ch = this.next();
3770
+ }
3771
+ directiveArgs.push(this.input.slice(position, this.position));
3772
+ }
3773
+ if (ch !== 0) this.readLineBreak();
3774
+ switch (directiveName) {
3775
+ case "YAML":
3776
+ if (version !== null) {
3777
+ throw this.#createError("Cannot handle YAML directive: duplication of %YAML directive");
3778
+ }
3779
+ version = this.yamlDirectiveHandler(directiveArgs);
3780
+ break;
3781
+ case "TAG":
3782
+ this.tagDirectiveHandler(directiveArgs);
3783
+ break;
3784
+ default:
3785
+ this.dispatchWarning(`unknown document directive "${directiveName}"`);
3786
+ break;
3787
+ }
3788
+ ch = this.peek();
3789
+ }
3790
+ return hasDirectives;
3791
+ }
3792
+ readDocument() {
3793
+ const documentStart = this.position;
3794
+ this.checkLineBreaks = false;
3795
+ this.tagMap = /* @__PURE__ */ new Map();
3796
+ this.anchorMap = /* @__PURE__ */ new Map();
3797
+ const hasDirectives = this.readDirectives();
3798
+ this.skipSeparationSpace(true, -1);
3799
+ let result = null;
3800
+ if (this.lineIndent === 0 && this.peek() === MINUS && this.peek(1) === MINUS && this.peek(2) === MINUS) {
3801
+ this.position += 3;
3802
+ this.skipSeparationSpace(true, -1);
3803
+ } else if (hasDirectives) {
3804
+ throw this.#createError("Cannot read document: directives end mark is expected");
3805
+ }
3806
+ const newState = this.composeNode({
3807
+ parentIndent: this.lineIndent - 1,
3808
+ nodeContext: CONTEXT_BLOCK_OUT,
3809
+ allowToSeek: false,
3810
+ allowCompact: true
3811
+ });
3812
+ if (newState) result = newState.result;
3813
+ this.skipSeparationSpace(true, -1);
3814
+ if (this.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(this.input.slice(documentStart, this.position))) {
3815
+ this.dispatchWarning("non-ASCII line breaks are interpreted as content");
3816
+ }
3817
+ if (this.position === this.lineStart && this.testDocumentSeparator()) {
3818
+ if (this.peek() === DOT) {
3819
+ this.position += 3;
3820
+ this.skipSeparationSpace(true, -1);
3821
+ }
3822
+ } else if (this.position < this.length - 1) {
3823
+ throw this.#createError("Cannot read document: end of the stream or a document separator is expected");
3824
+ }
3825
+ return result;
3826
+ }
3827
+ *readDocuments() {
3828
+ while (this.position < this.length - 1) {
3829
+ yield this.readDocument();
3830
+ }
3831
+ }
3832
+ };
3833
+
3834
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@jsr/std__yaml/parse.js
3835
+ function sanitizeInput(input) {
3836
+ input = String(input);
3837
+ if (input.length > 0) {
3838
+ if (!isEOL(input.charCodeAt(input.length - 1))) input += "\n";
3839
+ if (input.charCodeAt(0) === 65279) input = input.slice(1);
3840
+ }
3841
+ input += "\0";
3842
+ return input;
3843
+ }
3844
+ function parse(content, options = {}) {
3845
+ content = sanitizeInput(content);
3846
+ const state = new LoaderState(content, {
3847
+ ...options,
3848
+ schema: SCHEMA_MAP.get(options.schema)
3849
+ });
3850
+ const documentGenerator = state.readDocuments();
3851
+ const document = documentGenerator.next().value;
3852
+ if (!documentGenerator.next().done) {
3853
+ throw new SyntaxError("Found more than 1 document in the stream: expected a single document");
3854
+ }
3855
+ return document ?? null;
3856
+ }
3857
+
3858
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@mcpc/plugin-markdown-loader/src/markdown-loader.js
3859
+ import process5 from "node:process";
3860
+ function replaceEnvVars(str2) {
3861
+ return str2.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, varName) => {
3862
+ return process5.env[varName] || "";
3863
+ });
3864
+ }
3865
+ function replaceEnvVarsInObject(obj) {
3866
+ if (typeof obj === "string") {
3867
+ return replaceEnvVars(obj);
3868
+ }
3869
+ if (Array.isArray(obj)) {
3870
+ return obj.map((item) => replaceEnvVarsInObject(item));
3871
+ }
3872
+ if (obj && typeof obj === "object") {
3873
+ const result = {};
3874
+ for (const [key, value] of Object.entries(obj)) {
3875
+ result[key] = replaceEnvVarsInObject(value);
3876
+ }
3877
+ return result;
3878
+ }
3879
+ return obj;
3880
+ }
3881
+ function parseMarkdownAgent(content) {
3882
+ const frontMatterRegex = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
3883
+ const match = content.match(frontMatterRegex);
3884
+ if (!match) {
3885
+ throw new Error("Invalid Markdown agent file: missing YAML front matter. Expected format:\n---\nname: agent-name\n---\n\n# Description...");
3886
+ }
3887
+ const [, yamlContent, markdownContent] = match;
3888
+ let frontMatter;
3889
+ try {
3890
+ frontMatter = parse(yamlContent);
3891
+ } catch (error) {
3892
+ throw new Error(`Failed to parse YAML front matter: ${error}`);
3893
+ }
3894
+ if (!frontMatter.name) {
3895
+ throw new Error("Invalid Markdown agent file: 'name' is required in front matter");
3896
+ }
3897
+ return {
3898
+ frontMatter,
3899
+ description: markdownContent.trim()
3900
+ };
3901
+ }
3902
+ var OPTION_KEYS = [
3903
+ "mode",
3904
+ "maxSteps",
3905
+ "maxTokens",
3906
+ "tracingEnabled",
3907
+ "refs",
3908
+ "samplingConfig",
3909
+ "providerOptions",
3910
+ "acpSettings"
3911
+ ];
3912
+ function markdownAgentToComposeDefinition(parsed) {
3913
+ const frontMatter = replaceEnvVarsInObject(parsed.frontMatter);
3914
+ const description = replaceEnvVars(parsed.description);
3915
+ const options = {};
3916
+ for (const key of OPTION_KEYS) {
3917
+ if (frontMatter[key] !== void 0) {
3918
+ options[key] = frontMatter[key];
3919
+ }
3920
+ }
3921
+ return {
3922
+ name: frontMatter.name,
3923
+ description,
3924
+ deps: frontMatter.deps,
3925
+ plugins: frontMatter.plugins,
3926
+ ...Object.keys(options).length > 0 ? {
3927
+ options
3928
+ } : {}
3929
+ };
3930
+ }
3931
+ async function loadMarkdownAgentFile(filePath) {
3932
+ const content = await readFile(filePath, "utf-8");
3933
+ const parsed = parseMarkdownAgent(content);
3934
+ return markdownAgentToComposeDefinition(parsed);
3935
+ }
3936
+
3937
+ // __mcpc__plugin-markdown-loader_latest/node_modules/@mcpc/plugin-markdown-loader/mod.ts
3938
+ function markdownLoaderPlugin() {
3939
+ return {
3940
+ name: "markdown-loader",
3941
+ version: "1.0.0",
3942
+ enforce: "pre",
3943
+ // Run before other plugins
3944
+ configureServer: () => {
3945
+ setMarkdownAgentLoader(loadMarkdownAgentFile);
3946
+ }
3947
+ };
3948
+ }
3949
+ var createPlugin = markdownLoaderPlugin;
3950
+ var defaultPlugin = markdownLoaderPlugin();
3951
+ var mod_default = defaultPlugin;
3952
+ export {
3953
+ createPlugin,
3954
+ mod_default as default,
3955
+ isMarkdownFile as isMarkdownAgentFile,
3956
+ loadMarkdownAgentFile,
3957
+ markdownAgentToComposeDefinition,
3958
+ markdownLoaderPlugin,
3959
+ parseMarkdownAgent,
3960
+ setMarkdownAgentLoader
3961
+ };