'use strict';

var chunkPWHXCQ22_cjs = require('./chunk-PWHXCQ22.cjs');
var chunk2BIE3CHY_cjs = require('./chunk-2BIE3CHY.cjs');
var chunkK52BGIHQ_cjs = require('./chunk-K52BGIHQ.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var a2a = require('@mastra/core/a2a');
var z = require('zod');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var z__default = /*#__PURE__*/_interopDefault(z);

// src/server/handlers/a2a.ts
var a2a_exports = {};
chunkO7I5CWRX_cjs.__export(a2a_exports, {
  AGENT_EXECUTION_ROUTE: () => AGENT_EXECUTION_ROUTE,
  GET_AGENT_CARD_ROUTE: () => GET_AGENT_CARD_ROUTE,
  getAgentCardByIdHandler: () => getAgentCardByIdHandler,
  getAgentExecutionHandler: () => getAgentExecutionHandler,
  handleMessageSend: () => handleMessageSend,
  handleMessageStream: () => handleMessageStream,
  handleTaskCancel: () => handleTaskCancel,
  handleTaskGet: () => handleTaskGet
});
function normalizeError(error, reqId, taskId, logger) {
  let a2aError;
  if (error instanceof a2a.MastraA2AError) {
    a2aError = error;
  } else if (error instanceof Error) {
    a2aError = a2a.MastraA2AError.internalError(error.message, { stack: error.stack });
  } else {
    a2aError = a2a.MastraA2AError.internalError("An unknown error occurred.", error);
  }
  if (taskId && !a2aError.taskId) {
    a2aError.taskId = taskId;
  }
  logger?.error(`Error processing request (Task: ${a2aError.taskId ?? "N/A"}, ReqID: ${reqId ?? "N/A"}):`, a2aError);
  return createErrorResponse(reqId, a2aError.toJSONRPCError());
}
function createErrorResponse(id, error) {
  return {
    jsonrpc: "2.0",
    id,
    // Can be null if request ID was invalid/missing
    error
  };
}
function createSuccessResponse(id, result) {
  if (!id) {
    throw a2a.MastraA2AError.internalError("Cannot create success response for null ID.");
  }
  return {
    jsonrpc: "2.0",
    id,
    result
  };
}
function convertToCoreMessage(message) {
  return {
    role: message.role === "user" ? "user" : "assistant",
    content: message.parts.map((msg) => convertToCoreMessagePart(msg))
  };
}
function convertToCoreMessagePart(part) {
  switch (part.kind) {
    case "text":
      return {
        type: "text",
        text: part.text
      };
    case "file":
      return {
        type: "file",
        data: "uri" in part.file ? new URL(part.file.uri) : part.file.bytes,
        mimeType: part.file.mimeType
      };
    case "data":
      throw new Error("Data parts are not supported in core messages");
  }
}

// src/server/a2a/tasks.ts
function isTaskStatusUpdate(update) {
  return "state" in update && !("parts" in update);
}
function isArtifactUpdate(update) {
  return "kind" in update && update.kind === "artifact-update";
}
function applyUpdateToTask(current, update) {
  let newTask = structuredClone(current);
  if (isTaskStatusUpdate(update)) {
    newTask.status = {
      ...newTask.status,
      // Keep existing properties if not overwritten
      ...update,
      // Apply updates
      timestamp: (/* @__PURE__ */ new Date()).toISOString()
    };
  } else if (isArtifactUpdate(update)) {
    if (!newTask.artifacts) {
      newTask.artifacts = [];
    } else {
      newTask.artifacts = [...newTask.artifacts];
    }
    const artifact = update.artifact;
    const existingIndex = newTask.artifacts.findIndex((a) => a.name === artifact.name);
    const existingArtifact = newTask.artifacts[existingIndex];
    if (existingArtifact) {
      if (update.append) {
        const appendedArtifact = JSON.parse(JSON.stringify(existingArtifact));
        appendedArtifact.parts.push(...artifact.parts);
        if (artifact.metadata) {
          appendedArtifact.metadata = {
            ...appendedArtifact.metadata || {},
            ...artifact.metadata
          };
        }
        if (artifact.description) appendedArtifact.description = artifact.description;
        newTask.artifacts[existingIndex] = appendedArtifact;
      } else {
        newTask.artifacts[existingIndex] = { ...artifact };
      }
    } else {
      newTask.artifacts.push({ ...artifact });
    }
  }
  return newTask;
}
async function loadOrCreateTask({
  agentId,
  taskId,
  taskStore,
  message,
  contextId,
  metadata,
  logger
}) {
  const data = await taskStore.load({ agentId, taskId });
  if (!data) {
    const initialTask = {
      id: taskId,
      contextId: contextId || crypto.randomUUID(),
      status: {
        state: "submitted",
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        message: void 0
      },
      artifacts: [],
      history: [message],
      metadata,
      kind: "task"
    };
    logger?.info(`[Task ${taskId}] Created new task.`);
    await taskStore.save({ agentId, data: initialTask });
    return initialTask;
  }
  logger?.info(`[Task ${taskId}] Loaded existing task.`);
  let updatedData = data;
  updatedData.history = [...data.history || [], message];
  const { status } = data;
  const finalStates = ["completed", "failed", "canceled"];
  if (finalStates.includes(status.state)) {
    logger?.warn(`[Task ${taskId}] Received message for task in final state ${status.state}. Restarting.`);
    updatedData = applyUpdateToTask(updatedData, {
      state: "submitted",
      message: void 0
    });
  } else if (status.state === "input-required") {
    logger?.info(`[Task ${taskId}] Changing state from 'input-required' to 'working'.`);
    updatedData = applyUpdateToTask(updatedData, { state: "working" });
  } else if (status.state === "working") {
    logger?.warn(`[Task ${taskId}] Received message while already 'working'. Proceeding.`);
  }
  await taskStore.save({ agentId, data: updatedData });
  return updatedData;
}
function createTaskContext({
  task,
  userMessage,
  history,
  activeCancellations
}) {
  return {
    task: structuredClone(task),
    userMessage,
    history: structuredClone(history),
    isCancelled: () => activeCancellations.has(task.id)
  };
}
var a2aAgentIdPathParams = z__default.default.object({
  agentId: z__default.default.string().describe("Unique identifier for the agent")
});
a2aAgentIdPathParams.extend({
  taskId: z__default.default.string().describe("Unique identifier for the task")
});
var pushNotificationAuthenticationInfoSchema = z__default.default.object({
  schemes: z__default.default.array(z__default.default.string()).describe("Supported authentication schemes - e.g. Basic, Bearer"),
  credentials: z__default.default.string().optional().describe("Optional credentials")
});
var pushNotificationConfigSchema = z__default.default.object({
  url: z__default.default.string().describe("URL for sending the push notifications"),
  id: z__default.default.string().optional().describe("Push Notification ID - created by server to support multiple callbacks"),
  token: z__default.default.string().optional().describe("Token unique to this task/session"),
  authentication: pushNotificationAuthenticationInfoSchema.optional()
});
var messageSendConfigurationSchema = z__default.default.object({
  acceptedOutputModes: z__default.default.array(z__default.default.string()).describe("Accepted output modalities by the client"),
  blocking: z__default.default.boolean().optional().describe("If the server should treat the client as a blocking request"),
  historyLength: z__default.default.number().optional().describe("Number of recent messages to be retrieved"),
  pushNotificationConfig: pushNotificationConfigSchema.optional()
});
var textPartSchema = z__default.default.object({
  kind: z__default.default.literal("text").describe("Part type - text for TextParts"),
  text: z__default.default.string().describe("Text content"),
  metadata: z__default.default.record(z__default.default.unknown()).optional().describe("Optional metadata associated with the part")
});
var fileWithBytesSchema = z__default.default.object({
  bytes: z__default.default.string().describe("base64 encoded content of the file"),
  mimeType: z__default.default.string().optional().describe("Optional mimeType for the file"),
  name: z__default.default.string().optional().describe("Optional name for the file")
});
var fileWithUriSchema = z__default.default.object({
  uri: z__default.default.string().describe("URL for the File content"),
  mimeType: z__default.default.string().optional().describe("Optional mimeType for the file"),
  name: z__default.default.string().optional().describe("Optional name for the file")
});
var filePartSchema = z__default.default.object({
  kind: z__default.default.literal("file").describe("Part type - file for FileParts"),
  file: z__default.default.union([fileWithBytesSchema, fileWithUriSchema]).describe("File content either as url or bytes"),
  metadata: z__default.default.record(z__default.default.unknown()).optional().describe("Optional metadata associated with the part")
});
var dataPartSchema = z__default.default.object({
  kind: z__default.default.literal("data").describe("Part type - data for DataParts"),
  data: z__default.default.record(z__default.default.unknown()).describe("Structured data content"),
  metadata: z__default.default.record(z__default.default.unknown()).optional().describe("Optional metadata associated with the part")
});
var partSchema = z__default.default.union([textPartSchema, filePartSchema, dataPartSchema]);
var messageSchema = z__default.default.object({
  kind: z__default.default.literal("message").describe("Event type"),
  messageId: z__default.default.string().describe("Identifier created by the message creator"),
  role: z__default.default.enum(["user", "agent"]).describe("Message sender's role"),
  parts: z__default.default.array(partSchema).describe("Message content"),
  contextId: z__default.default.string().optional().describe("The context the message is associated with"),
  taskId: z__default.default.string().optional().describe("Identifier of task the message is related to"),
  referenceTaskIds: z__default.default.array(z__default.default.string()).optional().describe("List of tasks referenced as context by this message"),
  extensions: z__default.default.array(z__default.default.string()).optional().describe("The URIs of extensions that are present or contributed to this Message"),
  metadata: z__default.default.record(z__default.default.unknown()).optional().describe("Extension metadata")
});
var messageSendParamsSchema = z__default.default.object({
  message: messageSchema,
  configuration: messageSendConfigurationSchema.optional(),
  metadata: z__default.default.record(z__default.default.unknown()).optional().describe("Extension metadata")
});
var taskQueryParamsSchema = z__default.default.object({
  id: z__default.default.string().describe("Task id"),
  historyLength: z__default.default.number().optional().describe("Number of recent messages to be retrieved"),
  metadata: z__default.default.record(z__default.default.unknown()).optional()
});
var taskIdParamsSchema = z__default.default.object({
  id: z__default.default.string().describe("Task id"),
  metadata: z__default.default.record(z__default.default.unknown()).optional()
});
z__default.default.object({
  message: messageSchema,
  metadata: z__default.default.record(z__default.default.any()).optional()
});
z__default.default.object({
  id: z__default.default.string()
});
var agentExecutionParamsSchema = z__default.default.union([messageSendParamsSchema, taskQueryParamsSchema, taskIdParamsSchema]);
var agentExecutionBodySchema = z__default.default.object({
  jsonrpc: z__default.default.literal("2.0"),
  id: z__default.default.union([z__default.default.string(), z__default.default.number()]),
  method: z__default.default.enum(["message/send", "message/stream", "tasks/get", "tasks/cancel"]),
  params: agentExecutionParamsSchema
});
var agentCardResponseSchema = z__default.default.object({
  name: z__default.default.string(),
  description: z__default.default.string(),
  url: z__default.default.string(),
  provider: z__default.default.object({
    organization: z__default.default.string(),
    url: z__default.default.string()
  }).optional(),
  version: z__default.default.string(),
  capabilities: z__default.default.object({
    streaming: z__default.default.boolean().optional(),
    pushNotifications: z__default.default.boolean().optional(),
    stateTransitionHistory: z__default.default.boolean().optional()
  }),
  defaultInputModes: z__default.default.array(z__default.default.string()),
  defaultOutputModes: z__default.default.array(z__default.default.string()),
  skills: z__default.default.array(
    z__default.default.object({
      id: z__default.default.string(),
      name: z__default.default.string(),
      description: z__default.default.string(),
      tags: z__default.default.array(z__default.default.string()).optional()
    })
  )
});
z__default.default.unknown();
var agentExecutionResponseSchema = z__default.default.unknown();

// src/server/handlers/a2a.ts
var messageSendParamsSchema2 = z.z.object({
  message: z.z.object({
    role: z.z.enum(["user", "agent"]),
    parts: z.z.array(
      z.z.object({
        kind: z.z.enum(["text"]),
        text: z.z.string()
      })
    ),
    kind: z.z.literal("message"),
    messageId: z.z.string(),
    contextId: z.z.string().optional(),
    taskId: z.z.string().optional(),
    referenceTaskIds: z.z.array(z.z.string()).optional(),
    extensions: z.z.array(z.z.string()).optional(),
    metadata: z.z.record(z.z.any()).optional()
  })
});
async function getAgentCardByIdHandler({
  mastra,
  agentId,
  executionUrl = `/a2a/${agentId}`,
  provider = {
    organization: "Mastra",
    url: "https://mastra.ai"
  },
  version = "1.0",
  requestContext
}) {
  const agent = await chunkPWHXCQ22_cjs.getAgentFromSystem({ mastra, agentId });
  const [instructions, tools] = await Promise.all([agent.getInstructions({ requestContext }), agent.listTools({ requestContext })]);
  const agentCard = {
    name: agent.id || agentId,
    description: chunk2BIE3CHY_cjs.convertInstructionsToString(instructions),
    url: executionUrl,
    provider,
    version,
    capabilities: {
      streaming: true,
      // All agents support streaming
      pushNotifications: false,
      stateTransitionHistory: false
    },
    defaultInputModes: ["text"],
    defaultOutputModes: ["text"],
    // Convert agent tools to skills format for A2A protocol
    skills: Object.entries(tools).map(([toolId, tool]) => ({
      id: toolId,
      name: toolId,
      description: tool.description || `Tool: ${toolId}`,
      // Optional fields
      tags: ["tool"]
    }))
  };
  return agentCard;
}
function validateMessageSendParams(params) {
  try {
    messageSendParamsSchema2.parse(params);
  } catch (error) {
    if (error instanceof z.z.ZodError) {
      throw a2a.MastraA2AError.invalidParams(error.errors[0].message);
    }
    throw error;
  }
}
async function handleMessageSend({
  requestId,
  params,
  taskStore,
  agent,
  agentId,
  logger,
  requestContext
}) {
  validateMessageSendParams(params);
  const { message, metadata } = params;
  const { contextId } = message;
  const taskId = message.taskId || crypto.randomUUID();
  let currentData = await loadOrCreateTask({
    taskId,
    taskStore,
    agentId,
    message,
    contextId,
    metadata
  });
  createTaskContext({
    task: currentData,
    userMessage: message,
    history: currentData.history || [],
    activeCancellations: taskStore.activeCancellations
  });
  try {
    const resourceId = metadata?.resourceId ?? message.metadata?.resourceId ?? agentId;
    const result = await agent.generate([convertToCoreMessage(message)], {
      runId: taskId,
      requestContext,
      ...contextId ? { threadId: contextId, resourceId } : {}
    });
    currentData = applyUpdateToTask(currentData, {
      state: "completed",
      message: {
        messageId: crypto.randomUUID(),
        role: "agent",
        parts: [
          {
            kind: "text",
            text: result.text
          }
        ],
        kind: "message"
      }
    });
    currentData.metadata = {
      ...currentData.metadata,
      execution: {
        toolCalls: result.toolCalls,
        toolResults: result.toolResults,
        usage: result.usage,
        finishReason: result.finishReason
      }
    };
    await taskStore.save({ agentId, data: currentData });
  } catch (handlerError) {
    const failureStatusUpdate = {
      state: "failed",
      message: {
        messageId: crypto.randomUUID(),
        role: "agent",
        parts: [
          {
            kind: "text",
            text: `Handler failed: ${handlerError instanceof Error ? handlerError.message : String(handlerError)}`
          }
        ],
        kind: "message"
      }
    };
    currentData = applyUpdateToTask(currentData, failureStatusUpdate);
    try {
      await taskStore.save({ agentId, data: currentData });
    } catch (saveError) {
      logger?.error(`Failed to save task ${currentData.id} after handler error:`, saveError?.message);
    }
    return normalizeError(handlerError, requestId, currentData.id, logger);
  }
  return createSuccessResponse(requestId, currentData);
}
async function handleTaskGet({
  requestId,
  taskStore,
  agentId,
  taskId
}) {
  const task = await taskStore.load({ agentId, taskId });
  if (!task) {
    throw a2a.MastraA2AError.taskNotFound(taskId);
  }
  return createSuccessResponse(requestId, task);
}
async function* handleMessageStream({
  requestId,
  params,
  taskStore,
  agent,
  agentId,
  logger,
  requestContext
}) {
  yield createSuccessResponse(requestId, {
    state: "working",
    message: {
      messageId: crypto.randomUUID(),
      kind: "message",
      role: "agent",
      parts: [{ kind: "text", text: "Generating response..." }]
    }
  });
  let result;
  try {
    result = await handleMessageSend({
      requestId,
      params,
      taskStore,
      agent,
      agentId,
      requestContext,
      logger
    });
  } catch (err) {
    if (!(err instanceof a2a.MastraA2AError)) {
      throw err;
    }
    result = createErrorResponse(requestId, err.toJSONRPCError());
  }
  yield result;
}
async function handleTaskCancel({
  requestId,
  taskStore,
  agentId,
  taskId,
  logger
}) {
  let data = await taskStore.load({
    agentId,
    taskId
  });
  if (!data) {
    throw a2a.MastraA2AError.taskNotFound(taskId);
  }
  const finalStates = ["completed", "failed", "canceled"];
  if (finalStates.includes(data.status.state)) {
    logger?.info(`Task ${taskId} already in final state ${data.status.state}, cannot cancel.`);
    return createSuccessResponse(requestId, data);
  }
  taskStore.activeCancellations.add(taskId);
  const cancelUpdate = {
    state: "canceled",
    message: {
      role: "agent",
      parts: [{ kind: "text", text: "Task cancelled by request." }],
      kind: "message",
      messageId: crypto.randomUUID()
    }
  };
  data = applyUpdateToTask(data, cancelUpdate);
  await taskStore.save({ agentId, data });
  taskStore.activeCancellations.delete(taskId);
  return createSuccessResponse(requestId, data);
}
async function getAgentExecutionHandler({
  requestId,
  mastra,
  agentId,
  requestContext,
  method,
  params,
  taskStore,
  logger
}) {
  const agent = await chunkPWHXCQ22_cjs.getAgentFromSystem({ mastra, agentId });
  let taskId;
  try {
    taskId = "id" in params ? params.id : params.message?.taskId || "No task ID provided";
    switch (method) {
      case "message/send": {
        const result2 = await handleMessageSend({
          requestId,
          params,
          taskStore,
          agent,
          agentId,
          requestContext
        });
        return result2;
      }
      case "message/stream":
        const result = await handleMessageStream({
          requestId,
          taskStore,
          params,
          agent,
          agentId,
          requestContext
        });
        return result;
      case "tasks/get": {
        const result2 = await handleTaskGet({
          requestId,
          taskStore,
          agentId,
          taskId
        });
        return result2;
      }
      case "tasks/cancel": {
        const result2 = await handleTaskCancel({
          requestId,
          taskStore,
          agentId,
          taskId
        });
        return result2;
      }
      default:
        throw a2a.MastraA2AError.methodNotFound(method);
    }
  } catch (error) {
    if (error instanceof a2a.MastraA2AError && taskId && !error.taskId) {
      error.taskId = taskId;
    }
    return normalizeError(error, requestId, taskId, logger);
  }
}
var GET_AGENT_CARD_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "GET",
  path: "/.well-known/:agentId/agent-card.json",
  responseType: "json",
  pathParamSchema: a2aAgentIdPathParams,
  responseSchema: agentCardResponseSchema,
  summary: "Get agent card",
  description: "Returns the agent card information for A2A protocol discovery",
  tags: ["Agent-to-Agent"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, requestContext }) => {
    const executionUrl = `/a2a/${agentId}`;
    const provider = {
      organization: "Mastra",
      url: "https://mastra.ai"
    };
    const version = "1.0";
    const agent = await chunkPWHXCQ22_cjs.getAgentFromSystem({ mastra, agentId });
    const [instructions, tools] = await Promise.all([agent.getInstructions({ requestContext }), agent.listTools({ requestContext })]);
    const agentCard = {
      name: agent.id || agentId,
      description: chunk2BIE3CHY_cjs.convertInstructionsToString(instructions),
      url: executionUrl,
      provider,
      version,
      capabilities: {
        streaming: true,
        pushNotifications: false,
        stateTransitionHistory: false
      },
      defaultInputModes: ["text"],
      defaultOutputModes: ["text"],
      skills: Object.entries(tools).map(([toolId, tool]) => ({
        id: toolId,
        name: toolId,
        description: tool.description || `Tool: ${toolId}`,
        tags: ["tool"]
      }))
    };
    return agentCard;
  }
});
var AGENT_EXECUTION_ROUTE = chunkK52BGIHQ_cjs.createRoute({
  method: "POST",
  path: "/a2a/:agentId",
  responseType: "json",
  pathParamSchema: a2aAgentIdPathParams,
  bodySchema: agentExecutionBodySchema,
  responseSchema: agentExecutionResponseSchema,
  summary: "Execute agent",
  description: "Executes an agent action via JSON-RPC 2.0 over A2A protocol",
  tags: ["Agent-to-Agent"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, requestContext, taskStore, ...bodyParams }) => {
    const { id: requestId, method, params } = bodyParams;
    return await getAgentExecutionHandler({
      requestId: String(requestId),
      mastra,
      agentId,
      requestContext,
      method,
      params,
      taskStore
    });
  }
});

exports.AGENT_EXECUTION_ROUTE = AGENT_EXECUTION_ROUTE;
exports.GET_AGENT_CARD_ROUTE = GET_AGENT_CARD_ROUTE;
exports.a2a_exports = a2a_exports;
exports.getAgentCardByIdHandler = getAgentCardByIdHandler;
exports.getAgentExecutionHandler = getAgentExecutionHandler;
exports.handleMessageSend = handleMessageSend;
exports.handleMessageStream = handleMessageStream;
exports.handleTaskCancel = handleTaskCancel;
exports.handleTaskGet = handleTaskGet;
//# sourceMappingURL=chunk-EB24NOO6.cjs.map
//# sourceMappingURL=chunk-EB24NOO6.cjs.map