@mcpc-tech/cli 0.1.24 → 0.1.26

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.
Files changed (3) hide show
  1. package/bin/mcpc.cjs +251 -2527
  2. package/bin/mcpc.mjs +251 -2527
  3. package/package.json +2 -1
package/bin/mcpc.cjs CHANGED
@@ -502,7 +502,7 @@ var require_cross_spawn = __commonJS({
502
502
  var cp = require("child_process");
503
503
  var parse = require_parse();
504
504
  var enoent = require_enoent();
505
- function spawn3(command, args, options) {
505
+ function spawn2(command, args, options) {
506
506
  const parsed = parse(command, args, options);
507
507
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
508
508
  enoent.hookChildProcess(spawned, parsed);
@@ -514,8 +514,8 @@ var require_cross_spawn = __commonJS({
514
514
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
515
515
  return result;
516
516
  }
517
- module2.exports = spawn3;
518
- module2.exports.spawn = spawn3;
517
+ module2.exports = spawn2;
518
+ module2.exports.spawn = spawn2;
519
519
  module2.exports.sync = spawnSync;
520
520
  module2.exports._parse = parse;
521
521
  module2.exports._enoent = enoent;
@@ -2372,19 +2372,9 @@ var Response2 = class _Response {
2372
2372
  });
2373
2373
  Object.setPrototypeOf(Response2, GlobalResponse);
2374
2374
  Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
2375
- var webFetch = global.fetch;
2376
2375
  if (typeof global.crypto === "undefined") {
2377
2376
  global.crypto = import_crypto.default;
2378
2377
  }
2379
- global.fetch = (info, init) => {
2380
- init = {
2381
- // Disable compression handling so people can return the result of a fetch
2382
- // directly in the loader without messing with the Content-Encoding header.
2383
- compress: false,
2384
- ...init
2385
- };
2386
- return webFetch(info, init);
2387
- };
2388
2378
  var outgoingEnded = Symbol("outgoingEnded");
2389
2379
 
2390
2380
  // __mcpc__cli_latest/node_modules/@mcpc/cli/src/config/loader.js
@@ -5161,17 +5151,17 @@ var Client = class extends Protocol {
5161
5151
  this._cachedToolOutputValidators.clear();
5162
5152
  this._cachedKnownTaskTools.clear();
5163
5153
  this._cachedRequiredTaskTools.clear();
5164
- for (const tool3 of tools) {
5165
- if (tool3.outputSchema) {
5166
- const toolValidator = this._jsonSchemaValidator.getValidator(tool3.outputSchema);
5167
- this._cachedToolOutputValidators.set(tool3.name, toolValidator);
5154
+ for (const tool2 of tools) {
5155
+ if (tool2.outputSchema) {
5156
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool2.outputSchema);
5157
+ this._cachedToolOutputValidators.set(tool2.name, toolValidator);
5168
5158
  }
5169
- const taskSupport = tool3.execution?.taskSupport;
5159
+ const taskSupport = tool2.execution?.taskSupport;
5170
5160
  if (taskSupport === "required" || taskSupport === "optional") {
5171
- this._cachedKnownTaskTools.add(tool3.name);
5161
+ this._cachedKnownTaskTools.add(tool2.name);
5172
5162
  }
5173
5163
  if (taskSupport === "required") {
5174
- this._cachedRequiredTaskTools.add(tool3.name);
5164
+ this._cachedRequiredTaskTools.add(tool2.name);
5175
5165
  }
5176
5166
  }
5177
5167
  }
@@ -7468,14 +7458,14 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
7468
7458
  acquiredKeys.push(defKey);
7469
7459
  allClients[serverId] = client;
7470
7460
  const { tools } = await client.listTools();
7471
- tools.forEach((tool3) => {
7472
- const toolNameWithScope = `${name}.${tool3.name}`;
7473
- const internalToolName = tool3.name;
7461
+ tools.forEach((tool2) => {
7462
+ const toolNameWithScope = `${name}.${tool2.name}`;
7463
+ const internalToolName = tool2.name;
7474
7464
  const rawToolId = `${serverId}_${internalToolName}`;
7475
7465
  const toolId = sanitizePropertyKey(rawToolId);
7476
7466
  if (filterIn && !filterIn({
7477
7467
  action: internalToolName,
7478
- tool: tool3,
7468
+ tool: tool2,
7479
7469
  mcpName: name,
7480
7470
  toolNameWithScope,
7481
7471
  internalToolName,
@@ -7490,7 +7480,7 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
7490
7480
  timeout: def.toolCallTimeout
7491
7481
  });
7492
7482
  allTools[toolId] = {
7493
- ...tool3,
7483
+ ...tool2,
7494
7484
  execute,
7495
7485
  _originalName: toolNameWithScope
7496
7486
  };
@@ -7553,13 +7543,13 @@ var createConfigPlugin = () => ({
7553
7543
  name: "built-in-config",
7554
7544
  version: "1.0.0",
7555
7545
  enforce: "pre",
7556
- transformTool: (tool3, context2) => {
7546
+ transformTool: (tool2, context2) => {
7557
7547
  const server = context2.server;
7558
7548
  const config = server.findToolConfig?.(context2.toolName);
7559
7549
  if (config?.description) {
7560
- tool3.description = config.description;
7550
+ tool2.description = config.description;
7561
7551
  }
7562
- return tool3;
7552
+ return tool2;
7563
7553
  }
7564
7554
  });
7565
7555
  var config_plugin_default = createConfigPlugin();
@@ -7569,10 +7559,10 @@ var createToolNameMappingPlugin = () => ({
7569
7559
  name: "built-in-tool-name-mapping",
7570
7560
  version: "1.0.0",
7571
7561
  enforce: "pre",
7572
- transformTool: (tool3, context2) => {
7562
+ transformTool: (tool2, context2) => {
7573
7563
  const server = context2.server;
7574
7564
  const toolName = context2.toolName;
7575
- const originalName = tool3._originalName || toolName;
7565
+ const originalName = tool2._originalName || toolName;
7576
7566
  const dotNotation = originalName.replace(/_/g, ".");
7577
7567
  const underscoreNotation = originalName.replace(/\./g, "_");
7578
7568
  if (dotNotation !== originalName && server.toolNameMapping) {
@@ -7584,7 +7574,7 @@ var createToolNameMappingPlugin = () => ({
7584
7574
  if (originalName !== toolName && server.toolNameMapping) {
7585
7575
  server.toolNameMapping.set(originalName, toolName);
7586
7576
  }
7587
- return tool3;
7577
+ return tool2;
7588
7578
  }
7589
7579
  });
7590
7580
  var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
@@ -8077,13 +8067,13 @@ var PromptUtils = {
8077
8067
  * Generate tool list for descriptions
8078
8068
  */
8079
8069
  generateToolList: (tools) => {
8080
- return tools.filter((tool3) => !tool3.hide).map((tool3) => `<tool name="${tool3.name}"${tool3.description ? ` description="${tool3.description}"` : ""}/>`).join("\n");
8070
+ return tools.filter((tool2) => !tool2.hide).map((tool2) => `<tool name="${tool2.name}"${tool2.description ? ` description="${tool2.description}"` : ""}/>`).join("\n");
8081
8071
  },
8082
8072
  /**
8083
8073
  * Generate hidden tool list for descriptions
8084
8074
  */
8085
8075
  generateHiddenToolList: (tools) => {
8086
- return tools.filter((tool3) => tool3.hide).map((tool3) => `<tool name="${tool3.name}" hide/>`).join("\n");
8076
+ return tools.filter((tool2) => tool2.hide).map((tool2) => `<tool name="${tool2.name}" hide/>`).join("\n");
8087
8077
  },
8088
8078
  /**
8089
8079
  * Format workflow steps for display
@@ -9868,12 +9858,12 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
9868
9858
  }
9869
9859
  buildDepGroups() {
9870
9860
  const depGroups = {};
9871
- this.toolNameToDetailList.forEach(([toolName, tool3]) => {
9872
- if (tool3?.inputSchema) {
9861
+ this.toolNameToDetailList.forEach(([toolName, tool2]) => {
9862
+ if (tool2?.inputSchema) {
9873
9863
  depGroups[toolName] = {
9874
9864
  type: "object",
9875
- description: tool3.description || `Tool: ${toolName}`,
9876
- ...tool3.inputSchema
9865
+ description: tool2.description || `Tool: ${toolName}`,
9866
+ ...tool2.inputSchema
9877
9867
  };
9878
9868
  } else {
9879
9869
  const toolSchema = this.server.getHiddenToolSchema(toolName);
@@ -9930,10 +9920,10 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
9930
9920
  }
9931
9921
  buildSystemPrompt(userRequest, agenticSchema, context2) {
9932
9922
  const toolList = this.allToolNames.map((name) => {
9933
- const tool3 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9923
+ const tool2 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9934
9924
  const toolSchema = this.server.getHiddenToolSchema(name);
9935
- if (tool3 && tool3[1]) {
9936
- return `- ${name}: ${tool3[1].description || `Tool: ${name}`}`;
9925
+ if (tool2 && tool2[1]) {
9926
+ return `- ${name}: ${tool2[1].description || `Tool: ${name}`}`;
9937
9927
  } else if (toolSchema) {
9938
9928
  return `- ${name}: ${toolSchema.description}`;
9939
9929
  }
@@ -9960,7 +9950,7 @@ ${JSON.stringify(context2, null, 2)}`;
9960
9950
  ## Current Task
9961
9951
  You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
9962
9952
 
9963
- When you need to use a tool, specify the tool name in 'action' and provide tool-specific parameters as additional properties.`;
9953
+ When you need to use a tool, specify the tool name in 'useTool' and provide tool-specific parameters as additional properties.`;
9964
9954
  return this.formatPromptForMode({
9965
9955
  prompt: basePrompt + taskPrompt,
9966
9956
  schema: agenticSchema
@@ -10156,8 +10146,9 @@ function convertAISDKToMCPMessages(prompt) {
10156
10146
  if (toolCalls.length > 0) {
10157
10147
  const calls = toolCalls.map((c) => {
10158
10148
  const call = c;
10149
+ const toolArgs = call.args ?? call.input ?? {};
10159
10150
  return `<use_tool tool="${call.toolName}">
10160
- ${JSON.stringify(call.input || {})}
10151
+ ${JSON.stringify(toolArgs)}
10161
10152
  </use_tool>`;
10162
10153
  });
10163
10154
  parts.push(calls.join("\n"));
@@ -10165,7 +10156,8 @@ ${JSON.stringify(call.input || {})}
10165
10156
  if (toolResults.length > 0) {
10166
10157
  const results = toolResults.map((c) => {
10167
10158
  const result = c;
10168
- const output = JSON.stringify(result.output || result.result || "undefined");
10159
+ const resultValue = result.result ?? result.output ?? "undefined";
10160
+ const output = JSON.stringify(resultValue);
10169
10161
  return `Tool "${result.toolName}" result:
10170
10162
  ${output}`;
10171
10163
  });
@@ -10210,7 +10202,16 @@ var MCPSamplingLanguageModel = class {
10210
10202
  * Generate a response using MCP's createMessage capability
10211
10203
  */
10212
10204
  async doGenerate(options) {
10213
- const messages = this.convertMessages(options.prompt);
10205
+ const useNativeTools = this.supportsSamplingTools();
10206
+ this.server.sendLoggingMessage({
10207
+ level: "info",
10208
+ data: `Client supports native tools: ${useNativeTools}`
10209
+ });
10210
+ const messages = this.convertMessages(options.prompt, useNativeTools);
10211
+ this.server.sendLoggingMessage({
10212
+ level: "info",
10213
+ data: `Converted messages for MCP: ${JSON.stringify(messages)}`
10214
+ });
10214
10215
  let systemPrompt;
10215
10216
  for (const msg of options.prompt) {
10216
10217
  if (msg.role === "system") {
@@ -10218,7 +10219,10 @@ var MCPSamplingLanguageModel = class {
10218
10219
  break;
10219
10220
  }
10220
10221
  }
10221
- const useNativeTools = this.supportsSamplingTools();
10222
+ this.server.sendLoggingMessage({
10223
+ level: "info",
10224
+ data: `Client supports native tools: ${useNativeTools}`
10225
+ });
10222
10226
  systemPrompt = this.injectResponseFormatInstructions(systemPrompt, options.responseFormat, useNativeTools);
10223
10227
  systemPrompt = this.injectToolInstructions(systemPrompt, options.tools, useNativeTools);
10224
10228
  const createMessageParams = {
@@ -10232,8 +10236,34 @@ var MCPSamplingLanguageModel = class {
10232
10236
  createMessageParams.toolChoice = {
10233
10237
  mode: "auto"
10234
10238
  };
10239
+ this.server.sendLoggingMessage({
10240
+ level: "info",
10241
+ data: `Converted ${options.tools.length} tools to MCP format: ${JSON.stringify(createMessageParams.tools?.map((t) => t.name))}`
10242
+ });
10243
+ } else if (options.tools && options.tools.length > 0) {
10244
+ this.server.sendLoggingMessage({
10245
+ level: "info",
10246
+ data: `Tools provided but not using native mode - injecting into system prompt instead`
10247
+ });
10235
10248
  }
10249
+ this.server.sendLoggingMessage({
10250
+ level: "info",
10251
+ data: `Calling createMessage with params: ${JSON.stringify({
10252
+ hasSystemPrompt: !!systemPrompt,
10253
+ hasTools: !!createMessageParams.tools,
10254
+ toolCount: createMessageParams.tools?.length || 0,
10255
+ createMessageParams
10256
+ }, null, 2)}`
10257
+ });
10236
10258
  const result = await this.server.createMessage(createMessageParams);
10259
+ this.server.sendLoggingMessage({
10260
+ level: "info",
10261
+ data: `createMessage result: ${JSON.stringify({
10262
+ contentType: result.content.type,
10263
+ stopReason: result.stopReason,
10264
+ text: result.content
10265
+ })}`
10266
+ });
10237
10267
  const content = [];
10238
10268
  if (useNativeTools) {
10239
10269
  const contentArray = Array.isArray(result.content) ? result.content : [
@@ -10351,8 +10381,52 @@ var MCPSamplingLanguageModel = class {
10351
10381
  /**
10352
10382
  * Convert AI SDK messages to MCP sampling format
10353
10383
  */
10354
- convertMessages(prompt) {
10355
- return convertAISDKToMCPMessages(prompt);
10384
+ convertMessages(prompt, useNativeTools) {
10385
+ if (!useNativeTools) {
10386
+ return convertAISDKToMCPMessages(prompt);
10387
+ }
10388
+ const messages = [];
10389
+ for (const msg of prompt) {
10390
+ if (msg.role === "system") continue;
10391
+ const role = msg.role === "assistant" ? "assistant" : "user";
10392
+ const contentBlocks = [];
10393
+ for (const part of msg.content) {
10394
+ if (part.type === "text") {
10395
+ contentBlocks.push({
10396
+ type: "text",
10397
+ text: part.text
10398
+ });
10399
+ } else if (part.type === "tool-call") {
10400
+ const call = part;
10401
+ contentBlocks.push({
10402
+ type: "tool_use",
10403
+ id: call.toolCallId,
10404
+ name: call.toolName,
10405
+ input: call.args ?? call.input ?? {}
10406
+ });
10407
+ } else if (part.type === "tool-result") {
10408
+ const result = part;
10409
+ contentBlocks.push({
10410
+ type: "tool_result",
10411
+ toolUseId: result.toolCallId,
10412
+ // TODO: Handle different result types properly
10413
+ content: [
10414
+ {
10415
+ type: "text",
10416
+ text: result.output.type === "text" ? result.output.value?.toString() : JSON.stringify(result.output)
10417
+ }
10418
+ ]
10419
+ });
10420
+ }
10421
+ }
10422
+ if (contentBlocks.length > 0) {
10423
+ messages.push({
10424
+ role,
10425
+ content: contentBlocks
10426
+ });
10427
+ }
10428
+ }
10429
+ return messages;
10356
10430
  }
10357
10431
  /**
10358
10432
  * Map MCP stop reason to AI SDK finish reason
@@ -10365,18 +10439,23 @@ var MCPSamplingLanguageModel = class {
10365
10439
  */
10366
10440
  supportsSamplingTools() {
10367
10441
  const capabilities = this.server.getClientCapabilities();
10368
- return !!capabilities?.sampling?.tools;
10442
+ const supportsTools = !!capabilities?.sampling?.tools;
10443
+ this.server.sendLoggingMessage({
10444
+ level: "info",
10445
+ data: `Client capabilities check: sampling=${!!capabilities?.sampling}, tools=${supportsTools}`
10446
+ });
10447
+ return supportsTools;
10369
10448
  }
10370
10449
  /**
10371
10450
  * Convert AI SDK tools to MCP Tool format
10372
10451
  */
10373
10452
  convertAISDKToolsToMCP(tools) {
10374
10453
  if (!tools || tools.length === 0) return [];
10375
- return tools.filter((tool3) => tool3.type === "function").map((tool3) => {
10376
- const toolAny = tool3;
10454
+ return tools.filter((tool2) => tool2.type === "function").map((tool2) => {
10455
+ const toolAny = tool2;
10377
10456
  return {
10378
- name: tool3.name,
10379
- description: toolAny.description || `Tool: ${tool3.name}`,
10457
+ name: tool2.name,
10458
+ description: toolAny.description || `Tool: ${tool2.name}`,
10380
10459
  inputSchema: {
10381
10460
  type: "object",
10382
10461
  ...toolAny.inputSchema || toolAny.parameters
@@ -10431,8 +10510,16 @@ IMPORTANT: You MUST respond with valid JSON only. Do not include any text before
10431
10510
  return systemPrompt;
10432
10511
  }
10433
10512
  if (useNativeTools) {
10513
+ this.server.sendLoggingMessage({
10514
+ level: "info",
10515
+ data: `Using native tools mode - skipping XML tool injection`
10516
+ });
10434
10517
  return systemPrompt;
10435
10518
  }
10519
+ this.server.sendLoggingMessage({
10520
+ level: "info",
10521
+ data: `Injecting ${tools.length} tools into system prompt (fallback mode)`
10522
+ });
10436
10523
  let enhanced = systemPrompt || "";
10437
10524
  const toolsPrompt = `
10438
10525
 
@@ -10443,21 +10530,21 @@ You have access to the following tools. To use a tool, respond with this XML for
10443
10530
  </use_tool>
10444
10531
 
10445
10532
  Follow the JSON schema definition for each tool's parameters.
10446
- You can use multiple tools in one response. You can include text before tool calls, but do NOT include text after tool calls - wait for the tool results first.
10533
+ You can use multiple tools in one response. DO NOT include text before or after tool calls - wait for the tool results first.
10447
10534
 
10448
10535
  Tools:`;
10449
- const toolDescriptions = tools.map((tool3) => {
10450
- if (tool3.type === "function") {
10451
- const toolAny = tool3;
10536
+ const toolDescriptions = tools.map((tool2) => {
10537
+ if (tool2.type === "function") {
10538
+ const toolAny = tool2;
10452
10539
  const description = toolAny.description || "No description provided";
10453
10540
  const schema = toolAny.inputSchema || toolAny.parameters;
10454
10541
  const params = schema ? `
10455
10542
  JSON Schema: ${JSON.stringify(schema, null, 2)}` : "";
10456
10543
  return `
10457
- - ${tool3.name}: ${description}${params}`;
10458
- } else if (tool3.type === "provider-defined") {
10544
+ - ${tool2.name}: ${description}${params}`;
10545
+ } else if (tool2.type === "provider-defined") {
10459
10546
  return `
10460
- - ${tool3.name}: ${tool3.id || "No description provided"}`;
10547
+ - ${tool2.name}: ${tool2.id || "No description provided"}`;
10461
10548
  }
10462
10549
  return "";
10463
10550
  }).filter(Boolean).join("");
@@ -10779,2436 +10866,63 @@ var createAISamplingModePlugin = () => ({
10779
10866
  });
10780
10867
  var mode_ai_sampling_plugin_default = createAISamplingModePlugin();
10781
10868
 
10782
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/acp.js
10783
- var import_zod3 = require("zod");
10784
-
10785
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/schema.js
10786
- var import_zod2 = require("zod");
10787
- var AGENT_METHODS = {
10788
- authenticate: "authenticate",
10789
- initialize: "initialize",
10790
- session_cancel: "session/cancel",
10791
- session_load: "session/load",
10792
- session_new: "session/new",
10793
- session_prompt: "session/prompt",
10794
- session_set_mode: "session/set_mode",
10795
- session_set_model: "session/set_model"
10796
- };
10797
- var CLIENT_METHODS = {
10798
- fs_read_text_file: "fs/read_text_file",
10799
- fs_write_text_file: "fs/write_text_file",
10800
- session_request_permission: "session/request_permission",
10801
- session_update: "session/update",
10802
- terminal_create: "terminal/create",
10803
- terminal_kill: "terminal/kill",
10804
- terminal_output: "terminal/output",
10805
- terminal_release: "terminal/release",
10806
- terminal_wait_for_exit: "terminal/wait_for_exit"
10807
- };
10808
- var PROTOCOL_VERSION = 1;
10809
- var writeTextFileRequestSchema = import_zod2.z.object({
10810
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10811
- content: import_zod2.z.string(),
10812
- path: import_zod2.z.string(),
10813
- sessionId: import_zod2.z.string()
10814
- });
10815
- var readTextFileRequestSchema = import_zod2.z.object({
10816
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10817
- limit: import_zod2.z.number().optional().nullable(),
10818
- line: import_zod2.z.number().optional().nullable(),
10819
- path: import_zod2.z.string(),
10820
- sessionId: import_zod2.z.string()
10821
- });
10822
- var terminalOutputRequestSchema = import_zod2.z.object({
10823
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10824
- sessionId: import_zod2.z.string(),
10825
- terminalId: import_zod2.z.string()
10826
- });
10827
- var releaseTerminalRequestSchema = import_zod2.z.object({
10828
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10829
- sessionId: import_zod2.z.string(),
10830
- terminalId: import_zod2.z.string()
10831
- });
10832
- var waitForTerminalExitRequestSchema = import_zod2.z.object({
10833
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10834
- sessionId: import_zod2.z.string(),
10835
- terminalId: import_zod2.z.string()
10836
- });
10837
- var killTerminalCommandRequestSchema = import_zod2.z.object({
10838
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10839
- sessionId: import_zod2.z.string(),
10840
- terminalId: import_zod2.z.string()
10841
- });
10842
- var extMethodRequestSchema = import_zod2.z.record(import_zod2.z.unknown());
10843
- var roleSchema = import_zod2.z.union([import_zod2.z.literal("assistant"), import_zod2.z.literal("user")]);
10844
- var textResourceContentsSchema = import_zod2.z.object({
10845
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10846
- mimeType: import_zod2.z.string().optional().nullable(),
10847
- text: import_zod2.z.string(),
10848
- uri: import_zod2.z.string()
10849
- });
10850
- var blobResourceContentsSchema = import_zod2.z.object({
10851
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10852
- blob: import_zod2.z.string(),
10853
- mimeType: import_zod2.z.string().optional().nullable(),
10854
- uri: import_zod2.z.string()
10855
- });
10856
- var toolKindSchema = import_zod2.z.union([
10857
- import_zod2.z.literal("read"),
10858
- import_zod2.z.literal("edit"),
10859
- import_zod2.z.literal("delete"),
10860
- import_zod2.z.literal("move"),
10861
- import_zod2.z.literal("search"),
10862
- import_zod2.z.literal("execute"),
10863
- import_zod2.z.literal("think"),
10864
- import_zod2.z.literal("fetch"),
10865
- import_zod2.z.literal("switch_mode"),
10866
- import_zod2.z.literal("other")
10867
- ]);
10868
- var toolCallStatusSchema = import_zod2.z.union([
10869
- import_zod2.z.literal("pending"),
10870
- import_zod2.z.literal("in_progress"),
10871
- import_zod2.z.literal("completed"),
10872
- import_zod2.z.literal("failed")
10873
- ]);
10874
- var writeTextFileResponseSchema = import_zod2.z.object({
10875
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10876
- });
10877
- var readTextFileResponseSchema = import_zod2.z.object({
10878
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10879
- content: import_zod2.z.string()
10880
- });
10881
- var requestPermissionResponseSchema = import_zod2.z.object({
10882
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10883
- outcome: import_zod2.z.union([
10884
- import_zod2.z.object({
10885
- outcome: import_zod2.z.literal("cancelled")
10886
- }),
10887
- import_zod2.z.object({
10888
- optionId: import_zod2.z.string(),
10889
- outcome: import_zod2.z.literal("selected")
10890
- })
10891
- ])
10892
- });
10893
- var createTerminalResponseSchema = import_zod2.z.object({
10894
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10895
- terminalId: import_zod2.z.string()
10896
- });
10897
- var releaseTerminalResponseSchema = import_zod2.z.object({
10898
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10899
- });
10900
- var waitForTerminalExitResponseSchema = import_zod2.z.object({
10901
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10902
- exitCode: import_zod2.z.number().optional().nullable(),
10903
- signal: import_zod2.z.string().optional().nullable()
10904
- });
10905
- var killTerminalResponseSchema = import_zod2.z.object({
10906
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10907
- });
10908
- var extMethodResponseSchema = import_zod2.z.record(import_zod2.z.unknown());
10909
- var cancelNotificationSchema = import_zod2.z.object({
10910
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10911
- sessionId: import_zod2.z.string()
10912
- });
10913
- var extNotificationSchema = import_zod2.z.record(import_zod2.z.unknown());
10914
- var authenticateRequestSchema = import_zod2.z.object({
10915
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10916
- methodId: import_zod2.z.string()
10917
- });
10918
- var setSessionModeRequestSchema = import_zod2.z.object({
10919
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10920
- modeId: import_zod2.z.string(),
10921
- sessionId: import_zod2.z.string()
10922
- });
10923
- var setSessionModelRequestSchema = import_zod2.z.object({
10924
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10925
- modelId: import_zod2.z.string(),
10926
- sessionId: import_zod2.z.string()
10927
- });
10928
- var extMethodRequest1Schema = import_zod2.z.record(import_zod2.z.unknown());
10929
- var httpHeaderSchema = import_zod2.z.object({
10930
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10931
- name: import_zod2.z.string(),
10932
- value: import_zod2.z.string()
10933
- });
10934
- var annotationsSchema = import_zod2.z.object({
10935
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10936
- audience: import_zod2.z.array(roleSchema).optional().nullable(),
10937
- lastModified: import_zod2.z.string().optional().nullable(),
10938
- priority: import_zod2.z.number().optional().nullable()
10939
- });
10940
- var embeddedResourceResourceSchema = import_zod2.z.union([
10941
- textResourceContentsSchema,
10942
- blobResourceContentsSchema
10943
- ]);
10944
- var authenticateResponseSchema = import_zod2.z.object({
10945
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10946
- });
10947
- var setSessionModeResponseSchema = import_zod2.z.object({
10948
- meta: import_zod2.z.unknown().optional()
10949
- });
10950
- var promptResponseSchema = import_zod2.z.object({
10951
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10952
- stopReason: import_zod2.z.union([
10953
- import_zod2.z.literal("end_turn"),
10954
- import_zod2.z.literal("max_tokens"),
10955
- import_zod2.z.literal("max_turn_requests"),
10956
- import_zod2.z.literal("refusal"),
10957
- import_zod2.z.literal("cancelled")
10958
- ])
10959
- });
10960
- var setSessionModelResponseSchema = import_zod2.z.object({
10961
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10962
- });
10963
- var extMethodResponse1Schema = import_zod2.z.record(import_zod2.z.unknown());
10964
- var sessionModeIdSchema = import_zod2.z.string();
10965
- var extNotification1Schema = import_zod2.z.record(import_zod2.z.unknown());
10966
- var unstructuredCommandInputSchema = import_zod2.z.object({
10967
- hint: import_zod2.z.string()
10968
- });
10969
- var permissionOptionSchema = import_zod2.z.object({
10970
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10971
- kind: import_zod2.z.union([
10972
- import_zod2.z.literal("allow_once"),
10973
- import_zod2.z.literal("allow_always"),
10974
- import_zod2.z.literal("reject_once"),
10975
- import_zod2.z.literal("reject_always")
10976
- ]),
10977
- name: import_zod2.z.string(),
10978
- optionId: import_zod2.z.string()
10979
- });
10980
- var toolCallContentSchema = import_zod2.z.union([
10981
- import_zod2.z.object({
10982
- content: import_zod2.z.union([
10983
- import_zod2.z.object({
10984
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10985
- annotations: annotationsSchema.optional().nullable(),
10986
- text: import_zod2.z.string(),
10987
- type: import_zod2.z.literal("text")
10988
- }),
10989
- import_zod2.z.object({
10990
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10991
- annotations: annotationsSchema.optional().nullable(),
10992
- data: import_zod2.z.string(),
10993
- mimeType: import_zod2.z.string(),
10994
- type: import_zod2.z.literal("image"),
10995
- uri: import_zod2.z.string().optional().nullable()
10996
- }),
10997
- import_zod2.z.object({
10998
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10999
- annotations: annotationsSchema.optional().nullable(),
11000
- data: import_zod2.z.string(),
11001
- mimeType: import_zod2.z.string(),
11002
- type: import_zod2.z.literal("audio")
11003
- }),
11004
- import_zod2.z.object({
11005
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11006
- annotations: annotationsSchema.optional().nullable(),
11007
- description: import_zod2.z.string().optional().nullable(),
11008
- mimeType: import_zod2.z.string().optional().nullable(),
11009
- name: import_zod2.z.string(),
11010
- size: import_zod2.z.number().optional().nullable(),
11011
- title: import_zod2.z.string().optional().nullable(),
11012
- type: import_zod2.z.literal("resource_link"),
11013
- uri: import_zod2.z.string()
11014
- }),
11015
- import_zod2.z.object({
11016
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11017
- annotations: annotationsSchema.optional().nullable(),
11018
- resource: embeddedResourceResourceSchema,
11019
- type: import_zod2.z.literal("resource")
11020
- })
11021
- ]),
11022
- type: import_zod2.z.literal("content")
11023
- }),
11024
- import_zod2.z.object({
11025
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11026
- newText: import_zod2.z.string(),
11027
- oldText: import_zod2.z.string().optional().nullable(),
11028
- path: import_zod2.z.string(),
11029
- type: import_zod2.z.literal("diff")
11030
- }),
11031
- import_zod2.z.object({
11032
- terminalId: import_zod2.z.string(),
11033
- type: import_zod2.z.literal("terminal")
11034
- })
11035
- ]);
11036
- var toolCallLocationSchema = import_zod2.z.object({
11037
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11038
- line: import_zod2.z.number().optional().nullable(),
11039
- path: import_zod2.z.string()
11040
- });
11041
- var envVariableSchema = import_zod2.z.object({
11042
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11043
- name: import_zod2.z.string(),
11044
- value: import_zod2.z.string()
11045
- });
11046
- var terminalExitStatusSchema = import_zod2.z.object({
11047
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11048
- exitCode: import_zod2.z.number().optional().nullable(),
11049
- signal: import_zod2.z.string().optional().nullable()
11050
- });
11051
- var fileSystemCapabilitySchema = import_zod2.z.object({
11052
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11053
- readTextFile: import_zod2.z.boolean().optional(),
11054
- writeTextFile: import_zod2.z.boolean().optional()
11055
- });
11056
- var stdioSchema = import_zod2.z.object({
11057
- args: import_zod2.z.array(import_zod2.z.string()),
11058
- command: import_zod2.z.string(),
11059
- env: import_zod2.z.array(envVariableSchema),
11060
- name: import_zod2.z.string()
11061
- });
11062
- var mcpServerSchema = import_zod2.z.union([
11063
- import_zod2.z.object({
11064
- headers: import_zod2.z.array(httpHeaderSchema),
11065
- name: import_zod2.z.string(),
11066
- type: import_zod2.z.literal("http"),
11067
- url: import_zod2.z.string()
11068
- }),
11069
- import_zod2.z.object({
11070
- headers: import_zod2.z.array(httpHeaderSchema),
11071
- name: import_zod2.z.string(),
11072
- type: import_zod2.z.literal("sse"),
11073
- url: import_zod2.z.string()
11074
- }),
11075
- stdioSchema
11076
- ]);
11077
- var contentBlockSchema = import_zod2.z.union([
11078
- import_zod2.z.object({
11079
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11080
- annotations: annotationsSchema.optional().nullable(),
11081
- text: import_zod2.z.string(),
11082
- type: import_zod2.z.literal("text")
11083
- }),
11084
- import_zod2.z.object({
11085
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11086
- annotations: annotationsSchema.optional().nullable(),
11087
- data: import_zod2.z.string(),
11088
- mimeType: import_zod2.z.string(),
11089
- type: import_zod2.z.literal("image"),
11090
- uri: import_zod2.z.string().optional().nullable()
11091
- }),
11092
- import_zod2.z.object({
11093
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11094
- annotations: annotationsSchema.optional().nullable(),
11095
- data: import_zod2.z.string(),
11096
- mimeType: import_zod2.z.string(),
11097
- type: import_zod2.z.literal("audio")
11098
- }),
11099
- import_zod2.z.object({
11100
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11101
- annotations: annotationsSchema.optional().nullable(),
11102
- description: import_zod2.z.string().optional().nullable(),
11103
- mimeType: import_zod2.z.string().optional().nullable(),
11104
- name: import_zod2.z.string(),
11105
- size: import_zod2.z.number().optional().nullable(),
11106
- title: import_zod2.z.string().optional().nullable(),
11107
- type: import_zod2.z.literal("resource_link"),
11108
- uri: import_zod2.z.string()
11109
- }),
11110
- import_zod2.z.object({
11111
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11112
- annotations: annotationsSchema.optional().nullable(),
11113
- resource: embeddedResourceResourceSchema,
11114
- type: import_zod2.z.literal("resource")
11115
- })
11116
- ]);
11117
- var authMethodSchema = import_zod2.z.object({
11118
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11119
- description: import_zod2.z.string().optional().nullable(),
11120
- id: import_zod2.z.string(),
11121
- name: import_zod2.z.string()
11122
- });
11123
- var mcpCapabilitiesSchema = import_zod2.z.object({
11124
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11125
- http: import_zod2.z.boolean().optional(),
11126
- sse: import_zod2.z.boolean().optional()
11127
- });
11128
- var promptCapabilitiesSchema = import_zod2.z.object({
11129
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11130
- audio: import_zod2.z.boolean().optional(),
11131
- embeddedContext: import_zod2.z.boolean().optional(),
11132
- image: import_zod2.z.boolean().optional()
11133
- });
11134
- var modelInfoSchema = import_zod2.z.object({
11135
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11136
- description: import_zod2.z.string().optional().nullable(),
11137
- modelId: import_zod2.z.string(),
11138
- name: import_zod2.z.string()
11139
- });
11140
- var sessionModeSchema = import_zod2.z.object({
11141
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11142
- description: import_zod2.z.string().optional().nullable(),
11143
- id: sessionModeIdSchema,
11144
- name: import_zod2.z.string()
11145
- });
11146
- var sessionModelStateSchema = import_zod2.z.object({
11147
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11148
- availableModels: import_zod2.z.array(modelInfoSchema),
11149
- currentModelId: import_zod2.z.string()
11150
- });
11151
- var sessionModeStateSchema = import_zod2.z.object({
11152
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11153
- availableModes: import_zod2.z.array(sessionModeSchema),
11154
- currentModeId: import_zod2.z.string()
11155
- });
11156
- var planEntrySchema = import_zod2.z.object({
11157
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11158
- content: import_zod2.z.string(),
11159
- priority: import_zod2.z.union([import_zod2.z.literal("high"), import_zod2.z.literal("medium"), import_zod2.z.literal("low")]),
11160
- status: import_zod2.z.union([
11161
- import_zod2.z.literal("pending"),
11162
- import_zod2.z.literal("in_progress"),
11163
- import_zod2.z.literal("completed")
11164
- ])
11165
- });
11166
- var availableCommandInputSchema = unstructuredCommandInputSchema;
11167
- var clientNotificationSchema = import_zod2.z.union([
11168
- cancelNotificationSchema,
11169
- extNotificationSchema
11170
- ]);
11171
- var createTerminalRequestSchema = import_zod2.z.object({
11172
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11173
- args: import_zod2.z.array(import_zod2.z.string()).optional(),
11174
- command: import_zod2.z.string(),
11175
- cwd: import_zod2.z.string().optional().nullable(),
11176
- env: import_zod2.z.array(envVariableSchema).optional(),
11177
- outputByteLimit: import_zod2.z.number().optional().nullable(),
11178
- sessionId: import_zod2.z.string()
11179
- });
11180
- var terminalOutputResponseSchema = import_zod2.z.object({
11181
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11182
- exitStatus: terminalExitStatusSchema.optional().nullable(),
11183
- output: import_zod2.z.string(),
11184
- truncated: import_zod2.z.boolean()
11185
- });
11186
- var newSessionRequestSchema = import_zod2.z.object({
11187
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11188
- cwd: import_zod2.z.string(),
11189
- mcpServers: import_zod2.z.array(mcpServerSchema)
11190
- });
11191
- var loadSessionRequestSchema = import_zod2.z.object({
11192
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11193
- cwd: import_zod2.z.string(),
11194
- mcpServers: import_zod2.z.array(mcpServerSchema),
11195
- sessionId: import_zod2.z.string()
11196
- });
11197
- var promptRequestSchema = import_zod2.z.object({
11198
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11199
- prompt: import_zod2.z.array(contentBlockSchema),
11200
- sessionId: import_zod2.z.string()
11201
- });
11202
- var newSessionResponseSchema = import_zod2.z.object({
11203
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11204
- models: sessionModelStateSchema.optional().nullable(),
11205
- modes: sessionModeStateSchema.optional().nullable(),
11206
- sessionId: import_zod2.z.string()
11207
- });
11208
- var loadSessionResponseSchema = import_zod2.z.object({
11209
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11210
- models: sessionModelStateSchema.optional().nullable(),
11211
- modes: sessionModeStateSchema.optional().nullable()
11212
- });
11213
- var toolCallUpdateSchema = import_zod2.z.object({
11214
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11215
- content: import_zod2.z.array(toolCallContentSchema).optional().nullable(),
11216
- kind: toolKindSchema.optional().nullable(),
11217
- locations: import_zod2.z.array(toolCallLocationSchema).optional().nullable(),
11218
- rawInput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11219
- rawOutput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11220
- status: toolCallStatusSchema.optional().nullable(),
11221
- title: import_zod2.z.string().optional().nullable(),
11222
- toolCallId: import_zod2.z.string()
11223
- });
11224
- var clientCapabilitiesSchema = import_zod2.z.object({
11225
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11226
- fs: fileSystemCapabilitySchema.optional(),
11227
- terminal: import_zod2.z.boolean().optional()
11228
- });
11229
- var agentCapabilitiesSchema = import_zod2.z.object({
11230
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11231
- loadSession: import_zod2.z.boolean().optional(),
11232
- mcpCapabilities: mcpCapabilitiesSchema.optional(),
11233
- promptCapabilities: promptCapabilitiesSchema.optional()
11234
- });
11235
- var availableCommandSchema = import_zod2.z.object({
11236
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11237
- description: import_zod2.z.string(),
11238
- input: availableCommandInputSchema.optional().nullable(),
11239
- name: import_zod2.z.string()
11240
- });
11241
- var clientResponseSchema = import_zod2.z.union([
11242
- writeTextFileResponseSchema,
11243
- readTextFileResponseSchema,
11244
- requestPermissionResponseSchema,
11245
- createTerminalResponseSchema,
11246
- terminalOutputResponseSchema,
11247
- releaseTerminalResponseSchema,
11248
- waitForTerminalExitResponseSchema,
11249
- killTerminalResponseSchema,
11250
- extMethodResponseSchema
11251
- ]);
11252
- var requestPermissionRequestSchema = import_zod2.z.object({
11253
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11254
- options: import_zod2.z.array(permissionOptionSchema),
11255
- sessionId: import_zod2.z.string(),
11256
- toolCall: toolCallUpdateSchema
11257
- });
11258
- var initializeRequestSchema = import_zod2.z.object({
11259
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11260
- clientCapabilities: clientCapabilitiesSchema.optional(),
11261
- protocolVersion: import_zod2.z.number()
11262
- });
11263
- var initializeResponseSchema = import_zod2.z.object({
11264
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11265
- agentCapabilities: agentCapabilitiesSchema.optional(),
11266
- authMethods: import_zod2.z.array(authMethodSchema).optional(),
11267
- protocolVersion: import_zod2.z.number()
11268
- });
11269
- var sessionNotificationSchema = import_zod2.z.object({
11270
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11271
- sessionId: import_zod2.z.string(),
11272
- update: import_zod2.z.union([
11273
- import_zod2.z.object({
11274
- content: contentBlockSchema,
11275
- sessionUpdate: import_zod2.z.literal("user_message_chunk")
11276
- }),
11277
- import_zod2.z.object({
11278
- content: contentBlockSchema,
11279
- sessionUpdate: import_zod2.z.literal("agent_message_chunk")
11280
- }),
11281
- import_zod2.z.object({
11282
- content: contentBlockSchema,
11283
- sessionUpdate: import_zod2.z.literal("agent_thought_chunk")
11284
- }),
11285
- import_zod2.z.object({
11286
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11287
- content: import_zod2.z.array(toolCallContentSchema).optional(),
11288
- kind: import_zod2.z.union([
11289
- import_zod2.z.literal("read"),
11290
- import_zod2.z.literal("edit"),
11291
- import_zod2.z.literal("delete"),
11292
- import_zod2.z.literal("move"),
11293
- import_zod2.z.literal("search"),
11294
- import_zod2.z.literal("execute"),
11295
- import_zod2.z.literal("think"),
11296
- import_zod2.z.literal("fetch"),
11297
- import_zod2.z.literal("switch_mode"),
11298
- import_zod2.z.literal("other")
11299
- ]).optional(),
11300
- locations: import_zod2.z.array(toolCallLocationSchema).optional(),
11301
- rawInput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11302
- rawOutput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11303
- sessionUpdate: import_zod2.z.literal("tool_call"),
11304
- status: import_zod2.z.union([
11305
- import_zod2.z.literal("pending"),
11306
- import_zod2.z.literal("in_progress"),
11307
- import_zod2.z.literal("completed"),
11308
- import_zod2.z.literal("failed")
11309
- ]).optional(),
11310
- title: import_zod2.z.string(),
11311
- toolCallId: import_zod2.z.string()
11312
- }),
11313
- import_zod2.z.object({
11314
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11315
- content: import_zod2.z.array(toolCallContentSchema).optional().nullable(),
11316
- kind: toolKindSchema.optional().nullable(),
11317
- locations: import_zod2.z.array(toolCallLocationSchema).optional().nullable(),
11318
- rawInput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11319
- rawOutput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11320
- sessionUpdate: import_zod2.z.literal("tool_call_update"),
11321
- status: toolCallStatusSchema.optional().nullable(),
11322
- title: import_zod2.z.string().optional().nullable(),
11323
- toolCallId: import_zod2.z.string()
11324
- }),
11325
- import_zod2.z.object({
11326
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11327
- entries: import_zod2.z.array(planEntrySchema),
11328
- sessionUpdate: import_zod2.z.literal("plan")
11329
- }),
11330
- import_zod2.z.object({
11331
- availableCommands: import_zod2.z.array(availableCommandSchema),
11332
- sessionUpdate: import_zod2.z.literal("available_commands_update")
11333
- }),
11334
- import_zod2.z.object({
11335
- currentModeId: sessionModeIdSchema,
11336
- sessionUpdate: import_zod2.z.literal("current_mode_update")
11337
- })
11338
- ])
11339
- });
11340
- var clientRequestSchema = import_zod2.z.union([
11341
- writeTextFileRequestSchema,
11342
- readTextFileRequestSchema,
11343
- requestPermissionRequestSchema,
11344
- createTerminalRequestSchema,
11345
- terminalOutputRequestSchema,
11346
- releaseTerminalRequestSchema,
11347
- waitForTerminalExitRequestSchema,
11348
- killTerminalCommandRequestSchema,
11349
- extMethodRequestSchema
11350
- ]);
11351
- var agentRequestSchema = import_zod2.z.union([
11352
- initializeRequestSchema,
11353
- authenticateRequestSchema,
11354
- newSessionRequestSchema,
11355
- loadSessionRequestSchema,
11356
- setSessionModeRequestSchema,
11357
- promptRequestSchema,
11358
- setSessionModelRequestSchema,
11359
- extMethodRequest1Schema
11360
- ]);
11361
- var agentResponseSchema = import_zod2.z.union([
11362
- initializeResponseSchema,
11363
- authenticateResponseSchema,
11364
- newSessionResponseSchema,
11365
- loadSessionResponseSchema,
11366
- setSessionModeResponseSchema,
11367
- promptResponseSchema,
11368
- setSessionModelResponseSchema,
11369
- extMethodResponse1Schema
11370
- ]);
11371
- var agentNotificationSchema = import_zod2.z.union([
11372
- sessionNotificationSchema,
11373
- extNotification1Schema
11374
- ]);
11375
- var agentClientProtocolSchema = import_zod2.z.union([
11376
- clientRequestSchema,
11377
- clientResponseSchema,
11378
- clientNotificationSchema,
11379
- agentRequestSchema,
11380
- agentResponseSchema,
11381
- agentNotificationSchema
11382
- ]);
11383
-
11384
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/stream.js
11385
- function ndJsonStream(output, input) {
11386
- const textEncoder = new TextEncoder();
11387
- const textDecoder = new TextDecoder();
11388
- const readable = new ReadableStream({
11389
- async start(controller) {
11390
- let content = "";
11391
- const reader = input.getReader();
11392
- try {
11393
- while (true) {
11394
- const { value, done } = await reader.read();
11395
- if (done) {
11396
- break;
11397
- }
11398
- if (!value) {
11399
- continue;
11400
- }
11401
- content += textDecoder.decode(value, { stream: true });
11402
- const lines = content.split("\n");
11403
- content = lines.pop() || "";
11404
- for (const line of lines) {
11405
- const trimmedLine = line.trim();
11406
- if (trimmedLine) {
11407
- try {
11408
- const message = JSON.parse(trimmedLine);
11409
- controller.enqueue(message);
11410
- } catch (err) {
11411
- console.error("Failed to parse JSON message:", trimmedLine, err);
11412
- }
11413
- }
11414
- }
11415
- }
11416
- } finally {
11417
- reader.releaseLock();
11418
- controller.close();
11419
- }
11420
- }
11421
- });
11422
- const writable = new WritableStream({
11423
- async write(message) {
11424
- const content = JSON.stringify(message) + "\n";
11425
- const writer = output.getWriter();
11426
- try {
11427
- await writer.write(textEncoder.encode(content));
11428
- } finally {
11429
- writer.releaseLock();
11430
- }
11431
- }
11432
- });
11433
- return { readable, writable };
11434
- }
11435
-
11436
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/acp.js
11437
- var ClientSideConnection = class {
11438
- #connection;
11439
- /**
11440
- * Creates a new client-side connection to an agent.
11441
- *
11442
- * This establishes the communication channel between a client and agent
11443
- * following the ACP specification.
11444
- *
11445
- * @param toClient - A function that creates a Client handler to process incoming agent requests
11446
- * @param stream - The bidirectional message stream for communication. Typically created using
11447
- * {@link ndJsonStream} for stdio-based connections.
11448
- *
11449
- * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
11450
- */
11451
- constructor(toClient, stream) {
11452
- const client = toClient(this);
11453
- const requestHandler = async (method, params) => {
11454
- switch (method) {
11455
- case CLIENT_METHODS.fs_write_text_file: {
11456
- const validatedParams = writeTextFileRequestSchema.parse(params);
11457
- return client.writeTextFile?.(validatedParams);
11458
- }
11459
- case CLIENT_METHODS.fs_read_text_file: {
11460
- const validatedParams = readTextFileRequestSchema.parse(params);
11461
- return client.readTextFile?.(validatedParams);
11462
- }
11463
- case CLIENT_METHODS.session_request_permission: {
11464
- const validatedParams = requestPermissionRequestSchema.parse(params);
11465
- return client.requestPermission(validatedParams);
11466
- }
11467
- case CLIENT_METHODS.terminal_create: {
11468
- const validatedParams = createTerminalRequestSchema.parse(params);
11469
- return client.createTerminal?.(validatedParams);
11470
- }
11471
- case CLIENT_METHODS.terminal_output: {
11472
- const validatedParams = terminalOutputRequestSchema.parse(params);
11473
- return client.terminalOutput?.(validatedParams);
11474
- }
11475
- case CLIENT_METHODS.terminal_release: {
11476
- const validatedParams = releaseTerminalRequestSchema.parse(params);
11477
- const result = await client.releaseTerminal?.(validatedParams);
11478
- return result ?? {};
11479
- }
11480
- case CLIENT_METHODS.terminal_wait_for_exit: {
11481
- const validatedParams = waitForTerminalExitRequestSchema.parse(params);
11482
- return client.waitForTerminalExit?.(validatedParams);
11483
- }
11484
- case CLIENT_METHODS.terminal_kill: {
11485
- const validatedParams = killTerminalCommandRequestSchema.parse(params);
11486
- const result = await client.killTerminal?.(validatedParams);
11487
- return result ?? {};
11488
- }
11489
- default:
11490
- if (method.startsWith("_")) {
11491
- const customMethod = method.substring(1);
11492
- if (!client.extMethod) {
11493
- throw RequestError.methodNotFound(method);
11494
- }
11495
- return client.extMethod(customMethod, params);
11496
- }
11497
- throw RequestError.methodNotFound(method);
11498
- }
11499
- };
11500
- const notificationHandler = async (method, params) => {
11501
- switch (method) {
11502
- case CLIENT_METHODS.session_update: {
11503
- const validatedParams = sessionNotificationSchema.parse(params);
11504
- return client.sessionUpdate(validatedParams);
11505
- }
11506
- default:
11507
- if (method.startsWith("_")) {
11508
- const customMethod = method.substring(1);
11509
- if (!client.extNotification) {
11510
- return;
11511
- }
11512
- return client.extNotification(customMethod, params);
11513
- }
11514
- throw RequestError.methodNotFound(method);
11515
- }
11516
- };
11517
- this.#connection = new Connection(requestHandler, notificationHandler, stream);
11518
- }
11519
- /**
11520
- * Establishes the connection with a client and negotiates protocol capabilities.
11521
- *
11522
- * This method is called once at the beginning of the connection to:
11523
- * - Negotiate the protocol version to use
11524
- * - Exchange capability information between client and agent
11525
- * - Determine available authentication methods
11526
- *
11527
- * The agent should respond with its supported protocol version and capabilities.
11528
- *
11529
- * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
11530
- */
11531
- async initialize(params) {
11532
- return await this.#connection.sendRequest(AGENT_METHODS.initialize, params);
11533
- }
11534
- /**
11535
- * Creates a new conversation session with the agent.
11536
- *
11537
- * Sessions represent independent conversation contexts with their own history and state.
11538
- *
11539
- * The agent should:
11540
- * - Create a new session context
11541
- * - Connect to any specified MCP servers
11542
- * - Return a unique session ID for future requests
11543
- *
11544
- * May return an `auth_required` error if the agent requires authentication.
11545
- *
11546
- * See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/session-setup)
11547
- */
11548
- async newSession(params) {
11549
- return await this.#connection.sendRequest(AGENT_METHODS.session_new, params);
11550
- }
11551
- /**
11552
- * Loads an existing session to resume a previous conversation.
11553
- *
11554
- * This method is only available if the agent advertises the `loadSession` capability.
11555
- *
11556
- * The agent should:
11557
- * - Restore the session context and conversation history
11558
- * - Connect to the specified MCP servers
11559
- * - Stream the entire conversation history back to the client via notifications
11560
- *
11561
- * See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
11562
- */
11563
- async loadSession(params) {
11564
- return await this.#connection.sendRequest(AGENT_METHODS.session_load, params) ?? {};
11565
- }
11566
- /**
11567
- * Sets the operational mode for a session.
11568
- *
11569
- * Allows switching between different agent modes (e.g., "ask", "architect", "code")
11570
- * that affect system prompts, tool availability, and permission behaviors.
11571
- *
11572
- * The mode must be one of the modes advertised in `availableModes` during session
11573
- * creation or loading. Agents may also change modes autonomously and notify the
11574
- * client via `current_mode_update` notifications.
11575
- *
11576
- * This method can be called at any time during a session, whether the Agent is
11577
- * idle or actively generating a turn.
11578
- *
11579
- * See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
11580
- */
11581
- async setSessionMode(params) {
11582
- return await this.#connection.sendRequest(AGENT_METHODS.session_set_mode, params) ?? {};
11583
- }
11584
- /**
11585
- * **UNSTABLE**
11586
- *
11587
- * This capability is not part of the spec yet, and may be removed or changed at any point.
11588
- *
11589
- * Select a model for a given session.
11590
- */
11591
- async setSessionModel(params) {
11592
- return await this.#connection.sendRequest(AGENT_METHODS.session_set_model, params) ?? {};
11593
- }
11594
- /**
11595
- * Authenticates the client using the specified authentication method.
11596
- *
11597
- * Called when the agent requires authentication before allowing session creation.
11598
- * The client provides the authentication method ID that was advertised during initialization.
11599
- *
11600
- * After successful authentication, the client can proceed to create sessions with
11601
- * `newSession` without receiving an `auth_required` error.
11602
- *
11603
- * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
11604
- */
11605
- async authenticate(params) {
11606
- return await this.#connection.sendRequest(AGENT_METHODS.authenticate, params) ?? {};
11607
- }
11608
- /**
11609
- * Processes a user prompt within a session.
11610
- *
11611
- * This method handles the whole lifecycle of a prompt:
11612
- * - Receives user messages with optional context (files, images, etc.)
11613
- * - Processes the prompt using language models
11614
- * - Reports language model content and tool calls to the Clients
11615
- * - Requests permission to run tools
11616
- * - Executes any requested tool calls
11617
- * - Returns when the turn is complete with a stop reason
11618
- *
11619
- * See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/prompt-turn)
11620
- */
11621
- async prompt(params) {
11622
- return await this.#connection.sendRequest(AGENT_METHODS.session_prompt, params);
10869
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-executor.js
10870
+ var import_acp_ai_provider = require("@mcpc-tech/acp-ai-provider");
10871
+ var AIACPExecutor = class extends BaseAIExecutor {
10872
+ acpSettings;
10873
+ clientTools;
10874
+ provider = null;
10875
+ model = null;
10876
+ constructor(config) {
10877
+ super(config);
10878
+ this.acpSettings = config.acpSettings;
10879
+ this.clientTools = config.clientTools ?? [];
11623
10880
  }
11624
- /**
11625
- * Cancels ongoing operations for a session.
11626
- *
11627
- * This is a notification sent by the client to cancel an ongoing prompt turn.
11628
- *
11629
- * Upon receiving this notification, the Agent SHOULD:
11630
- * - Stop all language model requests as soon as possible
11631
- * - Abort all tool call invocations in progress
11632
- * - Send any pending `session/update` notifications
11633
- * - Respond to the original `session/prompt` request with `StopReason::Cancelled`
11634
- *
11635
- * See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
11636
- */
11637
- async cancel(params) {
11638
- return await this.#connection.sendNotification(AGENT_METHODS.session_cancel, params);
10881
+ initProvider() {
10882
+ if (!this.model) {
10883
+ this.provider = (0, import_acp_ai_provider.createACPProvider)(this.acpSettings);
10884
+ this.model = this.provider.languageModel();
10885
+ }
10886
+ return this.model;
11639
10887
  }
11640
- /**
11641
- * Extension method
11642
- *
11643
- * Allows the Client to send an arbitrary request that is not part of the ACP spec.
11644
- */
11645
- async extMethod(method, params) {
11646
- return await this.#connection.sendRequest(`_${method}`, params);
10888
+ getModel() {
10889
+ if (!this.model) throw new Error("Model not initialized");
10890
+ return this.model;
11647
10891
  }
11648
- /**
11649
- * Extension notification
11650
- *
11651
- * Allows the Client to send an arbitrary notification that is not part of the ACP spec.
11652
- */
11653
- async extNotification(method, params) {
11654
- return await this.#connection.sendNotification(`_${method}`, params);
10892
+ getExecutorType() {
10893
+ return "acp";
11655
10894
  }
11656
- };
11657
- var Connection = class {
11658
- #pendingResponses = /* @__PURE__ */ new Map();
11659
- #nextRequestId = 0;
11660
- #requestHandler;
11661
- #notificationHandler;
11662
- #stream;
11663
- #writeQueue = Promise.resolve();
11664
- constructor(requestHandler, notificationHandler, stream) {
11665
- this.#requestHandler = requestHandler;
11666
- this.#notificationHandler = notificationHandler;
11667
- this.#stream = stream;
11668
- this.#receive();
11669
- }
11670
- async #receive() {
11671
- const reader = this.#stream.readable.getReader();
11672
- try {
11673
- while (true) {
11674
- const { value: message, done } = await reader.read();
11675
- if (done) {
11676
- break;
11677
- }
11678
- if (!message) {
11679
- continue;
11680
- }
11681
- try {
11682
- this.#processMessage(message);
11683
- } catch (err) {
11684
- console.error("Unexpected error during message processing:", message, err);
11685
- if ("id" in message && message.id !== void 0) {
11686
- this.#sendMessage({
11687
- jsonrpc: "2.0",
11688
- id: message.id,
11689
- error: {
11690
- code: -32700,
11691
- message: "Parse error"
11692
- }
11693
- });
11694
- }
11695
- }
11696
- }
11697
- } finally {
11698
- reader.releaseLock();
10895
+ getToolListDescription() {
10896
+ if (this.clientTools.length === 0) {
10897
+ return "Tools will be provided by AI SDK";
11699
10898
  }
10899
+ return this.clientTools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
11700
10900
  }
11701
- async #processMessage(message) {
11702
- if ("method" in message && "id" in message) {
11703
- const response = await this.#tryCallRequestHandler(message.method, message.params);
11704
- if ("error" in response) {
11705
- console.error("Error handling request", message, response.error);
11706
- }
11707
- await this.#sendMessage({
11708
- jsonrpc: "2.0",
11709
- id: message.id,
11710
- ...response
10901
+ buildTools() {
10902
+ const aiTools = {};
10903
+ for (const [name, detail] of this.clientTools) {
10904
+ if (!detail.execute) continue;
10905
+ aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
10906
+ const result = await detail.execute(input);
10907
+ return this.formatResult(result);
11711
10908
  });
11712
- } else if ("method" in message) {
11713
- const response = await this.#tryCallNotificationHandler(message.method, message.params);
11714
- if ("error" in response) {
11715
- console.error("Error handling notification", message, response.error);
11716
- }
11717
- } else if ("id" in message) {
11718
- this.#handleResponse(message);
11719
- } else {
11720
- console.error("Invalid message", { message });
11721
10909
  }
10910
+ return aiTools;
11722
10911
  }
11723
- async #tryCallRequestHandler(method, params) {
11724
- try {
11725
- const result = await this.#requestHandler(method, params);
11726
- return { result: result ?? null };
11727
- } catch (error) {
11728
- if (error instanceof RequestError) {
11729
- return error.toResult();
11730
- }
11731
- if (error instanceof import_zod3.z.ZodError) {
11732
- return RequestError.invalidParams(error.format()).toResult();
11733
- }
11734
- let details;
11735
- if (error instanceof Error) {
11736
- details = error.message;
11737
- } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
11738
- details = error.message;
11739
- }
11740
- try {
11741
- return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
11742
- } catch {
11743
- return RequestError.internalError({ details }).toResult();
11744
- }
11745
- }
10912
+ formatResult(result) {
10913
+ const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
10914
+ return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
11746
10915
  }
11747
- async #tryCallNotificationHandler(method, params) {
11748
- try {
11749
- await this.#notificationHandler(method, params);
11750
- return { result: null };
11751
- } catch (error) {
11752
- if (error instanceof RequestError) {
11753
- return error.toResult();
11754
- }
11755
- if (error instanceof import_zod3.z.ZodError) {
11756
- return RequestError.invalidParams(error.format()).toResult();
11757
- }
11758
- let details;
11759
- if (error instanceof Error) {
11760
- details = error.message;
11761
- } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
11762
- details = error.message;
11763
- }
11764
- try {
11765
- return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
11766
- } catch {
11767
- return RequestError.internalError({ details }).toResult();
11768
- }
11769
- }
10916
+ execute(args) {
10917
+ this.initProvider();
10918
+ return super.execute(args);
11770
10919
  }
11771
- #handleResponse(response) {
11772
- const pendingResponse = this.#pendingResponses.get(response.id);
11773
- if (pendingResponse) {
11774
- if ("result" in response) {
11775
- pendingResponse.resolve(response.result);
11776
- } else if ("error" in response) {
11777
- pendingResponse.reject(response.error);
11778
- }
11779
- this.#pendingResponses.delete(response.id);
11780
- } else {
11781
- console.error("Got response to unknown request", response.id);
10920
+ cleanup() {
10921
+ if (this.provider && typeof this.provider.cleanup === "function") {
10922
+ this.provider.cleanup();
11782
10923
  }
11783
- }
11784
- async sendRequest(method, params) {
11785
- const id = this.#nextRequestId++;
11786
- const responsePromise = new Promise((resolve3, reject) => {
11787
- this.#pendingResponses.set(id, { resolve: resolve3, reject });
11788
- });
11789
- await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
11790
- return responsePromise;
11791
- }
11792
- async sendNotification(method, params) {
11793
- await this.#sendMessage({ jsonrpc: "2.0", method, params });
11794
- }
11795
- async #sendMessage(message) {
11796
- this.#writeQueue = this.#writeQueue.then(async () => {
11797
- const writer = this.#stream.writable.getWriter();
11798
- try {
11799
- await writer.write(message);
11800
- } finally {
11801
- writer.releaseLock();
11802
- }
11803
- }).catch((error) => {
11804
- console.error("ACP write error:", error);
11805
- });
11806
- return this.#writeQueue;
11807
- }
11808
- };
11809
- var RequestError = class _RequestError extends Error {
11810
- code;
11811
- data;
11812
- constructor(code, message, data) {
11813
- super(message);
11814
- this.code = code;
11815
- this.name = "RequestError";
11816
- this.data = data;
11817
- }
11818
- /**
11819
- * Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
11820
- */
11821
- static parseError(data) {
11822
- return new _RequestError(-32700, "Parse error", data);
11823
- }
11824
- /**
11825
- * The JSON sent is not a valid Request object.
11826
- */
11827
- static invalidRequest(data) {
11828
- return new _RequestError(-32600, "Invalid request", data);
11829
- }
11830
- /**
11831
- * The method does not exist / is not available.
11832
- */
11833
- static methodNotFound(method) {
11834
- return new _RequestError(-32601, "Method not found", { method });
11835
- }
11836
- /**
11837
- * Invalid method parameter(s).
11838
- */
11839
- static invalidParams(data) {
11840
- return new _RequestError(-32602, "Invalid params", data);
11841
- }
11842
- /**
11843
- * Internal JSON-RPC error.
11844
- */
11845
- static internalError(data) {
11846
- return new _RequestError(-32603, "Internal error", data);
11847
- }
11848
- /**
11849
- * Authentication required.
11850
- */
11851
- static authRequired(data) {
11852
- return new _RequestError(-32e3, "Authentication required", data);
11853
- }
11854
- /**
11855
- * Resource, such as a file, was not found
11856
- */
11857
- static resourceNotFound(uri) {
11858
- return new _RequestError(-32002, "Resource not found", uri && { uri });
11859
- }
11860
- toResult() {
11861
- return {
11862
- error: {
11863
- code: this.code,
11864
- message: this.message,
11865
- data: this.data
11866
- }
11867
- };
11868
- }
11869
- toErrorResponse() {
11870
- return {
11871
- code: this.code,
11872
- message: this.message,
11873
- data: this.data
11874
- };
11875
- }
11876
- };
11877
-
11878
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/language-model.js
11879
- var import_node_child_process = require("node:child_process");
11880
- var import_node_process9 = __toESM(require("node:process"), 1);
11881
- var import_node_stream2 = require("node:stream");
11882
- var import_zod4 = __toESM(require("zod"), 1);
11883
-
11884
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/format-tool-error.js
11885
- function formatToolError(toolResult) {
11886
- if (!toolResult || toolResult.length === 0) return "Unknown tool error";
11887
- const parts = [];
11888
- for (const blk of toolResult) {
11889
- if (blk.type === "content") {
11890
- if (blk.content.type === "text") {
11891
- parts.push(blk.content.text);
11892
- }
11893
- }
11894
- }
11895
- return parts.join("\n");
11896
- }
11897
-
11898
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-host.js
11899
- var import_node_net = require("node:net");
11900
-
11901
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/json-rpc.js
11902
- function createResponse(id, result) {
11903
- return {
11904
- jsonrpc: "2.0",
11905
- id,
11906
- result
11907
- };
11908
- }
11909
- function createErrorResponse(id, code, message, data) {
11910
- const error = {
11911
- code,
11912
- message
11913
- };
11914
- if (data !== void 0) {
11915
- error.data = data;
11916
- }
11917
- return {
11918
- jsonrpc: "2.0",
11919
- id,
11920
- error
11921
- };
11922
- }
11923
- function parseMessage(line) {
11924
- try {
11925
- const parsed = JSON.parse(line);
11926
- if (parsed.jsonrpc !== "2.0") return null;
11927
- return parsed;
11928
- } catch {
11929
- return null;
11930
- }
11931
- }
11932
- function serializeMessage2(message) {
11933
- return JSON.stringify(message);
11934
- }
11935
-
11936
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/types.js
11937
- var JsonRpcErrorCode = {
11938
- PARSE_ERROR: -32700,
11939
- INVALID_REQUEST: -32600,
11940
- METHOD_NOT_FOUND: -32601,
11941
- INVALID_PARAMS: -32602,
11942
- INTERNAL_ERROR: -32603
11943
- };
11944
- var ProxyMethod = {
11945
- // Host -> Proxy
11946
- REGISTER_TOOLS: "registerTools",
11947
- // Proxy -> Host
11948
- CALL_HANDLER: "callHandler"
11949
- };
11950
-
11951
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-runtime.js
11952
- var RUNTIME_CODE = `
11953
- /* MCP Protocol Version 2024-11-05 */
11954
- const isDeno=typeof Deno!=="undefined",MCP_VER="2024-11-05";
11955
- let tools=[],host=null,pending=new Map,buf="",hbuf="",rid=0;
11956
- const env=k=>isDeno?Deno.env.get(k):process.env[k];
11957
- const write=async m=>{
11958
- const s=JSON.stringify(m)+"\\n";
11959
- if(isDeno)await Deno.stdout.write(new TextEncoder().encode(s));
11960
- else process.stdout.write(s);
11961
- };
11962
- const send=(id,r,e)=>write({jsonrpc:"2.0",id,...(e?{error:e}:{result:r})});
11963
- const hostReq=(m,p)=>new Promise((res,rej)=>{
11964
- const id="r-"+ ++rid;
11965
- const s=JSON.stringify({jsonrpc:"2.0",id,method:m,params:p})+"\\n";
11966
- if(isDeno)host.write(new TextEncoder().encode(s));
11967
- else host.write(s);
11968
- const t=setTimeout(()=>{pending.delete(id);rej(new Error("timeout"))},30000);
11969
- pending.set(id,{resolve:v=>{clearTimeout(t);res(v)},reject:e=>{clearTimeout(t);rej(e)}});
11970
- });
11971
- const init=async()=>{
11972
- const p=parseInt(env("ACP_TOOL_PROXY_PORT")||"0",10);
11973
- if(p){
11974
- if(isDeno){
11975
- host=await Deno.connect({hostname:"127.0.0.1",port:p});
11976
- (async()=>{
11977
- const d=new TextDecoder(),b=new Uint8Array(65536);
11978
- while(true){const n=await host.read(b);if(!n)break;
11979
- hbuf+=d.decode(b.subarray(0,n));let ls=hbuf.split("\\n");hbuf=ls.pop();
11980
- for(let l of ls)if(l.trim())onHostMsg(l)}})();
11981
- }else{
11982
- host=require("net").createConnection({host:"127.0.0.1",port:p});
11983
- await new Promise(r=>host.on("connect",r));
11984
- host.on("data",d=>{hbuf+=d;let ls=hbuf.split("\\n");hbuf=ls.pop();
11985
- for(let l of ls)if(l.trim())onHostMsg(l)});
11986
- }
11987
- try{tools=await hostReq("getTools")}catch(e){
11988
- const m="Failed to get tools: "+e.message+"\\n";
11989
- if(isDeno)Deno.stderr.write(new TextEncoder().encode(m));
11990
- else process.stderr.write(m);
11991
- }
11992
- }
11993
- };
11994
- const onHostMsg=l=>{try{let r=JSON.parse(l),h=pending.get(r.id);
11995
- if(h){pending.delete(r.id);r.error?h.reject(new Error(r.error.message)):h.resolve(r.result)}}catch{}};
11996
- const handle=async l=>{let m;try{m=JSON.parse(l)}catch{return}if(m.jsonrpc!=="2.0")return;
11997
- if(m.method==="initialize")send(m.id,{protocolVersion:MCP_VER,capabilities:{tools:{}},serverInfo:{name:"proxy",version:"1.0"}});
11998
- else if(m.method==="notifications/initialized");
11999
- else if(m.method==="tools/list")send(m.id,{tools:tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))});
12000
- else if(m.method==="tools/call"){let p=m.params,t=tools.find(x=>x.name===p.name);
12001
- if(!t)send(m.id,null,{code:-32601,message:"Not found"});
12002
- else try{let r=await hostReq("callHandler",{name:p.name,args:p.arguments||{}});send(m.id,r)}
12003
- catch(e){send(m.id,{content:[{type:"text",text:"Error: "+e.message}],isError:true})}}
12004
- else send(m.id,null,{code:-32601,message:"Unknown"});
12005
- };
12006
- init().then(async()=>{
12007
- if(isDeno){
12008
- const d=new TextDecoder(),b=new Uint8Array(65536);
12009
- while(true){const n=await Deno.stdin.read(b);if(!n)break;
12010
- buf+=d.decode(b.subarray(0,n));let ls=buf.split("\\n");buf=ls.pop();for(let l of ls)if(l.trim())handle(l)}
12011
- }else{
12012
- process.stdin.setEncoding("utf8");
12013
- process.stdin.on("data",c=>{buf+=c;let ls=buf.split("\\n");buf=ls.pop();for(let l of ls)if(l.trim())handle(l)});
12014
- }
12015
- });
12016
- `.trim().replace(/\n/g, "");
12017
-
12018
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-host.js
12019
- var ToolProxyHost = class {
12020
- server = null;
12021
- connections = [];
12022
- tools = /* @__PURE__ */ new Map();
12023
- serverName;
12024
- port = 0;
12025
- constructor(name = "acp-tool-proxy") {
12026
- this.serverName = name;
12027
- }
12028
- /**
12029
- * Register an AI SDK tool to be exposed through the proxy
12030
- */
12031
- registerTool(name, tool3) {
12032
- this.tools.set(name, tool3);
12033
- }
12034
- /**
12035
- * Register multiple tools at once
12036
- */
12037
- registerTools(tools) {
12038
- for (const [name, tool3] of Object.entries(tools)) {
12039
- this.registerTool(name, tool3);
12040
- }
12041
- }
12042
- /**
12043
- * Get tool definitions for the runtime
12044
- */
12045
- getToolDefinitions() {
12046
- const definitions = [];
12047
- for (const [name, tool3] of this.tools.entries()) {
12048
- definitions.push({
12049
- name,
12050
- description: tool3.description || `Tool: ${name}`,
12051
- // inputSchema from Tool can be Zod or JSON schema, cast to JSON schema format
12052
- inputSchema: tool3.inputSchema || {
12053
- type: "object",
12054
- properties: {}
12055
- }
12056
- });
12057
- }
12058
- return definitions;
12059
- }
12060
- /**
12061
- * Start TCP server and return MCP server config for ACP
12062
- */
12063
- async start() {
12064
- if (!this.server) {
12065
- await this.startServer();
12066
- }
12067
- return this.getServerConfig();
12068
- }
12069
- /**
12070
- * Get MCP server configuration
12071
- */
12072
- getServerConfig() {
12073
- return {
12074
- name: this.serverName,
12075
- command: "node",
12076
- args: [
12077
- "-e",
12078
- RUNTIME_CODE
12079
- ],
12080
- env: [
12081
- {
12082
- name: "ACP_TOOL_PROXY_PORT",
12083
- value: String(this.port)
12084
- }
12085
- ]
12086
- };
12087
- }
12088
- /**
12089
- * Start TCP server to receive tool execution requests
12090
- */
12091
- startServer() {
12092
- return new Promise((resolve3, reject) => {
12093
- this.server = (0, import_node_net.createServer)((socket) => {
12094
- this.handleConnection(socket);
12095
- });
12096
- this.server.on("error", (err) => {
12097
- reject(err);
12098
- });
12099
- this.server.listen(0, "127.0.0.1", () => {
12100
- const address = this.server.address();
12101
- if (typeof address === "object" && address) {
12102
- this.port = address.port;
12103
- resolve3();
12104
- } else {
12105
- reject(new Error("Failed to get server address"));
12106
- }
12107
- });
12108
- });
12109
- }
12110
- /**
12111
- * Handle incoming connection from runtime
12112
- */
12113
- handleConnection(socket) {
12114
- this.connections.push(socket);
12115
- let buffer = "";
12116
- socket.on("data", (data) => {
12117
- buffer += data.toString();
12118
- const lines = buffer.split("\n");
12119
- buffer = lines.pop() || "";
12120
- for (const line of lines) {
12121
- if (!line.trim()) continue;
12122
- const message = parseMessage(line);
12123
- if (!message) continue;
12124
- if ("method" in message) {
12125
- this.handleRequest(socket, message).catch((err) => console.error("[ToolProxy] Error handling request:", err));
12126
- }
12127
- }
12128
- });
12129
- socket.on("close", () => {
12130
- this.connections = this.connections.filter((c) => c !== socket);
12131
- });
12132
- socket.on("error", (err) => {
12133
- console.error("[ToolProxy] Socket error:", err);
12134
- });
12135
- }
12136
- /**
12137
- * Handle JSON-RPC request from runtime
12138
- */
12139
- async handleRequest(socket, request) {
12140
- try {
12141
- if (request.method === ProxyMethod.CALL_HANDLER) {
12142
- const params = request.params;
12143
- const tool3 = this.tools.get(params.name);
12144
- if (!tool3) {
12145
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.METHOD_NOT_FOUND, `Tool not found: ${params.name}`));
12146
- return;
12147
- }
12148
- if (!tool3.execute) {
12149
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.INTERNAL_ERROR, `Tool has no execute function: ${params.name}`));
12150
- return;
12151
- }
12152
- const result = await tool3.execute?.(params.args, {
12153
- toolCallId: params.name,
12154
- messages: []
12155
- });
12156
- const toolResult = {
12157
- content: [
12158
- {
12159
- type: "text",
12160
- text: typeof result === "string" ? result : JSON.stringify(result)
12161
- }
12162
- ]
12163
- };
12164
- this.sendResponse(socket, createResponse(request.id, toolResult));
12165
- } else if (request.method === "getTools") {
12166
- const definitions = this.getToolDefinitions();
12167
- this.sendResponse(socket, createResponse(request.id, definitions));
12168
- } else {
12169
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.METHOD_NOT_FOUND, `Unknown method: ${request.method}`));
12170
- }
12171
- } catch (error) {
12172
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.INTERNAL_ERROR, error instanceof Error ? error.message : String(error)));
12173
- }
12174
- }
12175
- /**
12176
- * Send response to runtime
12177
- */
12178
- sendResponse(socket, response) {
12179
- socket.write(serializeMessage2(response) + "\n");
12180
- }
12181
- /**
12182
- * Stop the TCP server
12183
- */
12184
- stop() {
12185
- for (const socket of this.connections) {
12186
- socket.destroy();
12187
- }
12188
- this.connections = [];
12189
- if (this.server) {
12190
- this.server.close();
12191
- this.server = null;
12192
- }
12193
- this.port = 0;
12194
- }
12195
- };
12196
-
12197
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/acp-tool.js
12198
- var import_ai2 = require("ai");
12199
- var ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME = "acp.acp_provider_agent_dynamic_tool";
12200
- var executeRegistry = /* @__PURE__ */ new Map();
12201
- function getACPDynamicTool() {
12202
- return {
12203
- [ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME]: (0, import_ai2.tool)({
12204
- type: "provider-defined",
12205
- id: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME,
12206
- name: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME,
12207
- args: {},
12208
- inputSchema: (0, import_ai2.jsonSchema)({})
12209
- })
12210
- };
12211
- }
12212
- function getExecuteByName(name) {
12213
- return executeRegistry.get(name);
12214
- }
12215
- function hasRegisteredExecute(name) {
12216
- return executeRegistry.has(name);
12217
- }
12218
-
12219
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/utils.js
12220
- function extractBase64Data(data) {
12221
- return data.includes(",") ? data.split(",")[1] : data;
12222
- }
12223
-
12224
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/convert-utils.js
12225
- var import_ai3 = require("ai");
12226
- function convertAiSdkMessagesToAcp(options, isFreshSession) {
12227
- const messages = !isFreshSession ? options.prompt.filter((m) => m.role === "user").slice(-1) : options.prompt;
12228
- const contentBlocks = [];
12229
- for (const msg of messages) {
12230
- let prefix = "";
12231
- if (msg.role === "system") prefix = "System: ";
12232
- else if (msg.role === "assistant") prefix = "Assistant: ";
12233
- else if (msg.role === "tool") prefix = "Result: ";
12234
- if (Array.isArray(msg.content)) {
12235
- let isFirst = true;
12236
- for (const part of msg.content) {
12237
- if (part.type === "text") {
12238
- const text = isFirst ? `${prefix}${part.text} ` : part.text;
12239
- contentBlocks.push({
12240
- type: "text",
12241
- text
12242
- });
12243
- isFirst = false;
12244
- } else if (part.type === "tool-call") {
12245
- const toolCallText = `[Tool Call: ${part.toolName}(${JSON.stringify(part.input)})]`;
12246
- const text = isFirst ? `${prefix}${toolCallText} ` : toolCallText;
12247
- contentBlocks.push({
12248
- type: "text",
12249
- text
12250
- });
12251
- isFirst = false;
12252
- } else if (part.type === "tool-result") {
12253
- const resultData = part.result ?? part.output;
12254
- const resultText = JSON.stringify(resultData) ?? "null";
12255
- const text = isFirst ? `${prefix}${resultText} ` : resultText;
12256
- contentBlocks.push({
12257
- type: "text",
12258
- text
12259
- });
12260
- isFirst = false;
12261
- } else if (part.type === "file" && typeof part.data === "string") {
12262
- const type = part.mediaType.startsWith("image/") ? "image" : part.mediaType.startsWith("audio/") ? "audio" : null;
12263
- if (type) {
12264
- contentBlocks.push({
12265
- type,
12266
- mimeType: part.mediaType,
12267
- data: extractBase64Data(part.data)
12268
- });
12269
- }
12270
- }
12271
- }
12272
- } else if (typeof msg.content === "string") {
12273
- contentBlocks.push({
12274
- type: "text",
12275
- text: `${prefix}${msg.content} `
12276
- });
12277
- }
12278
- }
12279
- return contentBlocks;
12280
- }
12281
- function extractACPTools(tools, prepared = true) {
12282
- const acpTools2 = [];
12283
- if (!tools) {
12284
- return acpTools2;
12285
- }
12286
- const toolsArray = Array.isArray(tools) ? tools : Object.entries(tools).map(([name, tool3]) => ({
12287
- type: "function",
12288
- name,
12289
- ...tool3
12290
- }));
12291
- for (const t of toolsArray) {
12292
- if (t.type === "function") {
12293
- const toolWithSchema = t;
12294
- const toolInputSchema = toolWithSchema.inputSchema;
12295
- if (hasRegisteredExecute(t.name) && toolInputSchema) {
12296
- const execute = getExecuteByName(t.name);
12297
- if (execute) {
12298
- acpTools2.push({
12299
- ...t,
12300
- name: t.name,
12301
- inputSchema: prepared ? toolInputSchema : (0, import_ai3.asSchema)(toolInputSchema).jsonSchema,
12302
- execute
12303
- });
12304
- }
12305
- }
12306
- }
12307
- }
12308
- return acpTools2;
12309
- }
12310
-
12311
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/language-model.js
12312
- var ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2 = "acp.acp_provider_agent_dynamic_tool";
12313
- var providerAgentDynamicToolSchema = import_zod4.default.object({
12314
- toolCallId: import_zod4.default.string().describe("The unique ID of the tool call."),
12315
- toolName: import_zod4.default.string().describe("The name of the tool being called."),
12316
- args: import_zod4.default.record(import_zod4.default.unknown()).describe("The input arguments for the tool call.")
12317
- });
12318
- var ACPAISDKClient = class {
12319
- onSessionUpdateCallback;
12320
- onPermissionRequestCallback;
12321
- setSessionUpdateHandler(handler) {
12322
- this.onSessionUpdateCallback = handler;
12323
- }
12324
- setPermissionRequestHandler(handler) {
12325
- this.onPermissionRequestCallback = handler;
12326
- }
12327
- sessionUpdate(params) {
12328
- if (this.onSessionUpdateCallback) {
12329
- this.onSessionUpdateCallback(params);
12330
- }
12331
- return Promise.resolve();
12332
- }
12333
- async requestPermission(params) {
12334
- if (this.onPermissionRequestCallback) {
12335
- return await this.onPermissionRequestCallback(params);
12336
- }
12337
- return {
12338
- outcome: {
12339
- outcome: "selected",
12340
- optionId: params.options[0]?.optionId || "allow"
12341
- }
12342
- };
12343
- }
12344
- writeTextFile(_params) {
12345
- throw new Error("File operations not implemented in language model client");
12346
- }
12347
- readTextFile(_params) {
12348
- throw new Error("File operations not implemented in language model client");
12349
- }
12350
- };
12351
- var ACPLanguageModel = class {
12352
- specificationVersion = "v2";
12353
- provider = "acp";
12354
- modelId;
12355
- modeId;
12356
- supportedUrls = {};
12357
- config;
12358
- agentProcess = null;
12359
- connection = null;
12360
- sessionId = null;
12361
- sessionResponse = null;
12362
- client = null;
12363
- currentModelId = null;
12364
- currentModeId = null;
12365
- isFreshSession = true;
12366
- // State for managing stream conversion
12367
- textBlockIndex = 0;
12368
- thinkBlockIndex = 0;
12369
- currentTextId = null;
12370
- currentThinkingId = null;
12371
- toolCallsMap = /* @__PURE__ */ new Map();
12372
- // Tool proxy for host-side tool execution
12373
- toolProxyHost = null;
12374
- constructor(modelId, modeId, config) {
12375
- this.modelId = modelId;
12376
- this.modeId = modeId;
12377
- this.config = config;
12378
- }
12379
- /**
12380
- * Resets the internal state used for stream conversion.
12381
- */
12382
- resetStreamState() {
12383
- this.textBlockIndex = 0;
12384
- this.thinkBlockIndex = 0;
12385
- this.currentTextId = null;
12386
- this.currentThinkingId = null;
12387
- this.toolCallsMap.clear();
12388
- }
12389
- /**
12390
- * Parses a 'tool_call' notification update into a structured object.
12391
- * Note: We only use rawInput for tool input (content is for UI display).
12392
- */
12393
- parseToolCall(update) {
12394
- if (update.sessionUpdate !== "tool_call") {
12395
- throw new Error("Invalid update type for parseToolCall");
12396
- }
12397
- const toolCallId = update.toolCallId;
12398
- const toolName = update.title || update.toolCallId;
12399
- const toolInput = update.rawInput ?? {};
12400
- return {
12401
- toolCallId,
12402
- toolName,
12403
- toolInput
12404
- };
12405
- }
12406
- /**
12407
- * Parses a 'tool_call_update' notification update into a structured object.
12408
- * Note: We only use rawOutput for tool result (content is for UI display).
12409
- */
12410
- parseToolResult(update) {
12411
- if (update.sessionUpdate !== "tool_call_update") {
12412
- throw new Error("Invalid update type for parseToolResult");
12413
- }
12414
- const toolCallId = update.toolCallId;
12415
- const toolName = update.title || update.toolCallId;
12416
- const toolResult = update.rawOutput ?? update.content ?? null;
12417
- const isError2 = update.status === "failed";
12418
- return {
12419
- toolCallId,
12420
- toolName,
12421
- toolResult,
12422
- isError: isError2,
12423
- status: update.status
12424
- };
12425
- }
12426
- /**
12427
- * Converts AI SDK prompt messages into ACP ContentBlock objects.
12428
- * When session exists, only extracts the last user message (history is in session).
12429
- * Prefixes text with role since ACP ContentBlock has no role field.
12430
- */
12431
- /**
12432
- * Ensures the ACP agent process is running and a session is established.
12433
- * @param acpTools - Tools from streamText options to proxy
12434
- */
12435
- /**
12436
- * Connects to the ACP agent process and initializes the protocol connection.
12437
- * Does NOT start a session.
12438
- */
12439
- async connectClient() {
12440
- if (this.connection) {
12441
- return;
12442
- }
12443
- if (!this.agentProcess) {
12444
- const sessionCwd = this.config.session?.cwd || (typeof import_node_process9.default.cwd === "function" ? import_node_process9.default.cwd() : "/");
12445
- this.agentProcess = (0, import_node_child_process.spawn)(this.config.command, this.config.args ?? [], {
12446
- stdio: [
12447
- "pipe",
12448
- "pipe",
12449
- "inherit"
12450
- ],
12451
- env: {
12452
- ...import_node_process9.default.env,
12453
- ...this.config.env
12454
- },
12455
- cwd: sessionCwd
12456
- });
12457
- if (!this.agentProcess.stdout || !this.agentProcess.stdin) {
12458
- throw new Error("Failed to spawn agent process with stdio");
12459
- }
12460
- const input = import_node_stream2.Writable.toWeb(this.agentProcess.stdin);
12461
- const output = import_node_stream2.Readable.toWeb(this.agentProcess.stdout);
12462
- this.client = new ACPAISDKClient();
12463
- this.connection = new ClientSideConnection(() => this.client, ndJsonStream(input, output));
12464
- }
12465
- if (!this.connection) {
12466
- throw new Error("Connection not initialized");
12467
- }
12468
- const initConfig = {
12469
- ...this.config.initialize,
12470
- protocolVersion: this.config.initialize?.protocolVersion ?? PROTOCOL_VERSION,
12471
- clientCapabilities: this.config.initialize?.clientCapabilities ?? {
12472
- fs: {
12473
- readTextFile: false,
12474
- writeTextFile: false
12475
- },
12476
- terminal: false
12477
- }
12478
- };
12479
- const initResult = await this.connection.initialize(initConfig);
12480
- const validAuthMethods = initResult.authMethods?.find((a) => a.id === this.config.authMethodId)?.id;
12481
- if ((initResult.authMethods?.length ?? 0) > 0) {
12482
- if (!this.config.authMethodId || !validAuthMethods) {
12483
- console.log("[acp-ai-provider] Warning: No authMethodId specified in config, skipping authentication step. If this is not desired, please set one of the authMethodId in the ACPProviderSettings.", JSON.stringify(initResult.authMethods, null, 2));
12484
- }
12485
- if (this.config.authMethodId && validAuthMethods) {
12486
- await this.connection.authenticate({
12487
- methodId: this.config.authMethodId ?? initResult.authMethods?.[0].id
12488
- });
12489
- }
12490
- }
12491
- }
12492
- /**
12493
- * Starts a new session or updates the existing one.
12494
- * Assumes connectClient() has been called.
12495
- */
12496
- async startSession(acpTools2) {
12497
- if (!this.connection) {
12498
- throw new Error("Not connected");
12499
- }
12500
- const mcpServers = [
12501
- ...this.config.session?.mcpServers ?? []
12502
- ];
12503
- let toolsAdded = false;
12504
- if (acpTools2 && acpTools2.length > 0 && !this.toolProxyHost) {
12505
- console.log("[acp-ai-provider] Setting up tool proxy for client-side tools...", acpTools2.map((t) => t.name));
12506
- this.toolProxyHost = new ToolProxyHost("acp-ai-sdk-tools");
12507
- for (const t of acpTools2) {
12508
- this.toolProxyHost.registerTool(t.name, t);
12509
- }
12510
- toolsAdded = true;
12511
- }
12512
- if (this.toolProxyHost) {
12513
- const proxyConfig = await this.toolProxyHost.start();
12514
- mcpServers.push(proxyConfig);
12515
- }
12516
- if (this.sessionId && toolsAdded) {
12517
- this.sessionResponse = await this.connection.newSession({
12518
- ...this.config.session,
12519
- cwd: this.config.session?.cwd ?? import_node_process9.default.cwd(),
12520
- mcpServers
12521
- });
12522
- this.sessionId = this.sessionResponse.sessionId;
12523
- this.isFreshSession = true;
12524
- await this.applySessionDelay();
12525
- return;
12526
- }
12527
- if (this.sessionId) {
12528
- return;
12529
- }
12530
- if (this.config.existingSessionId) {
12531
- await this.connection.loadSession({
12532
- sessionId: this.config.existingSessionId,
12533
- cwd: this.config.session?.cwd ?? import_node_process9.default.cwd(),
12534
- mcpServers
12535
- });
12536
- this.sessionId = this.config.existingSessionId;
12537
- this.sessionResponse = {
12538
- sessionId: this.config.existingSessionId
12539
- };
12540
- this.isFreshSession = false;
12541
- } else {
12542
- this.sessionResponse = await this.connection.newSession({
12543
- ...this.config.session,
12544
- cwd: this.config.session?.cwd ?? import_node_process9.default.cwd(),
12545
- mcpServers
12546
- });
12547
- this.sessionId = this.sessionResponse.sessionId;
12548
- this.isFreshSession = true;
12549
- }
12550
- const { models, modes } = this.sessionResponse ?? {};
12551
- if (models?.currentModelId) {
12552
- this.currentModelId = models.currentModelId;
12553
- }
12554
- if (modes?.currentModeId) {
12555
- this.currentModeId = modes.currentModeId;
12556
- }
12557
- if (this.modelId && this.modelId !== this.currentModelId) {
12558
- await this.setModel(this.modelId);
12559
- this.currentModelId = this.modelId;
12560
- }
12561
- if (this.modeId && this.modeId !== this.currentModeId) {
12562
- await this.setMode(this.modeId);
12563
- this.currentModeId = this.modeId;
12564
- }
12565
- await this.applySessionDelay();
12566
- }
12567
- async applySessionDelay() {
12568
- if (this.config.sessionDelayMs) {
12569
- console.log(`[acp-ai-provider] Waiting ${this.config.sessionDelayMs}ms after session setup...`);
12570
- await new Promise((resolve3) => setTimeout(resolve3, this.config.sessionDelayMs));
12571
- }
12572
- }
12573
- /**
12574
- * Ensures the ACP agent process is running and a session is established.
12575
- * @param acpTools - Tools from streamText options to proxy
12576
- */
12577
- async ensureConnected(acpTools2) {
12578
- await this.connectClient();
12579
- await this.startSession(acpTools2);
12580
- }
12581
- /**
12582
- * Clears connection state. Skips if persistSession is enabled.
12583
- */
12584
- cleanup() {
12585
- if (this.config.persistSession) return;
12586
- this.forceCleanup();
12587
- }
12588
- /**
12589
- * Returns the current session ID.
12590
- */
12591
- getSessionId() {
12592
- return this.sessionId;
12593
- }
12594
- /**
12595
- * Initializes the session and returns session info (models, modes, meta).
12596
- * Call this before prompting to discover available options.
12597
- */
12598
- /**
12599
- * Initializes the session and returns session info (models, modes, meta).
12600
- * Call this before prompting to discover available options.
12601
- *
12602
- * @param acpTools - Optional list of tools to register during session initialization.
12603
- */
12604
- async initSession(tools) {
12605
- const acpTools2 = extractACPTools(tools, false);
12606
- await this.ensureConnected(acpTools2.length > 0 ? acpTools2 : void 0);
12607
- return this.sessionResponse;
12608
- }
12609
- /**
12610
- * Sets the session mode (e.g., "ask", "plan").
12611
- */
12612
- async setMode(modeId) {
12613
- if (!this.connection || !this.sessionId) {
12614
- throw new Error("Not connected. Call preconnect() first.");
12615
- }
12616
- const availableModes = this.sessionResponse?.modes?.availableModes;
12617
- if (availableModes) {
12618
- const foundMode = availableModes.find((m) => m.id === modeId);
12619
- if (!foundMode) {
12620
- const availableList = availableModes.map((m) => m.id).join(", ");
12621
- const currentInfo = this.sessionResponse?.modes?.currentModeId ? ` (Current: "${this.sessionResponse.modes.currentModeId}")` : "";
12622
- throw new Error(`Mode "${modeId}" is not available${currentInfo}. Available modes: ${availableList}`);
12623
- }
12624
- }
12625
- await this.connection.setSessionMode({
12626
- sessionId: this.sessionId,
12627
- modeId
12628
- });
12629
- this.currentModeId = modeId;
12630
- }
12631
- /**
12632
- * Sets the session model.
12633
- */
12634
- async setModel(modelId) {
12635
- if (!this.connection || !this.sessionId) {
12636
- throw new Error("Not connected. Call preconnect() first.");
12637
- }
12638
- const { models } = this.sessionResponse ?? {};
12639
- if (models?.availableModels) {
12640
- if (!models.availableModels.some((m) => m.modelId === modelId)) {
12641
- const availableList = models.availableModels.map((m) => m.modelId).join(", ");
12642
- const currentInfo = this.currentModelId ? ` (Current: "${this.currentModelId}")` : "";
12643
- throw new Error(`Model "${modelId}" is not available${currentInfo}. Available models: ${availableList}`);
12644
- }
12645
- }
12646
- await this.connection.setSessionModel({
12647
- sessionId: this.sessionId,
12648
- modelId
12649
- });
12650
- this.currentModelId = modelId;
12651
- }
12652
- /**
12653
- * Forces cleanup regardless of persistSession setting.
12654
- */
12655
- forceCleanup() {
12656
- if (this.toolProxyHost) {
12657
- this.toolProxyHost.stop();
12658
- this.toolProxyHost = null;
12659
- }
12660
- if (this.agentProcess) {
12661
- this.agentProcess.kill();
12662
- this.agentProcess.stdin?.end();
12663
- this.agentProcess.stdout?.destroy();
12664
- this.agentProcess = null;
12665
- }
12666
- this.connection = null;
12667
- this.sessionId = null;
12668
- this.sessionResponse = null;
12669
- this.client = null;
12670
- }
12671
- /**
12672
- * Emits raw content (plan, diffs, terminals) as raw stream parts.
12673
- * Plan data is emitted directly, while diffs and terminals are bound to a toolCallId.
12674
- */
12675
- emitRawContent(controller, data) {
12676
- if ("entries" in data) {
12677
- controller.enqueue({
12678
- type: "raw",
12679
- rawValue: JSON.stringify({
12680
- type: "plan",
12681
- entries: data.entries
12682
- })
12683
- });
12684
- return;
12685
- }
12686
- for (const item of data.content) {
12687
- if (item.type === "diff" || item.type === "terminal") {
12688
- controller.enqueue({
12689
- type: "raw",
12690
- rawValue: JSON.stringify({
12691
- ...item,
12692
- toolCallId: data.toolCallId
12693
- })
12694
- });
12695
- }
12696
- }
12697
- }
12698
- /**
12699
- * Standardized handler for converting SessionNotifications into
12700
- * LanguageModelV2StreamPart objects, pushing them onto a stream controller.
12701
- */
12702
- handleStreamNotification(controller, notification) {
12703
- const update = notification.update;
12704
- switch (update.sessionUpdate) {
12705
- case "plan":
12706
- this.emitRawContent(controller, {
12707
- type: "plan",
12708
- entries: update.entries
12709
- });
12710
- break;
12711
- case "agent_thought_chunk":
12712
- if (!this.currentThinkingId) {
12713
- this.currentThinkingId = `reasoning - ${this.thinkBlockIndex++} `;
12714
- controller.enqueue({
12715
- type: "reasoning-start",
12716
- id: this.currentThinkingId
12717
- });
12718
- }
12719
- controller.enqueue({
12720
- type: "reasoning-delta",
12721
- id: this.currentThinkingId,
12722
- delta: update.content.type === "text" ? update.content.text : ""
12723
- });
12724
- break;
12725
- case "agent_message_chunk":
12726
- if (this.currentThinkingId) {
12727
- controller.enqueue({
12728
- type: "reasoning-end",
12729
- id: this.currentThinkingId
12730
- });
12731
- this.currentThinkingId = null;
12732
- }
12733
- if (update.content.type === "text") {
12734
- const textChunk = update.content.text;
12735
- if (!this.currentTextId) {
12736
- this.currentTextId = `text - ${this.textBlockIndex++} `;
12737
- controller.enqueue({
12738
- type: "text-start",
12739
- id: this.currentTextId
12740
- });
12741
- }
12742
- controller.enqueue({
12743
- type: "text-delta",
12744
- id: this.currentTextId,
12745
- delta: textChunk
12746
- });
12747
- }
12748
- break;
12749
- case "tool_call": {
12750
- if (this.currentTextId) {
12751
- controller.enqueue({
12752
- type: "text-end",
12753
- id: this.currentTextId
12754
- });
12755
- this.currentTextId = null;
12756
- }
12757
- if (this.currentThinkingId) {
12758
- controller.enqueue({
12759
- type: "reasoning-end",
12760
- id: this.currentThinkingId
12761
- });
12762
- this.currentThinkingId = null;
12763
- }
12764
- const { toolCallId, toolName, toolInput } = this.parseToolCall(update);
12765
- const existingToolCall = this.toolCallsMap.get(toolCallId);
12766
- const hasInput = toolInput && typeof toolInput === "object" && Object.keys(toolInput).length > 0;
12767
- if (!existingToolCall) {
12768
- this.toolCallsMap.set(toolCallId, {
12769
- index: this.toolCallsMap.size,
12770
- name: toolName,
12771
- inputStarted: true,
12772
- inputAvailable: !!hasInput
12773
- });
12774
- controller.enqueue({
12775
- type: "tool-input-start",
12776
- id: toolCallId,
12777
- toolName
12778
- });
12779
- if (hasInput) {
12780
- controller.enqueue({
12781
- type: "tool-call",
12782
- toolCallId,
12783
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12784
- input: JSON.stringify({
12785
- toolCallId,
12786
- toolName,
12787
- args: toolInput
12788
- })
12789
- });
12790
- }
12791
- } else if (!existingToolCall.inputAvailable && hasInput) {
12792
- existingToolCall.inputAvailable = true;
12793
- if (update.title && existingToolCall.name !== update.title && update.title !== toolCallId) {
12794
- existingToolCall.name = update.title;
12795
- }
12796
- controller.enqueue({
12797
- type: "tool-call",
12798
- toolCallId,
12799
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12800
- input: JSON.stringify({
12801
- toolCallId,
12802
- toolName: existingToolCall.name,
12803
- args: toolInput
12804
- })
12805
- });
12806
- }
12807
- break;
12808
- }
12809
- case "tool_call_update": {
12810
- const { toolCallId, toolName, toolResult, isError: isError2, status } = this.parseToolResult(update);
12811
- let toolInfo = this.toolCallsMap.get(toolCallId);
12812
- if (status === "in_progress") {
12813
- if (!toolInfo) {
12814
- toolInfo = {
12815
- index: this.toolCallsMap.size,
12816
- name: toolName,
12817
- inputStarted: true,
12818
- inputAvailable: true
12819
- };
12820
- this.toolCallsMap.set(toolCallId, toolInfo);
12821
- controller.enqueue({
12822
- type: "tool-input-start",
12823
- id: toolCallId,
12824
- toolName
12825
- });
12826
- }
12827
- if (!toolInfo.inputAvailable) {
12828
- toolInfo.inputAvailable = true;
12829
- if (update.title && toolInfo.name !== update.title && update.title !== toolCallId) {
12830
- toolInfo.name = update.title;
12831
- }
12832
- controller.enqueue({
12833
- type: "tool-call",
12834
- toolCallId,
12835
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12836
- input: JSON.stringify({
12837
- toolCallId,
12838
- toolName: toolInfo.name,
12839
- args: {}
12840
- })
12841
- });
12842
- }
12843
- const content2 = update.content ?? [];
12844
- if (content2.length > 0) {
12845
- this.emitRawContent(controller, {
12846
- content: content2,
12847
- toolCallId
12848
- });
12849
- }
12850
- break;
12851
- }
12852
- if (![
12853
- "completed",
12854
- "failed"
12855
- ].includes(status)) {
12856
- break;
12857
- }
12858
- if (!toolInfo) {
12859
- toolInfo = {
12860
- index: this.toolCallsMap.size,
12861
- name: toolName,
12862
- inputAvailable: true
12863
- };
12864
- this.toolCallsMap.set(toolCallId, toolInfo);
12865
- controller.enqueue({
12866
- type: "tool-call",
12867
- toolCallId,
12868
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12869
- input: JSON.stringify({
12870
- toolCallId,
12871
- toolName
12872
- })
12873
- });
12874
- } else if (!toolInfo.inputAvailable) {
12875
- toolInfo.inputAvailable = true;
12876
- if (update.title && toolInfo.name !== update.title && update.title !== toolCallId) {
12877
- toolInfo.name = update.title;
12878
- }
12879
- controller.enqueue({
12880
- type: "tool-call",
12881
- toolCallId,
12882
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12883
- input: JSON.stringify({
12884
- toolCallId,
12885
- toolName: toolInfo.name,
12886
- args: {}
12887
- })
12888
- });
12889
- }
12890
- controller.enqueue({
12891
- type: "tool-result",
12892
- toolCallId,
12893
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12894
- result: toolResult,
12895
- providerExecuted: true,
12896
- // https://github.com/vercel/ai/blob/282f062922cb59167dd3a11e3af67cfa0b75f317/packages/ai/src/generate-text/run-tools-transformation.ts#L316
12897
- ...isError2 && {
12898
- isError: true,
12899
- result: new Error(formatToolError(toolResult))
12900
- }
12901
- });
12902
- const content = update.content ?? [];
12903
- if (content.length > 0) {
12904
- this.emitRawContent(controller, {
12905
- content,
12906
- toolCallId
12907
- });
12908
- }
12909
- break;
12910
- }
12911
- }
12912
- }
12913
- /**
12914
- * Implements the non-streaming generation method.
12915
- */
12916
- async doGenerate(options) {
12917
- try {
12918
- await this.ensureConnected();
12919
- const promptContent = convertAiSdkMessagesToAcp(options, this.isFreshSession);
12920
- this.isFreshSession = false;
12921
- let accumulatedText = "";
12922
- const toolCalls = [];
12923
- const toolResults = /* @__PURE__ */ new Map();
12924
- const mockController = {
12925
- enqueue: (part) => {
12926
- switch (part.type) {
12927
- case "text-delta":
12928
- accumulatedText += part.delta;
12929
- break;
12930
- case "tool-call": {
12931
- const inputData = JSON.parse(part.input);
12932
- toolCalls.push({
12933
- id: part.toolCallId,
12934
- name: inputData.toolName,
12935
- input: inputData.args
12936
- });
12937
- break;
12938
- }
12939
- case "tool-result": {
12940
- const matchingToolCall = toolCalls.find((tc) => tc.id === part.toolCallId);
12941
- toolResults.set(part.toolCallId, {
12942
- name: matchingToolCall?.name || part.toolCallId,
12943
- result: part.result,
12944
- isError: part.isError
12945
- });
12946
- break;
12947
- }
12948
- // Other stream parts (reasoning, start/end blocks, etc.)
12949
- // are ignored in non-streaming mode
12950
- default:
12951
- break;
12952
- }
12953
- }
12954
- };
12955
- const streamHandler = this.handleStreamNotification.bind(this);
12956
- this.resetStreamState();
12957
- if (this.client) {
12958
- this.client.setSessionUpdateHandler((notification) => {
12959
- streamHandler(mockController, notification);
12960
- });
12961
- }
12962
- const response = await this.connection.prompt({
12963
- sessionId: this.sessionId,
12964
- prompt: promptContent
12965
- });
12966
- const content = [];
12967
- if (accumulatedText.trim()) {
12968
- content.push({
12969
- type: "text",
12970
- text: accumulatedText
12971
- });
12972
- }
12973
- for (const toolCall of toolCalls) {
12974
- content.push({
12975
- type: "tool-call",
12976
- toolCallId: toolCall.id,
12977
- toolName: toolCall.name,
12978
- args: JSON.stringify(toolCall.input),
12979
- input: toolCall.input,
12980
- output: toolResults.get(toolCall.id)?.result
12981
- });
12982
- }
12983
- const result = {
12984
- content,
12985
- finishReason: response.stopReason === "end_turn" ? "stop" : "other",
12986
- usage: {
12987
- inputTokens: 0,
12988
- outputTokens: 0,
12989
- totalTokens: 0
12990
- },
12991
- warnings: []
12992
- };
12993
- this.cleanup();
12994
- return result;
12995
- } catch (error) {
12996
- this.cleanup();
12997
- throw error;
12998
- }
12999
- }
13000
- /**
13001
- * Implements the streaming generation method.
13002
- */
13003
- async doStream(options) {
13004
- const acpTools2 = extractACPTools(options.tools);
13005
- await this.ensureConnected(acpTools2.length > 0 ? acpTools2 : void 0);
13006
- const promptContent = convertAiSdkMessagesToAcp(options, this.isFreshSession);
13007
- this.isFreshSession = false;
13008
- const connection = this.connection;
13009
- const sessionId = this.sessionId;
13010
- const client = this.client;
13011
- const cleanup = () => this.cleanup();
13012
- const streamHandler = this.handleStreamNotification.bind(this);
13013
- const stream = new ReadableStream({
13014
- start: async (controller) => {
13015
- controller.enqueue({
13016
- type: "stream-start",
13017
- warnings: []
13018
- });
13019
- this.resetStreamState();
13020
- try {
13021
- if (client) {
13022
- client.setSessionUpdateHandler((notification) => {
13023
- streamHandler(controller, notification);
13024
- });
13025
- }
13026
- const response = await connection.prompt({
13027
- sessionId,
13028
- prompt: promptContent
13029
- });
13030
- controller.enqueue({
13031
- type: "finish",
13032
- finishReason: response.stopReason === "end_turn" ? "stop" : "other",
13033
- usage: {
13034
- inputTokens: 0,
13035
- outputTokens: 0,
13036
- totalTokens: 0
13037
- }
13038
- });
13039
- controller.close();
13040
- cleanup();
13041
- } catch (error) {
13042
- cleanup();
13043
- controller.enqueue({
13044
- type: "error",
13045
- error
13046
- });
13047
- }
13048
- },
13049
- cancel: () => {
13050
- cleanup();
13051
- }
13052
- });
13053
- return {
13054
- stream,
13055
- warnings: []
13056
- };
13057
- }
13058
- get tools() {
13059
- return getACPDynamicTool();
13060
- }
13061
- };
13062
-
13063
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/provider.js
13064
- var ACPProvider = class {
13065
- config;
13066
- model = null;
13067
- constructor(config) {
13068
- this.config = config;
13069
- }
13070
- /**
13071
- * Create a language model instance for a specific ACP agent
13072
- *
13073
- * @returns A LanguageModelV2 instance
13074
- */
13075
- languageModel(modelId, modeId) {
13076
- if (!this.model) {
13077
- this.model = new ACPLanguageModel(modelId, modeId, this.config);
13078
- }
13079
- if (modelId) {
13080
- this.model.modelId = modelId;
13081
- }
13082
- if (modeId) {
13083
- this.model.modeId = modeId;
13084
- }
13085
- return this.model;
13086
- }
13087
- /**
13088
- * Shorthand for creating a language model
13089
- */
13090
- call() {
13091
- return this.languageModel();
13092
- }
13093
- /**
13094
- * Provider tools - includes the agent dynamic tool
13095
- */
13096
- get tools() {
13097
- return this.model?.tools;
13098
- }
13099
- /**
13100
- * Returns the current session ID if one is active.
13101
- * Useful when `persistSession` is enabled and you need to reference the session later.
13102
- */
13103
- getSessionId() {
13104
- return this.model?.getSessionId() ?? null;
13105
- }
13106
- /**
13107
- * Initializes the session and returns session info (models, modes, meta).
13108
- * Call this before prompting to discover available options.
13109
- */
13110
- initSession(tools) {
13111
- if (!this.model) {
13112
- this.languageModel();
13113
- }
13114
- return this.model.initSession(tools);
13115
- }
13116
- /**
13117
- * Initializes the connection to the agent process without starting a session.
13118
- * Useful if you need to reduce the time to the first token.
13119
- */
13120
- connect() {
13121
- if (!this.model) {
13122
- this.languageModel();
13123
- }
13124
- return this.model.connectClient();
13125
- }
13126
- /**
13127
- * Sets the session mode (e.g., "ask", "plan").
13128
- */
13129
- setMode(modeId) {
13130
- if (!this.model) {
13131
- throw new Error("No model initialized. Call languageModel() first.");
13132
- }
13133
- return this.model.setMode(modeId);
13134
- }
13135
- /**
13136
- * Sets the session model.
13137
- */
13138
- setModel(modelId) {
13139
- if (!this.model) {
13140
- throw new Error("No model initialized. Call languageModel() first.");
13141
- }
13142
- return this.model.setModel(modelId);
13143
- }
13144
- /**
13145
- * Forces cleanup of the connection and session.
13146
- * Call this when you're done with the provider instance, especially when using `persistSession`.
13147
- */
13148
- cleanup() {
13149
- this.model?.forceCleanup();
13150
- }
13151
- };
13152
- function createACPProvider(config) {
13153
- return new ACPProvider(config);
13154
- }
13155
-
13156
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-executor.js
13157
- var AIACPExecutor = class extends BaseAIExecutor {
13158
- acpSettings;
13159
- clientTools;
13160
- provider = null;
13161
- model = null;
13162
- constructor(config) {
13163
- super(config);
13164
- this.acpSettings = config.acpSettings;
13165
- this.clientTools = config.clientTools ?? [];
13166
- }
13167
- initProvider() {
13168
- if (!this.model) {
13169
- this.provider = createACPProvider(this.acpSettings);
13170
- this.model = this.provider.languageModel();
13171
- }
13172
- return this.model;
13173
- }
13174
- getModel() {
13175
- if (!this.model) throw new Error("Model not initialized");
13176
- return this.model;
13177
- }
13178
- getExecutorType() {
13179
- return "acp";
13180
- }
13181
- getToolListDescription() {
13182
- if (this.clientTools.length === 0) {
13183
- return "Tools will be provided by AI SDK";
13184
- }
13185
- return this.clientTools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
13186
- }
13187
- buildTools() {
13188
- const aiTools = {};
13189
- for (const [name, detail] of this.clientTools) {
13190
- if (!detail.execute) continue;
13191
- aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
13192
- const result = await detail.execute(input);
13193
- return this.formatResult(result);
13194
- });
13195
- }
13196
- return aiTools;
13197
- }
13198
- formatResult(result) {
13199
- const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
13200
- return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
13201
- }
13202
- execute(args) {
13203
- this.initProvider();
13204
- return super.execute(args);
13205
- }
13206
- cleanup() {
13207
- if (this.provider && typeof this.provider.cleanup === "function") {
13208
- this.provider.cleanup();
13209
- }
13210
- this.model = null;
13211
- this.provider = null;
10924
+ this.model = null;
10925
+ this.provider = null;
13212
10926
  }
13213
10927
  };
13214
10928
 
@@ -13567,13 +11281,13 @@ var PluginManager = class {
13567
11281
  /**
13568
11282
  * Apply transformTool hooks to a tool during composition
13569
11283
  */
13570
- async applyTransformToolHooks(tool3, context2) {
11284
+ async applyTransformToolHooks(tool2, context2) {
13571
11285
  const transformPlugins = this.plugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, context2.mode));
13572
11286
  if (transformPlugins.length === 0) {
13573
- return tool3;
11287
+ return tool2;
13574
11288
  }
13575
11289
  const sortedPlugins = sortPluginsByOrder(transformPlugins);
13576
- let currentTool = tool3;
11290
+ let currentTool = tool2;
13577
11291
  for (const plugin of sortedPlugins) {
13578
11292
  if (plugin.transformTool) {
13579
11293
  try {
@@ -13821,12 +11535,12 @@ var ToolManager = class {
13821
11535
  * Get tool schema if it's hidden (for internal access)
13822
11536
  */
13823
11537
  getHiddenToolSchema(name) {
13824
- const tool3 = this.toolRegistry.get(name);
11538
+ const tool2 = this.toolRegistry.get(name);
13825
11539
  const config = this.toolConfigs.get(name);
13826
- if (tool3 && config?.visibility?.hidden && tool3.schema) {
11540
+ if (tool2 && config?.visibility?.hidden && tool2.schema) {
13827
11541
  return {
13828
- description: tool3.description,
13829
- schema: tool3.schema
11542
+ description: tool2.description,
11543
+ schema: tool2.schema
13830
11544
  };
13831
11545
  }
13832
11546
  return void 0;
@@ -13855,18 +11569,18 @@ var ToolManager = class {
13855
11569
  */
13856
11570
  getRegisteredToolsAsComposed() {
13857
11571
  const composedTools = {};
13858
- for (const [name, tool3] of this.toolRegistry.entries()) {
11572
+ for (const [name, tool2] of this.toolRegistry.entries()) {
13859
11573
  if (this.toolConfigs.get(name)?.visibility?.public === true) {
13860
11574
  continue;
13861
11575
  }
13862
11576
  composedTools[name] = {
13863
11577
  name,
13864
- description: tool3.description,
13865
- inputSchema: jsonSchema(tool3.schema || {
11578
+ description: tool2.description,
11579
+ inputSchema: jsonSchema(tool2.schema || {
13866
11580
  type: "object",
13867
11581
  properties: {}
13868
11582
  }),
13869
- execute: tool3.callback
11583
+ execute: tool2.callback
13870
11584
  };
13871
11585
  }
13872
11586
  return composedTools;
@@ -13936,18 +11650,18 @@ async function processToolsWithPlugins(server, _externalTools, mode) {
13936
11650
  function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server) {
13937
11651
  const depGroups = {};
13938
11652
  const toolManager = server.toolManager;
13939
- toolNameToDetailList.forEach(([toolName, tool3]) => {
11653
+ toolNameToDetailList.forEach(([toolName, tool2]) => {
13940
11654
  const resolvedName = toolManager.resolveToolName(toolName);
13941
11655
  if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
13942
11656
  return;
13943
11657
  }
13944
- if (!tool3) {
11658
+ if (!tool2) {
13945
11659
  const allToolNames = [
13946
11660
  ...toolNameToDetailList.map(([n]) => n)
13947
11661
  ];
13948
11662
  throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
13949
11663
  }
13950
- const baseSchema = tool3.inputSchema.jsonSchema ?? tool3.inputSchema ?? {
11664
+ const baseSchema = tool2.inputSchema.jsonSchema ?? tool2.inputSchema ?? {
13951
11665
  type: "object",
13952
11666
  properties: {},
13953
11667
  required: []
@@ -13958,7 +11672,7 @@ function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicTool
13958
11672
  const sanitizedKey = sanitizePropertyKey(toolName);
13959
11673
  depGroups[sanitizedKey] = {
13960
11674
  type: "object",
13961
- description: tool3.description,
11675
+ description: tool2.description,
13962
11676
  properties: updatedProperties,
13963
11677
  required: [
13964
11678
  ...baseRequired
@@ -14234,9 +11948,9 @@ var ComposableMCPServer = class extends Server {
14234
11948
  const requestedToolNames = /* @__PURE__ */ new Set();
14235
11949
  const availableToolNames = /* @__PURE__ */ new Set();
14236
11950
  const allPlaceholderUsages = [];
14237
- tagToResults.tool.forEach((tool3) => {
14238
- if (tool3.attribs.name) {
14239
- const originalName = tool3.attribs.name;
11951
+ tagToResults.tool.forEach((tool2) => {
11952
+ if (tool2.attribs.name) {
11953
+ const originalName = tool2.attribs.name;
14240
11954
  const toolName = sanitizePropertyKey(originalName);
14241
11955
  if (toolName.endsWith(`_${ALL_TOOLS_PLACEHOLDER2}`) || toolName === ALL_TOOLS_PLACEHOLDER2) {
14242
11956
  allPlaceholderUsages.push(originalName);
@@ -14262,24 +11976,24 @@ var ComposableMCPServer = class extends Server {
14262
11976
  }
14263
11977
  return true;
14264
11978
  }
14265
- return tagToResults.tool.find((tool3) => {
14266
- const selectAll = tool3.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool3.attribs.name === `${mcpName}`;
11979
+ return tagToResults.tool.find((tool2) => {
11980
+ const selectAll = tool2.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool2.attribs.name === `${mcpName}`;
14267
11981
  if (selectAll) {
14268
11982
  return true;
14269
11983
  }
14270
- return tool3.attribs.name === toolNameWithScope || tool3.attribs.name === toolId;
11984
+ return tool2.attribs.name === toolNameWithScope || tool2.attribs.name === toolId;
14271
11985
  });
14272
11986
  });
14273
- Object.entries(tools).forEach(([toolId, tool3]) => {
14274
- this.toolManager.registerTool(toolId, tool3.description || "", tool3.inputSchema, tool3.execute);
11987
+ Object.entries(tools).forEach(([toolId, tool2]) => {
11988
+ this.toolManager.registerTool(toolId, tool2.description || "", tool2.inputSchema, tool2.execute);
14275
11989
  });
14276
11990
  const registeredTools = this.toolManager.getRegisteredToolsAsComposed();
14277
11991
  const allTools = {
14278
11992
  ...tools
14279
11993
  };
14280
- Object.entries(registeredTools).forEach(([toolName, tool3]) => {
11994
+ Object.entries(registeredTools).forEach(([toolName, tool2]) => {
14281
11995
  if (!allTools[toolName]) {
14282
- allTools[toolName] = tool3;
11996
+ allTools[toolName] = tool2;
14283
11997
  }
14284
11998
  availableToolNames.add(toolName);
14285
11999
  });
@@ -14323,11 +12037,11 @@ var ComposableMCPServer = class extends Server {
14323
12037
  const hiddenToolNames = this.getHiddenToolNames();
14324
12038
  const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
14325
12039
  publicToolNames.forEach((toolId) => {
14326
- const tool3 = allTools[toolId];
14327
- if (!tool3) {
12040
+ const tool2 = allTools[toolId];
12041
+ if (!tool2) {
14328
12042
  throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(allTools).join(", ")}`);
14329
12043
  }
14330
- this.tool(toolId, tool3.description || "", jsonSchema(tool3.inputSchema), tool3.execute, {
12044
+ this.tool(toolId, tool2.description || "", jsonSchema(tool2.inputSchema), tool2.execute, {
14331
12045
  internal: false
14332
12046
  });
14333
12047
  });
@@ -14380,12 +12094,12 @@ var ComposableMCPServer = class extends Server {
14380
12094
  };
14381
12095
 
14382
12096
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
14383
- var import_node_process10 = __toESM(require("node:process"), 1);
14384
- var isSCF = () => Boolean(import_node_process10.default.env.SCF_RUNTIME || import_node_process10.default.env.PROD_SCF);
12097
+ var import_node_process9 = __toESM(require("node:process"), 1);
12098
+ var isSCF = () => Boolean(import_node_process9.default.env.SCF_RUNTIME || import_node_process9.default.env.PROD_SCF);
14385
12099
  if (isSCF()) {
14386
12100
  console.log({
14387
12101
  isSCF: isSCF(),
14388
- SCF_RUNTIME: import_node_process10.default.env.SCF_RUNTIME
12102
+ SCF_RUNTIME: import_node_process9.default.env.SCF_RUNTIME
14389
12103
  });
14390
12104
  }
14391
12105
 
@@ -14433,15 +12147,18 @@ function createSearchPlugin(options = {}) {
14433
12147
  const allowedSearchDir = options.allowedDir || (0, import_node_os2.tmpdir)();
14434
12148
  const timeoutMs = options.timeoutMs || 3e4;
14435
12149
  const global2 = options.global ?? true;
12150
+ const agentName = options.agentName;
12151
+ const toolName = agentName ? `${agentName}__search-tool-result` : "search-tool-result";
14436
12152
  const activeTimeouts = /* @__PURE__ */ new Set();
14437
12153
  return {
14438
12154
  name: "plugin-search",
14439
12155
  version: "1.0.0",
14440
12156
  configureServer: (server) => {
14441
- const defaultDescription = `Search for text patterns in files and directories. Use this to find specific content, code, or information within files. Provide a simple literal string or a regular expression. If your pattern is a regex, ensure it's valid; otherwise use quotes or escape special characters to treat it as a literal string.
12157
+ const defaultDescription = agentName ? `Search for text patterns in files for the "${agentName}" agent. Use this to find specific content within large tool results. Provide a simple literal string or a regular expression.
12158
+ Only search within the allowed directory: ${allowedSearchDir}` : `Search for text patterns in files and directories. Use this to find specific content, code, or information within files. Provide a simple literal string or a regular expression. If your pattern is a regex, ensure it's valid; otherwise use quotes or escape special characters to treat it as a literal string.
14442
12159
  Only search within the allowed directory: ${allowedSearchDir}`;
14443
12160
  const toolDescription = options.toolDescription || defaultDescription;
14444
- server.tool("search-tool-result", toolDescription, jsonSchema({
12161
+ server.tool(toolName, toolDescription, jsonSchema({
14445
12162
  type: "object",
14446
12163
  properties: {
14447
12164
  pattern: {
@@ -14656,28 +12373,34 @@ function createLargeResultPlugin(options = {}) {
14656
12373
  const maxSize = options.maxSize || 8e3;
14657
12374
  const previewSize = options.previewSize || 4e3;
14658
12375
  let tempDir = options.tempDir || null;
14659
- const configuredServers = /* @__PURE__ */ new Map();
12376
+ let serverRef = null;
12377
+ let agentName = null;
14660
12378
  const defaultSearchDescription = `Search within large tool result files that were saved due to size limits. Use when: a tool result was saved to file because it exceeded the context limit. Do NOT use this tool before calling the actual tool first. Provide specific keywords or patterns related to the content you're looking for.`;
14661
- const searchConfig = {
14662
- maxResults: options.search?.maxResults || 15,
14663
- maxOutputSize: options.search?.maxOutputSize || 4e3,
14664
- toolDescription: options.search?.toolDescription || defaultSearchDescription,
14665
- global: true
14666
- };
14667
12379
  return {
14668
12380
  name: "plugin-large-result-handler",
14669
12381
  version: "1.0.0",
14670
12382
  dependencies: [],
14671
- configureServer: async (server) => {
14672
- if (!configuredServers.has(server)) {
12383
+ configureServer: (server) => {
12384
+ serverRef = server;
12385
+ },
12386
+ composeStart: async (context2) => {
12387
+ agentName = context2.serverName;
12388
+ if (serverRef) {
12389
+ const searchConfig = {
12390
+ maxResults: options.search?.maxResults || 15,
12391
+ maxOutputSize: options.search?.maxOutputSize || 4e3,
12392
+ toolDescription: options.search?.toolDescription || defaultSearchDescription,
12393
+ global: true,
12394
+ agentName
12395
+ };
14673
12396
  const searchPlugin = createSearchPlugin(searchConfig);
14674
- await server.addPlugin(searchPlugin);
14675
- configuredServers.set(server, true);
12397
+ await serverRef.addPlugin(searchPlugin);
14676
12398
  }
14677
12399
  },
14678
- transformTool: (tool3, context2) => {
14679
- const originalExecute = tool3.execute;
14680
- tool3.execute = async (args) => {
12400
+ transformTool: (tool2, context2) => {
12401
+ const originalExecute = tool2.execute;
12402
+ const searchToolName = agentName ? `${agentName}__search-tool-result` : "search-tool-result";
12403
+ tool2.execute = async (args) => {
14681
12404
  try {
14682
12405
  const result = await originalExecute(args);
14683
12406
  const resultText = JSON.stringify(result);
@@ -14708,7 +12431,7 @@ ${preview}
14708
12431
  \`\`\`
14709
12432
 
14710
12433
  **To read/understand the full content:**
14711
- - Use the \`search-tool-result\` tool with pattern: \`search-tool-result {"pattern": "your-search-term"}\`
12434
+ - Use the \`${searchToolName}\` tool with pattern: \`${searchToolName} {"pattern": "your-search-term"}\`
14712
12435
  - Search supports regex patterns for advanced queries`
14713
12436
  }
14714
12437
  ]
@@ -14719,10 +12442,11 @@ ${preview}
14719
12442
  throw error;
14720
12443
  }
14721
12444
  };
14722
- return tool3;
12445
+ return tool2;
14723
12446
  },
14724
12447
  dispose: () => {
14725
- configuredServers.clear();
12448
+ serverRef = null;
12449
+ agentName = null;
14726
12450
  tempDir = null;
14727
12451
  }
14728
12452
  };