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