// src/runtime/sandbox-events.ts
function extractLlmCallEvent(event, agentRunName) {
  if (!event || typeof event !== "object") return void 0;
  const type = String(event.type ?? "");
  const data = event.data && typeof event.data === "object" ? event.data : {};
  if (type === "llm_call" || type === "cost.usage" || type === "usage") {
    return buildLlmCall(data, agentRunName);
  }
  if (type === "message.completed" || type === "result" || type === "final") {
    const usage = data.usage;
    if (!usage || typeof usage !== "object") return void 0;
    return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName);
  }
  if (type === "done") {
    const usage = data.tokenUsage;
    if (!usage || typeof usage !== "object") return void 0;
    const out = pickFiniteNumber(usage, ["outputTokens", "completion_tokens", "tokensOut"]);
    const reasoning = pickFiniteNumber(usage, ["reasoningTokens"]);
    const mergedOut = out !== void 0 || reasoning !== void 0 ? (out ?? 0) + (reasoning ?? 0) : void 0;
    return buildLlmCall(
      {
        inputTokens: usage.inputTokens,
        outputTokens: mergedOut,
        totalCostUsd: data.totalCostUsd,
        model: data.model ?? usage.model
      },
      agentRunName
    );
  }
  return void 0;
}
function sumSandboxUsage(events, agentRunName = "agent") {
  let input = 0;
  let output = 0;
  let costUsd = 0;
  for (const ev of events) {
    const call = extractLlmCallEvent(ev, agentRunName);
    if (!call) continue;
    input += call.tokensIn ?? 0;
    output += call.tokensOut ?? 0;
    costUsd += call.costUsd ?? 0;
  }
  return { input, output, costUsd };
}
function buildLlmCall(data, agentRunName) {
  const tokensIn = pickFiniteNumber(data, ["tokensIn", "inputTokens", "prompt_tokens"]);
  const tokensOut = pickFiniteNumber(data, ["tokensOut", "outputTokens", "completion_tokens"]);
  const costUsd = pickFiniteNumber(data, ["costUsd", "totalCostUsd", "cost_usd", "cost"]);
  if (tokensIn === void 0 && tokensOut === void 0 && costUsd === void 0) {
    return void 0;
  }
  const model = typeof data.model === "string" && data.model.length > 0 ? data.model : agentRunName;
  const event = {
    type: "llm_call",
    model
  };
  if (tokensIn !== void 0) event.tokensIn = tokensIn;
  if (tokensOut !== void 0) event.tokensOut = tokensOut;
  if (costUsd !== void 0) event.costUsd = costUsd;
  return event;
}
function pickFiniteNumber(data, keys) {
  for (const key of keys) {
    const value = data[key];
    if (typeof value === "number" && Number.isFinite(value)) return value;
  }
  return void 0;
}
function createSandboxToolPartState() {
  return { statusByCall: /* @__PURE__ */ new Map(), seq: 0 };
}
var TERMINAL_TOOL_FAILURE = /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i;
function mapSandboxToolEvent(event, state) {
  if (!event || typeof event !== "object") return [];
  const type = String(event.type ?? "");
  const data = event.data && typeof event.data === "object" ? event.data : {};
  if (type === "message.part.updated") {
    const part = data.part && typeof data.part === "object" ? data.part : {};
    if (String(part.type ?? "") !== "tool") return [];
    return projectToolPart(part, state, typeof event.id === "string" ? event.id : void 0);
  }
  if (type.includes("tool")) {
    const callId = pickString(data, ["toolCallId", "tool_use_id", "id"]) ?? (typeof event.id === "string" ? event.id : void 0) ?? `sandbox-tool-${++state.seq}`;
    const toolName = pickString(data, ["name", "toolName", "tool"]) ?? "sandbox_tool";
    if (type.includes("result")) {
      return [
        {
          type: "tool_result",
          toolName,
          toolCallId: callId,
          result: data.output ?? data.result ?? data.content ?? data
        }
      ];
    }
    return [
      { type: "tool_call", toolName, toolCallId: callId, args: data.input ?? data.args ?? {} }
    ];
  }
  return [];
}
function projectToolPart(part, state, eventId) {
  const callId = pickString(part, ["callID", "callId", "toolCallId", "id"]) ?? eventId ?? `sandbox-tool-${++state.seq}`;
  const toolName = pickString(part, ["tool", "toolName", "name"]) ?? "sandbox_tool";
  const toolState = part.state && typeof part.state === "object" ? part.state : {};
  const metadata = toolState.metadata && typeof toolState.metadata === "object" ? toolState.metadata : {};
  const status = pickString(toolState, ["status"]) ?? "updated";
  const previous = state.statusByCall.get(callId);
  const settled = previous === "completed" || previous !== void 0 && TERMINAL_TOOL_FAILURE.test(previous);
  if (settled) return [];
  const out = [];
  if (previous === void 0) {
    out.push({
      type: "tool_call",
      toolName,
      toolCallId: callId,
      args: toolState.input ?? metadata.input ?? {}
    });
  }
  state.statusByCall.set(callId, status);
  if (status === "completed") {
    out.push({
      type: "tool_result",
      toolName,
      toolCallId: callId,
      result: toolState.output ?? metadata.output ?? ""
    });
  } else if (TERMINAL_TOOL_FAILURE.test(status)) {
    const message = pickString(toolState, ["error", "message"]) ?? pickString(metadata, ["error", "message"]) ?? `sandbox tool ended with status ${status}`;
    const output = toolState.output ?? metadata.output;
    out.push({
      type: "tool_result",
      toolName,
      toolCallId: callId,
      result: { error: message, status, ...output !== void 0 ? { output } : {} }
    });
  }
  return out;
}
function pickString(data, keys) {
  for (const key of keys) {
    const value = data[key];
    if (typeof value === "string" && value.length > 0) return value;
  }
  return void 0;
}
function mapSandboxEvent(event, opts = {}) {
  if (!event || typeof event !== "object") return void 0;
  const type = String(event.type ?? "");
  const data = event.data && typeof event.data === "object" ? event.data : {};
  if (type === "message.part.updated") {
    const part = data.part && typeof data.part === "object" ? data.part : {};
    const partType = String(part.type ?? "");
    const delta = typeof data.delta === "string" ? data.delta : void 0;
    const text = delta ?? (typeof part.text === "string" ? part.text : void 0);
    if (text === void 0) return void 0;
    if (partType === "text") return { type: "text_delta", text };
    if (partType === "reasoning" || partType === "thinking")
      return { type: "reasoning_delta", text };
    return void 0;
  }
  return extractLlmCallEvent(event, opts.agentRunName ?? "agent");
}

export {
  extractLlmCallEvent,
  sumSandboxUsage,
  createSandboxToolPartState,
  mapSandboxToolEvent,
  mapSandboxEvent
};
//# sourceMappingURL=chunk-M22PL4GH.js.map