import {
  createThread,
  updateThreadStatus,
  updateThreadUsage
} from "../chunk-B4F53V4H.js";
import {
  runTurn
} from "../chunk-CRCDYAJC.js";
import "../chunk-PJZ5TQYW.js";
import "../chunk-AU4NAQGA.js";
import "../chunk-RIEAZ4TR.js";
import "../chunk-DBFPJSOY.js";
import "../chunk-72BKGVBE.js";
import "../chunk-HLP24IVO.js";
import "../chunk-SK4OB66U.js";
import "../chunk-DZIKCTP6.js";
import "../chunk-7T3L22TP.js";
import {
  getActor
} from "../chunk-LAWTTG2E.js";
import "../chunk-T3WHRKGD.js";
import "../chunk-4XXQAVKE.js";
import "../chunk-2RZARCTJ.js";
import "../chunk-5ZFOKZGR.js";
import {
  appendEvent
} from "../chunk-4NRHKTBW.js";
import "../chunk-JU6ELMEH.js";
import {
  bumpSessionStats,
  createSession,
  getSession,
  getSessionRow
} from "../chunk-SEGKFEG5.js";
import "../chunk-UU3ECGO5.js";
import "../chunk-AIBH32FN.js";
import "../chunk-YPXI7Q2M.js";
import {
  listEvents
} from "../chunk-LH3NEWMT.js";
import "../chunk-5UXN6QXJ.js";
import "../chunk-CTVBTCTF.js";
import "../chunk-EFOIR7R3.js";
import "../chunk-ZKZME3DE.js";
import "../chunk-GTYDSYTR.js";
import "../chunk-G7KUVNDY.js";
import {
  getAgent
} from "../chunk-LGPJPAHU.js";
import "../chunk-X27B5TCC.js";
import "../chunk-N7MLFZPQ.js";
import "../chunk-GU2NP7QE.js";
import "../chunk-6SD6MC2B.js";
import "../chunk-KUXEAQFY.js";
import "../chunk-CMOU2OFW.js";
import "../chunk-OGA7KDQZ.js";
import "../chunk-B6E6BVNK.js";
import "../chunk-UTSN34VY.js";
import "../chunk-PAQ2JFVD.js";
import "../chunk-S3JRZFF5.js";
import "../chunk-PZ5EGY64.js";
import "../chunk-CR3BEBUF.js";
import "../chunk-URNG7ZX2.js";
import "../chunk-ETWGCBIQ.js";
import "../chunk-UY3VT3HQ.js";
import "../chunk-PDWLVL34.js";
import "../chunk-YF3CVKQL.js";
import "../chunk-V5DH3OAC.js";
import "../chunk-JZE6OQDW.js";
import "../chunk-TPMZO6S2.js";
import "../chunk-3NYWS7JW.js";
import "../chunk-AQHYCRTO.js";
import "../chunk-7TSTCMII.js";
import "../chunk-KJ2GJLPQ.js";
import "../chunk-IBYOMAZ3.js";
import "../chunk-5R6325PY.js";
import "../chunk-437VVFAL.js";
import "../chunk-PJYCPDV5.js";
import "../chunk-IXTVS4A7.js";
import "../chunk-NMZMRH3E.js";
import "../chunk-CULYZ3VA.js";
import "../chunk-XJYR5HE3.js";
import "../chunk-7SF6FJ4U.js";
import "../chunk-4YC37DDW.js";
import "../chunk-H5YPGXEY.js";
import "../chunk-YE2RMJY7.js";
import "../chunk-CY6AWCC6.js";
import "../chunk-VRRGSQI7.js";
import "../chunk-FX2AEKOV.js";
import "../chunk-7AFOH6YL.js";
import "../chunk-7XQLG5P2.js";
import "../chunk-2MAQ6JFL.js";
import "../chunk-F4WUVOLE.js";
import {
  init_clock,
  nowMs
} from "../chunk-HFDLUBWN.js";
import "../chunk-RII4M3J2.js";
import "../chunk-DDJOPRB7.js";
import "../chunk-TLEKKGH7.js";
import "../chunk-KBM3MISV.js";
import "../chunk-J5Z5DSH4.js";
import {
  ApiError
} from "../chunk-EZYKRG4W.js";
import "../chunk-UYTSKFGK.js";
import "../chunk-2ESYSVXG.js";

