'use strict';

var chunk42WZN6MM_cjs = require('./chunk-42WZN6MM.cjs');
var chunkF3HP5HM6_cjs = require('./chunk-F3HP5HM6.cjs');
var chunkKIDHIRVO_cjs = require('./chunk-KIDHIRVO.cjs');
var chunkEFJCOPJ3_cjs = require('./chunk-EFJCOPJ3.cjs');
var chunk42M6Y2OD_cjs = require('./chunk-42M6Y2OD.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var crypto = require('crypto');

// src/server/handlers/responses.ts
var responses_exports = {};
chunkO7I5CWRX_cjs.__export(responses_exports, {
  CREATE_RESPONSE_ROUTE: () => CREATE_RESPONSE_ROUTE,
  DELETE_RESPONSE_ROUTE: () => DELETE_RESPONSE_ROUTE,
  GET_RESPONSE_ROUTE: () => GET_RESPONSE_ROUTE
});
var JSON_OBJECT_RESPONSE_SCHEMA = {
  type: "object",
  additionalProperties: true
};
function jsonResponse(data, status = 200) {
  return new Response(JSON.stringify(data), {
    status,
    headers: {
      "Content-Type": "application/json"
    }
  });
}
function createStructuredOutput(text) {
  if (!text) {
    return void 0;
  }
  switch (text.format.type) {
    case "json_object":
      return {
        schema: JSON_OBJECT_RESPONSE_SCHEMA,
        jsonPromptInjection: true
      };
    case "json_schema":
      return {
        schema: text.format.schema
      };
    default:
      return void 0;
  }
}
function getStreamedMessageOutputItem(response, responseId) {
  return response.output.find(
    (item) => item.type === "message" && item.id === responseId
  ) ?? null;
}
async function resolveThreadExecutionContext({
  agent,
  store,
  conversationId,
  previousResponseTurnRecord,
  requestContext
}) {
  if (conversationId && previousResponseTurnRecord && previousResponseTurnRecord.thread.id !== conversationId) {
    throw new chunk64ITUOXI_cjs.HTTPException(400, {
      message: "conversation_id and previous_response_id must reference the same conversation thread when both are provided"
    });
  }
  if (previousResponseTurnRecord) {
    return {
      threadId: previousResponseTurnRecord.thread.id,
      resourceId: previousResponseTurnRecord.thread.resourceId
    };
  }
  const effectiveThreadId = chunk42M6Y2OD_cjs.getEffectiveThreadId(requestContext, void 0);
  const effectiveResourceId = chunk42M6Y2OD_cjs.getEffectiveResourceId(requestContext, void 0);
  if (!store && !conversationId && !effectiveThreadId) {
    return null;
  }
  const memory = await agent.getMemory({ requestContext });
  if (!memory) {
    if (conversationId) {
      throw new chunk64ITUOXI_cjs.HTTPException(400, {
        message: "conversation_id requires the target agent to have memory configured"
      });
    }
    return null;
  }
  if (conversationId) {
    const existingThread2 = await memory.getThreadById({ threadId: conversationId });
    if (!existingThread2) {
      throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Conversation ${conversationId} was not found` });
    }
    await chunk42M6Y2OD_cjs.enforceThreadAccess({
      mastra: agent.getMastraInstance(),
      requestContext,
      threadId: conversationId,
      thread: existingThread2,
      effectiveResourceId
    });
    return {
      threadId: existingThread2.id,
      resourceId: effectiveResourceId ?? existingThread2.resourceId
    };
  }
  if (!effectiveThreadId) {
    if (!store) {
      return null;
    }
    const threadId2 = crypto.randomUUID();
    const createdThread2 = await memory.createThread({
      threadId: threadId2,
      resourceId: effectiveResourceId ?? threadId2
    });
    return {
      threadId: createdThread2.id,
      resourceId: createdThread2.resourceId
    };
  }
  const threadId = effectiveThreadId;
  const existingThread = await memory.getThreadById({ threadId });
  if (existingThread) {
    await chunk42M6Y2OD_cjs.enforceThreadAccess({
      mastra: agent.getMastraInstance(),
      requestContext,
      threadId,
      thread: existingThread,
      effectiveResourceId
    });
    return {
      threadId: existingThread.id,
      resourceId: effectiveResourceId ?? existingThread.resourceId
    };
  }
  if (!store) {
    return null;
  }
  const resourceId = effectiveResourceId ?? threadId;
  const createdThread = await memory.createThread({
    threadId,
    resourceId
  });
  return {
    threadId: createdThread.id,
    resourceId: createdThread.resourceId
  };
}
function createExecutionMemory(threadContext) {
  if (!threadContext) {
    return void 0;
  }
  return {
    memory: {
      thread: threadContext.threadId,
      resource: threadContext.resourceId
    }
  };
}
async function resolveResponseAgent({
  mastra,
  agentId
}) {
  if (!agentId) {
    throw new chunk64ITUOXI_cjs.HTTPException(400, {
      message: "Responses requests require an agent_id"
    });
  }
  if (!mastra) {
    throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Mastra instance is required for agent-backed responses" });
  }
  return chunkEFJCOPJ3_cjs.getAgentFromSystem({ mastra, agentId });
}
async function resolveAgentMemoryStore({
  agent,
  requestContext,
  errorMessage
}) {
  const agentMemoryStore = await chunkKIDHIRVO_cjs.getAgentMemoryStore({ agent, requestContext });
  if (!agentMemoryStore) {
    throw new chunk64ITUOXI_cjs.HTTPException(400, { message: errorMessage });
  }
  return agentMemoryStore;
}
async function executeGenerate({
  agent,
  resolvedModel,
  modelOverride,
  instructions,
  text,
  providerOptions,
  input,
  requestContext,
  abortSignal,
  threadContext
}) {
  const executionMemory = createExecutionMemory(threadContext);
  const structuredOutput = createStructuredOutput(text);
  const modelOption = modelOverride ? { model: modelOverride } : {};
  const commonOptions = {
    instructions,
    requestContext,
    abortSignal,
    ...modelOption,
    structuredOutput,
    providerOptions,
    ...executionMemory ?? {}
  };
  if (resolvedModel.specificationVersion === "v1") {
    if (threadContext) {
      return await agent.generateLegacy(input, {
        instructions,
        requestContext,
        abortSignal,
        ...modelOption,
        output: structuredOutput?.schema,
        providerOptions,
        resourceId: threadContext.resourceId,
        threadId: threadContext.threadId
      });
    }
    return await agent.generateLegacy(input, {
      instructions,
      requestContext,
      abortSignal,
      ...modelOption,
      output: structuredOutput?.schema,
      providerOptions
    });
  }
  return await agent.generate(input, commonOptions);
}
async function executeStream({
  agent,
  resolvedModel,
  modelOverride,
  instructions,
  text,
  providerOptions,
  input,
  requestContext,
  abortSignal,
  threadContext
}) {
  const executionMemory = createExecutionMemory(threadContext);
  const structuredOutput = createStructuredOutput(text);
  const modelOption = modelOverride ? { model: modelOverride } : {};
  const commonOptions = {
    instructions,
    requestContext,
    abortSignal,
    ...modelOption,
    structuredOutput,
    providerOptions,
    ...executionMemory ?? {}
  };
  if (resolvedModel.specificationVersion === "v1") {
    if (threadContext) {
      return await agent.streamLegacy(input, {
        instructions,
        requestContext,
        abortSignal,
        ...modelOption,
        output: structuredOutput?.schema,
        providerOptions,
        resourceId: threadContext.resourceId,
        threadId: threadContext.threadId
      });
    }
    return await agent.streamLegacy(input, {
      instructions,
      requestContext,
      abortSignal,
      ...modelOption,
      output: structuredOutput?.schema,
      providerOptions
    });
  }
  return await agent.stream(input, commonOptions);
}
async function resolveUsage(result) {
  return await (result.totalUsage ?? result.usage ?? null);
}
async function resolveProviderMetadata(result) {
  return await (result.providerMetadata ?? void 0);
}
async function resolveFinishReason(result) {
  return await result.finishReason ?? void 0;
}
async function resolveText(result) {
  return await result.text ?? "";
}
async function resolveCompletedResponseState(result, fallbackText) {
  const usage = await resolveUsage(result);
  return {
    completedAt: Math.floor(Date.now() / 1e3),
    status: chunkF3HP5HM6_cjs.toResponseStatus(await resolveFinishReason(result)),
    text: await resolveText(result) || fallbackText,
    usage,
    usageDetails: chunkF3HP5HM6_cjs.toResponseUsage(usage),
    providerOptions: await resolveProviderMetadata(result)
  };
}
async function storeCompletedResponse({
  agentMemoryStore,
  didStore,
  threadContext,
  responseId,
  metadata,
  completedState,
  messages,
  outputItems
}) {
  if (!didStore || !threadContext) {
    return;
  }
  await chunkKIDHIRVO_cjs.persistResponseTurnRecord({
    memoryStore: agentMemoryStore,
    responseId,
    metadata: {
      ...metadata,
      completedAt: completedState.completedAt,
      status: completedState.status,
      usage: completedState.usageDetails,
      providerOptions: completedState.providerOptions,
      messageIds: [],
      outputItems
    },
    threadContext,
    messages
  });
}
async function finalizeResponse({
  agentMemoryStore,
  didStore,
  threadContext,
  result,
  responseId,
  createdAt,
  model,
  instructions,
  previousResponseId,
  conversationId,
  configuredTools,
  responseMetadata,
  fallbackText,
  fallbackOutputItems
}) {
  const completedState = await resolveCompletedResponseState(result, fallbackText);
  const fallbackItems = fallbackOutputItems?.(completedState);
  const responseMessages = await chunkKIDHIRVO_cjs.resolveResponseTurnMessagesForStorage({
    result,
    responseId,
    text: completedState.text,
    threadContext,
    fallbackOutputItems: threadContext ? fallbackItems : void 0
  });
  const response = chunkF3HP5HM6_cjs.buildCompletedResponse({
    responseId,
    outputMessageId: responseId,
    model,
    createdAt,
    completedAt: completedState.completedAt,
    status: completedState.status,
    text: completedState.text,
    usage: completedState.usage,
    instructions,
    textConfig: responseMetadata.text,
    previousResponseId,
    conversationId,
    providerOptions: completedState.providerOptions,
    tools: configuredTools,
    messages: responseMessages,
    fallbackOutputItems: fallbackItems,
    store: didStore
  });
  await storeCompletedResponse({
    agentMemoryStore,
    didStore,
    threadContext,
    responseId,
    metadata: responseMetadata,
    completedState,
    messages: responseMessages,
    outputItems: response.output
  });
  return { completedState, response, responseMessages };
}
async function prepareCreateResponseRequest({
  body,
  mastra,
  requestContext
}) {
  const executionInput = chunkF3HP5HM6_cjs.mapResponseInputToExecutionMessages(body.input);
  let previousResponseTurnRecord = null;
  let resolvedAgent = null;
  if (body.previous_response_id) {
    if (body.agent_id) {
      resolvedAgent = await resolveResponseAgent({ mastra, agentId: body.agent_id });
      previousResponseTurnRecord = await chunkKIDHIRVO_cjs.findResponseTurnRecord({
        agent: resolvedAgent,
        responseId: body.previous_response_id,
        requestContext
      });
      if (!previousResponseTurnRecord) {
        const owningResponseTurnRecord = await chunkKIDHIRVO_cjs.findResponseTurnRecordAcrossAgents({
          mastra,
          responseId: body.previous_response_id,
          requestContext
        });
        if (owningResponseTurnRecord) {
          if (owningResponseTurnRecord.metadata.agentId === body.agent_id) {
            previousResponseTurnRecord = owningResponseTurnRecord;
          } else {
            throw new chunk64ITUOXI_cjs.HTTPException(400, {
              message: `Stored response ${body.previous_response_id} belongs to agent ${owningResponseTurnRecord.metadata.agentId}, not ${body.agent_id}`
            });
          }
        }
        if (!previousResponseTurnRecord) {
          throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored response ${body.previous_response_id} was not found` });
        }
      }
    } else {
      if (!mastra) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Mastra instance is required for agent-backed responses" });
      }
      previousResponseTurnRecord = await chunkKIDHIRVO_cjs.findResponseTurnRecordAcrossAgents({
        mastra,
        responseId: body.previous_response_id,
        requestContext
      });
      if (!previousResponseTurnRecord) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored response ${body.previous_response_id} was not found` });
      }
    }
  }
  const agent = resolvedAgent ?? await resolveResponseAgent({
    mastra,
    agentId: body.agent_id ?? previousResponseTurnRecord?.metadata.agentId
  });
  const resolvedModel = await agent.getModel({
    requestContext,
    modelConfig: body.model
  });
  const responseModel = body.model ?? (() => {
    if (resolvedModel.provider && resolvedModel.modelId) {
      const publicProviderId = resolvedModel.provider.includes(".") ? resolvedModel.provider.split(".")[0] : resolvedModel.provider;
      return `${publicProviderId}/${resolvedModel.modelId}`;
    }
    if (resolvedModel.modelId) {
      return resolvedModel.modelId;
    }
    throw new chunk64ITUOXI_cjs.HTTPException(500, {
      message: "Responses route could not determine the effective model for this request"
    });
  })();
  const shouldStore = body.store ?? false;
  const needsMemoryStore = shouldStore || Boolean(body.conversation_id) || Boolean(body.previous_response_id);
  const agentMemoryStore = needsMemoryStore ? await resolveAgentMemoryStore({
    agent,
    requestContext,
    errorMessage: body.previous_response_id ? "previous_response_id requires the target agent to have memory storage configured" : shouldStore ? "Stored responses require the target agent to have memory storage configured" : "conversation_id requires the target agent to have memory storage configured"
  }) : null;
  const configuredTools = chunkF3HP5HM6_cjs.mapMastraToolsToResponseTools(
    await Promise.resolve(agent.listTools({ requestContext }))
  );
  const responseId = chunkF3HP5HM6_cjs.createMessageId();
  const createdAt = Math.floor(Date.now() / 1e3);
  const threadContext = await resolveThreadExecutionContext({
    agent,
    store: shouldStore,
    conversationId: body.conversation_id,
    previousResponseTurnRecord,
    requestContext
  });
  if (shouldStore && !threadContext) {
    throw new chunk64ITUOXI_cjs.HTTPException(400, {
      message: "Stored responses require the target agent to have memory configured"
    });
  }
  const didStore = shouldStore && Boolean(threadContext);
  return {
    agent,
    agentMemoryStore,
    configuredTools,
    createdAt,
    didStore,
    executionInput,
    previousResponseTurnRecord,
    resolvedModel,
    responseId,
    responseModel,
    responseMetadata: {
      agentId: agent.id,
      model: responseModel,
      createdAt,
      instructions: body.instructions,
      text: body.text,
      previousResponseId: previousResponseTurnRecord?.message.id ?? body.previous_response_id,
      tools: configuredTools,
      store: didStore
    },
    threadContext
  };
}
function createResponseEventStream({
  agentMemoryStore,
  body,
  configuredTools,
  createdAt,
  didStore,
  previousResponseTurnRecord,
  responseId,
  responseModel,
  responseMetadata,
  streamResult,
  threadContext
}) {
  const createdResponse = chunkF3HP5HM6_cjs.buildInProgressResponse({
    responseId,
    model: responseModel,
    createdAt,
    instructions: body.instructions,
    textConfig: body.text,
    previousResponseId: body.previous_response_id,
    conversationId: threadContext?.threadId ?? body.conversation_id,
    tools: configuredTools,
    store: didStore
  });
  return new ReadableStream({
    async start(controller) {
      let sequenceNumber = 1;
      const enqueueEvent = (eventName, payload) => {
        controller.enqueue(
          chunkF3HP5HM6_cjs.formatSseEvent(eventName, {
            ...payload,
            sequence_number: sequenceNumber++
          })
        );
      };
      enqueueEvent("response.created", {
        type: "response.created",
        response: createdResponse
      });
      enqueueEvent("response.in_progress", {
        type: "response.in_progress",
        response: createdResponse
      });
      const streamEvents = chunkF3HP5HM6_cjs.createResponseStreamEventTranslator(responseId);
      const fullStream = await streamResult.fullStream;
      const reader = fullStream.getReader();
      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          for (const event of streamEvents.consume(value)) {
            enqueueEvent(event.event, event.payload);
          }
        }
        for (const event of streamEvents.flushPendingToolResults()) {
          enqueueEvent(event.event, event.payload);
        }
        const { completedState, response } = await finalizeResponse({
          agentMemoryStore,
          didStore,
          threadContext,
          result: streamResult,
          responseId,
          createdAt,
          model: responseModel,
          instructions: body.instructions,
          previousResponseId: previousResponseTurnRecord?.message.id ?? body.previous_response_id,
          conversationId: threadContext?.threadId ?? body.conversation_id,
          configuredTools,
          responseMetadata,
          fallbackText: streamEvents.text,
          fallbackOutputItems: (completedState2) => streamEvents.getOutputItems({
            text: completedState2.text,
            status: completedState2.status
          })
        });
        const completedItem = getStreamedMessageOutputItem(response, responseId);
        if (completedItem || completedState.text) {
          for (const event of streamEvents.completeText(
            completedState.text,
            completedItem ?? {
              id: responseId,
              type: "message",
              role: "assistant",
              status: "completed",
              content: [chunkF3HP5HM6_cjs.createOutputTextPart(completedState.text)]
            }
          )) {
            enqueueEvent(event.event, event.payload);
          }
        }
        enqueueEvent("response.completed", {
          type: "response.completed",
          response
        });
        controller.close();
      } catch (error) {
        controller.error(error);
      } finally {
        reader.releaseLock();
      }
    }
  });
}
var CREATE_RESPONSE_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/v1/responses",
  responseType: "datastream-response",
  bodySchema: chunk42WZN6MM_cjs.createResponseBodySchema,
  responseSchema: chunk42WZN6MM_cjs.responseObjectSchema,
  summary: "Create a response",
  description: "Creates a response through a Mastra-hosted Responses API-compatible route",
  tags: ["Responses"],
  requiresAuth: true,
  requiresPermission: chunk42M6Y2OD_cjs.MastraFGAPermissions.AGENTS_EXECUTE,
  handler: async ({ mastra, requestContext, abortSignal, ...body }) => {
    try {
      const {
        agent,
        agentMemoryStore,
        configuredTools,
        createdAt,
        didStore,
        executionInput,
        previousResponseTurnRecord,
        resolvedModel,
        responseId,
        responseModel,
        responseMetadata,
        threadContext
      } = await prepareCreateResponseRequest({ body, mastra, requestContext });
      if (!body.stream) {
        const result = await executeGenerate({
          agent,
          resolvedModel,
          modelOverride: body.model,
          instructions: body.instructions,
          text: body.text,
          providerOptions: body.providerOptions,
          input: executionInput,
          requestContext,
          abortSignal,
          threadContext
        });
        const { response } = await finalizeResponse({
          agentMemoryStore,
          didStore,
          threadContext,
          result,
          responseId,
          createdAt,
          model: responseModel,
          instructions: body.instructions,
          previousResponseId: previousResponseTurnRecord?.message.id ?? body.previous_response_id,
          conversationId: threadContext?.threadId ?? body.conversation_id,
          configuredTools,
          responseMetadata,
          fallbackText: ""
        });
        return jsonResponse(response);
      }
      const streamResult = await executeStream({
        agent,
        resolvedModel,
        modelOverride: body.model,
        instructions: body.instructions,
        text: body.text,
        providerOptions: body.providerOptions,
        input: executionInput,
        requestContext,
        abortSignal,
        threadContext
      });
      const stream = createResponseEventStream({
        agentMemoryStore,
        body,
        configuredTools,
        createdAt,
        didStore,
        previousResponseTurnRecord,
        responseId,
        responseModel,
        responseMetadata,
        streamResult,
        threadContext
      });
      return new Response(stream, {
        headers: {
          "Content-Type": "text/event-stream; charset=utf-8",
          "Cache-Control": "no-cache",
          Connection: "keep-alive",
          "X-Accel-Buffering": "no"
        }
      });
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error creating response");
    }
  }
});
var GET_RESPONSE_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/v1/responses/:responseId",
  responseType: "json",
  pathParamSchema: chunk42WZN6MM_cjs.responseIdPathParams,
  responseSchema: chunk42WZN6MM_cjs.responseObjectSchema,
  summary: "Retrieve a stored response",
  description: "Returns a previously stored response object",
  tags: ["Responses"],
  requiresAuth: true,
  requiresPermission: chunk42M6Y2OD_cjs.MastraFGAPermissions.AGENTS_READ,
  handler: async ({ mastra, requestContext, responseId }) => {
    try {
      const responseTurnRecord = await chunkKIDHIRVO_cjs.findResponseTurnRecordAcrossAgents({ mastra, responseId, requestContext });
      if (!responseTurnRecord) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored response ${responseId} was not found` });
      }
      return chunkF3HP5HM6_cjs.mapResponseTurnRecordToResponse(responseTurnRecord);
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error retrieving response");
    }
  }
});
var DELETE_RESPONSE_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "DELETE",
  path: "/v1/responses/:responseId",
  responseType: "json",
  pathParamSchema: chunk42WZN6MM_cjs.responseIdPathParams,
  responseSchema: chunk42WZN6MM_cjs.deleteResponseSchema,
  summary: "Delete a stored response",
  description: "Deletes a stored response so it can no longer be retrieved or chained",
  tags: ["Responses"],
  requiresAuth: true,
  requiresPermission: chunk42M6Y2OD_cjs.MastraFGAPermissions.AGENTS_DELETE,
  handler: async ({ mastra, requestContext, responseId }) => {
    try {
      const responseTurnRecord = await chunkKIDHIRVO_cjs.findResponseTurnRecordAcrossAgents({ mastra, responseId, requestContext });
      if (!responseTurnRecord) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored response ${responseId} was not found` });
      }
      await chunkKIDHIRVO_cjs.deleteResponseTurnRecord({ responseTurnRecord });
      const response = {
        id: responseId,
        object: "response",
        deleted: true
      };
      return response;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error deleting response");
    }
  }
});

exports.CREATE_RESPONSE_ROUTE = CREATE_RESPONSE_ROUTE;
exports.DELETE_RESPONSE_ROUTE = DELETE_RESPONSE_ROUTE;
exports.GET_RESPONSE_ROUTE = GET_RESPONSE_ROUTE;
exports.responses_exports = responses_exports;
//# sourceMappingURL=chunk-YZVC4WQD.cjs.map
//# sourceMappingURL=chunk-YZVC4WQD.cjs.map