// src/sessions/threads.ts
init_clock();
var MAX_THREAD_DEPTH = 1;
async function handleSpawnAgent(parentSessionId, agentId, prompt, parentDepth, parentTrace) {
  if (parentDepth >= MAX_THREAD_DEPTH) {
    throw new ApiError(
      400,
      "invalid_request_error",
      `thread depth limit reached (max ${MAX_THREAD_DEPTH})`
    );
  }
  const parentSession = getSession(parentSessionId);
  if (!parentSession) {
    throw new ApiError(404, "not_found_error", `parent session not found: ${parentSessionId}`);
  }
  const parentAgent = getAgent(parentSession.agent.id, parentSession.agent.version);
  if (parentAgent && parentAgent.callable_agents.length > 0) {
    const allowed = parentAgent.callable_agents.some((ca) => ca.id === agentId);
    if (!allowed) {
      return `Error: agent ${agentId} is not in callable_agents list`;
    }
  }
  const agent = getAgent(agentId);
  if (!agent) {
    throw new ApiError(404, "not_found_error", `agent not found: ${agentId}`);
  }
  const thread = createThread({
    sessionId: parentSessionId,
    agentId: agent.id,
    agentVersion: agent.version
  });
  appendEvent(parentSessionId, {
    type: "session.thread_created",
    payload: {
      session_thread_id: thread.id,
      agent_name: agent.name,
      agent_id: agentId
    },
    origin: "server",
    processedAt: nowMs(),
    traceId: parentTrace?.trace_id ?? null,
    spanId: parentTrace?.span_id ?? null,
    parentSpanId: parentTrace?.parent_span_id ?? null
  });
  const childSession = createSession({
    agent_id: agent.id,
    agent_version: agent.version,
    environment_id: parentSession.environment_id,
    title: `Thread from ${parentSessionId}`,
    metadata: { parent_session_id: parentSessionId, session_thread_id: thread.id },
    parent_session_id: parentSessionId,
    thread_depth: parentDepth + 1,
    vault_ids: parentSession.vault_ids
  });
  updateThreadStatus(thread.id, "running");
  appendEvent(parentSessionId, {
    type: "session.thread_status_running",
    payload: {
      session_thread_id: thread.id,
      agent_name: agent.name,
      child_session_id: childSession.id
    },
    origin: "server",
    processedAt: nowMs(),
    traceId: parentTrace?.trace_id ?? null,
    spanId: parentTrace?.span_id ?? null,
    parentSpanId: parentTrace?.parent_span_id ?? null
  });
  appendEvent(parentSessionId, {
    type: "agent.thread_message_sent",
    payload: {
      to_session_thread_id: thread.id,
      to_agent_name: agent.name,
      content: prompt
    },
    origin: "server",
    processedAt: nowMs(),
    traceId: parentTrace?.trace_id ?? null,
    spanId: parentTrace?.span_id ?? null,
    parentSpanId: parentTrace?.parent_span_id ?? null
  });
  getActor(childSession.id);
  const eventId = `thread_${childSession.id}_${nowMs()}`;
  await runTurn(childSession.id, [
    { kind: "text", eventId, text: prompt }
  ], 0, parentTrace);
  const maxWaitMs = 3e5;
  const pollIntervalMs = 500;
  const startMs = nowMs();
  let childRow = getSessionRow(childSession.id);
  while (childRow && childRow.status === "running" && nowMs() - startMs < maxWaitMs) {
    await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
    childRow = getSessionRow(childSession.id);
  }
  if (childRow && childRow.status === "running") {
    const { interruptSession } = await import("./interrupt.js");
    interruptSession(childSession.id);
  }
  let resultText = "";
  const events = listEvents(childSession.id, { limit: 100, order: "desc" });
  for (const evt of events) {
    if (evt.type === "agent.message") {
      const payload = JSON.parse(evt.payload_json);
      const text = (payload.content ?? []).filter((b) => b.type === "text" && b.text).map((b) => b.text).join("");
      if (text) {
        resultText = text;
        break;
      }
    }
  }
  const finalChildRow = getSessionRow(childSession.id);
  if (finalChildRow) {
    bumpSessionStats(
      parentSessionId,
      { tool_calls_count: finalChildRow.tool_calls_count },
      {
        input_tokens: finalChildRow.usage_input_tokens,
        output_tokens: finalChildRow.usage_output_tokens,
        cache_read_input_tokens: finalChildRow.usage_cache_read_input_tokens,
        cache_creation_input_tokens: finalChildRow.usage_cache_creation_input_tokens,
        cost_usd: finalChildRow.usage_cost_usd
      }
    );
    updateThreadUsage(thread.id, {
      input_tokens: finalChildRow.usage_input_tokens,
      output_tokens: finalChildRow.usage_output_tokens,
      cache_read_input_tokens: finalChildRow.usage_cache_read_input_tokens,
      cache_creation_input_tokens: finalChildRow.usage_cache_creation_input_tokens
    });
  }
  const stopReason = childRow?.stop_reason ?? "end_turn";
  const threadStatus = stopReason === "error" ? "terminated" : "idle";
  updateThreadStatus(thread.id, threadStatus, stopReason);
  appendEvent(parentSessionId, {
    type: "agent.thread_message_received",
    payload: {
      from_session_thread_id: thread.id,
      from_agent_name: agent.name,
      content: resultText || "(no response from sub-agent)"
    },
    origin: "server",
    processedAt: nowMs(),
    traceId: parentTrace?.trace_id ?? null,
    spanId: parentTrace?.span_id ?? null,
    parentSpanId: parentTrace?.parent_span_id ?? null
  });
  const statusEventType = threadStatus === "idle" ? "session.thread_status_idle" : "session.thread_status_terminated";
  appendEvent(parentSessionId, {
    type: statusEventType,
    payload: {
      session_thread_id: thread.id,
      agent_name: agent.name,
      stop_reason: stopReason,
      child_session_id: childSession.id,
      child_usage: finalChildRow ? {
        input_tokens: finalChildRow.usage_input_tokens,
        output_tokens: finalChildRow.usage_output_tokens,
        cache_read_input_tokens: finalChildRow.usage_cache_read_input_tokens,
        cache_creation_input_tokens: finalChildRow.usage_cache_creation_input_tokens,
        cost_usd: finalChildRow.usage_cost_usd,
        tool_calls_count: finalChildRow.tool_calls_count
      } : null
    },
    origin: "server",
    processedAt: nowMs(),
    traceId: parentTrace?.trace_id ?? null,
    spanId: parentTrace?.span_id ?? null,
    parentSpanId: parentTrace?.parent_span_id ?? null
  });
  return resultText || "(no response from sub-agent)";
}
export {
  handleSpawnAgent
};
