import {
  reportUpstreamFailure,
  reportUpstreamSuccess,
  resolveAnthropicKey
} from "./chunk-QSSOZHWF.js";
import {
  resolveRemoteSessionId
} from "./chunk-WU2SRT5G.js";
import {
  interruptSession
} from "./chunk-DC2UMEQH.js";
import {
  createOrUpsertMemory,
  deleteMemory,
  getMemory,
  listMemories,
  listMemoryStores,
  searchMemories,
  updateMemory
} from "./chunk-2UKAINAN.js";
import {
  assertResourceTenant
} from "./chunk-3F6VNSRK.js";
import {
  jsonOk,
  paginatedOk,
  routeWrap
} from "./chunk-KKJ5D3II.js";
import {
  forwardToAnthropic
} from "./chunk-VFSHH6I2.js";
import {
  runTurn,
  writePermissionResponse
} from "./chunk-D6BHZQGP.js";
import {
  enqueueTurn
} from "./chunk-ULPKWCA5.js";
import {
  getProxiedTenantId,
  isProxied
} from "./chunk-DZIKCTP6.js";
import {
  getActor
} from "./chunk-LAWTTG2E.js";
import {
  appendEvent
} from "./chunk-4NRHKTBW.js";
import {
  bumpSessionStats,
  getSession,
  getSessionRow,
  setOutcomeCriteria,
  updateSessionMutable
} from "./chunk-SEGKFEG5.js";
import {
  listEvents,
  rowToManagedEvent
} from "./chunk-LH3NEWMT.js";
import {
  getEnvironment,
  getEnvironmentRow
} from "./chunk-GTYDSYTR.js";
import {
  getAgent
} from "./chunk-LGPJPAHU.js";
import {
  getConfig
} from "./chunk-2MAQ6JFL.js";
import {
  init_clock,
  nowMs
} from "./chunk-HFDLUBWN.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";
import {
  pushPendingUserInput
} from "./chunk-UYTSKFGK.js";

// src/handlers/anthropic-compat/events.ts
import { z } from "zod";
init_client();
init_clock();
function assertSessionTenant(auth, sessionId) {
  const row = getDb().prepare(`SELECT tenant_id FROM sessions WHERE id = ?`).get(sessionId);
  if (row) {
    assertResourceTenant(auth, row.tenant_id, `session ${sessionId} not found`);
    return;
  }
  const proxyTenant = getProxiedTenantId(sessionId);
  if (proxyTenant !== void 0) {
    assertResourceTenant(auth, proxyTenant, `session ${sessionId} not found`);
    return;
  }
  throw notFound(`session ${sessionId} not found`);
}
var teeLog = (...args) => {
  if (process.env.DEBUG_SYNC === "1") console.log(...args);
};
var activeTees = /* @__PURE__ */ new Set();
var MAX_TEE_REENTRIES = 25;
async function executeServerSideTool(toolName, input, sessionId) {
  if (toolName === "memory" || toolName.startsWith("memory_")) {
    return executeMemoryTool(input, sessionId);
  }
  return null;
}
function executeMemoryTool(input, _sessionId) {
  const command = String(input.command ?? "");
  const storeId = String(input.store_id ?? "");
  if (command === "view") {
    if (!storeId) return { content: JSON.stringify({ error: "store_id is required" }) };
    const memories = listMemories(storeId);
    return { content: JSON.stringify({ memories }) };
  }
  if (command === "search") {
    if (!storeId) return { content: JSON.stringify({ error: "store_id is required" }) };
    const query = String(input.query ?? "");
    if (!query) return { content: JSON.stringify({ error: "query is required" }) };
    const memories = searchMemories(storeId, query);
    return { content: JSON.stringify({ memories }) };
  }
  if (command === "create") {
    if (!storeId) return { content: JSON.stringify({ error: "store_id is required" }) };
    const content = String(input.content ?? "");
    if (!content) return { content: JSON.stringify({ error: "content is required" }) };
    const path = String(input.path ?? `auto_${Date.now()}`);
    const memory = createOrUpsertMemory(storeId, path, content);
    return { content: JSON.stringify({ memory }) };
  }
  if (command === "update") {
    const memoryId = String(input.memory_id ?? "");
    if (!memoryId) return { content: JSON.stringify({ error: "memory_id is required" }) };
    const content = String(input.content ?? "");
    if (!content) return { content: JSON.stringify({ error: "content is required" }) };
    const { memory, conflict } = updateMemory(memoryId, content);
    if (conflict) return { content: JSON.stringify({ error: "conflict", detail: "content changed since last read" }) };
    if (!memory) return { content: JSON.stringify({ error: "not_found" }) };
    return { content: JSON.stringify({ memory }) };
  }
  if (command === "delete") {
    const memoryId = String(input.memory_id ?? "");
    if (!memoryId) return { content: JSON.stringify({ error: "memory_id is required" }) };
    const existing = getMemory(memoryId);
    if (!existing) return { content: JSON.stringify({ error: "not_found" }) };
    deleteMemory(memoryId);
    return { content: JSON.stringify({ deleted: true }) };
  }
  if (command === "list_stores") {
    const stores = listMemoryStores();
    return { content: JSON.stringify({ stores }) };
  }
  return { content: JSON.stringify({ error: `unknown memory command: ${command}` }) };
}
async function teeRemoteStream(localSessionId, remoteSessionId) {
  if (activeTees.has(localSessionId)) return;
  activeTees.add(localSessionId);
  try {
    await teeRemoteStreamInner(localSessionId, remoteSessionId);
  } finally {
    activeTees.delete(localSessionId);
  }
}
async function teeRemoteStreamInner(localSessionId, remoteSessionId) {
  const resolved = resolveAnthropicKey({ sessionId: localSessionId });
  if (!resolved) {
    teeLog("[tee] no API key");
    return;
  }
  const { value: apiKey, poolId } = resolved;
  const seenIds = /* @__PURE__ */ new Set();
  let reentryCount = 0;
  while (reentryCount <= MAX_TEE_REENTRIES) {
    teeLog(`[tee] connecting to Anthropic stream for ${remoteSessionId} (iteration ${reentryCount})`);
    const res = await fetch(`https://api.anthropic.com/v1/sessions/${remoteSessionId}/events/stream`, {
      headers: {
        "x-api-key": apiKey,
        "anthropic-version": "2023-06-01",
        "anthropic-beta": "managed-agents-2026-04-01",
        "accept": "text/event-stream"
      }
    });
    if (!res.ok || !res.body) {
      teeLog(`[tee] stream failed: ${res.status}`);
      if (res.status >= 500 || res.status === 429 || res.status === 401) {
        reportUpstreamFailure(poolId);
      }
      return;
    }
    if (reentryCount === 0) reportUpstreamSuccess(poolId);
    teeLog(`[tee] stream connected`);
    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";
    let sawRequiresAction = false;
    let lastToolUseEvt = null;
    let turnToolCalls = 0;
    let turnRunningAt = 0;
    let turnUsage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() ?? "";
        let eventData = "";
        for (const line of lines) {
          if (line.startsWith("data: ")) {
            eventData += line.slice(6);
          } else if (line === "" && eventData) {
            try {
              const evt = JSON.parse(eventData);
              const evtId = evt.id ?? "";
              if (evtId && seenIds.has(evtId)) {
                eventData = "";
                continue;
              }
              if (evtId) seenIds.add(evtId);
              if (evt.type === "user" || evt.type === "user.message" || evt.type === "user.custom_tool_result") {
                eventData = "";
                continue;
              }
              const typeMap = {
                "agent": "agent.message",
                "status_running": "session.status_running",
                "status_idle": "session.status_idle",
                "model_request_start": "span.model_request_start",
                "model_request_end": "span.model_request_end"
              };
              const localType = typeMap[evt.type] ?? evt.type;
              teeLog(`[tee] event: ${localType}`);
              appendEvent(localSessionId, {
                type: localType,
                payload: evt,
                origin: "server",
                processedAt: Date.now()
              });
              if (localType === "session.status_running") {
                turnRunningAt = Date.now();
              }
              if (localType.includes("tool_use")) {
                turnToolCalls++;
              }
              if (localType === "span.model_request_end") {
                const mu = evt.model_usage ?? evt.usage;
                if (mu) {
                  turnUsage.input_tokens += mu.input_tokens ?? 0;
                  turnUsage.output_tokens += mu.output_tokens ?? 0;
                  turnUsage.cache_read_input_tokens += mu.cache_read_input_tokens ?? 0;
                  turnUsage.cache_creation_input_tokens += mu.cache_creation_input_tokens ?? 0;
                }
              }
              if (localType === "session.status_idle") {
                const activeSec = turnRunningAt > 0 ? (Date.now() - turnRunningAt) / 1e3 : 0;
                bumpSessionStats(
                  localSessionId,
                  { turn_count: 1, tool_calls_count: turnToolCalls, active_seconds: Math.round(activeSec), duration_seconds: Math.round(activeSec) },
                  turnUsage.input_tokens > 0 || turnUsage.output_tokens > 0 ? turnUsage : void 0
                );
                if (reentryCount === 0) {
                  const session = getSession(localSessionId);
                  if (session && !session.title) {
                    const firstUserEvt = listEvents(localSessionId, { limit: 1, order: "asc" });
                    if (firstUserEvt.length > 0 && firstUserEvt[0].type === "user.message") {
                      try {
                        const p = JSON.parse(firstUserEvt[0].payload_json);
                        const text = p.content?.[0]?.text;
                        if (text) updateSessionMutable(localSessionId, { title: text.slice(0, 60) });
                      } catch {
                      }
                    }
                  }
                }
                turnToolCalls = 0;
                turnRunningAt = 0;
                turnUsage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
              }
              if (localType === "tool_use" || localType === "agent.custom_tool_use") {
                lastToolUseEvt = evt;
              }
              if (localType === "session.status_idle" && lastToolUseEvt) {
                sawRequiresAction = true;
                teeLog(`[tee] idle with pending tool_use \u2014 breaking for re-entry`);
                reader.cancel().catch(() => {
                });
              }
            } catch {
            }
            eventData = "";
          }
        }
      }
    } catch (err) {
      teeLog(`[tee] stream read error:`, err);
    }
    teeLog(`[tee] stream loop exited. sawRequiresAction=${sawRequiresAction} lastToolUseEvt=${!!lastToolUseEvt}`);
    if (!sawRequiresAction) return;
    teeLog(`[tee] detected requires_action \u2014 checking for server-side tool`);
    let toolPayload = lastToolUseEvt;
    if (!toolPayload) {
      const recentEvents = listEvents(localSessionId, { limit: 20, order: "desc" });
      const toolEvt = recentEvents.find(
        (e) => e.type === "tool_use" || e.type === "agent.custom_tool_use" || e.type === "agent.tool_use"
      );
      if (!toolEvt) {
        teeLog(`[tee] no tool_use event found`);
        return;
      }
      try {
        toolPayload = JSON.parse(toolEvt.payload_json);
      } catch {
        teeLog(`[tee] failed to parse tool event payload`);
        return;
      }
    }
    const toolName = toolPayload.tool_name ?? toolPayload.name ?? "";
    const toolUseId = toolPayload.tool_use_id ?? toolPayload.id ?? "";
    const toolInput = toolPayload.input ?? {};
    const result = await executeServerSideTool(toolName, toolInput, localSessionId);
    if (!result) {
      teeLog(`[tee] tool "${toolName}" not handled server-side \u2014 leaving as requires_action`);
      return;
    }
    teeLog(`[tee] tool "${toolName}" handled server-side \u2014 sending result to Anthropic`);
    appendEvent(localSessionId, {
      type: "user.custom_tool_result",
      payload: {
        custom_tool_use_id: toolUseId,
        content: [{ type: "text", text: result.content }]
      },
      origin: "server",
      processedAt: Date.now()
    });
    const postRes = await fetch(
      `https://api.anthropic.com/v1/sessions/${remoteSessionId}/events`,
      {
        method: "POST",
        headers: {
          "x-api-key": apiKey,
          "anthropic-version": "2023-06-01",
          "anthropic-beta": "managed-agents-2026-04-01",
          "content-type": "application/json"
        },
        body: JSON.stringify({
          events: [{
            type: "user.custom_tool_result",
            custom_tool_use_id: toolUseId,
            content: [{ type: "text", text: result.content }]
          }]
        })
      }
    );
    if (!postRes.ok) {
      teeLog(`[tee] failed to send tool result to Anthropic: ${postRes.status}`);
      return;
    }
    teeLog(`[tee] tool result sent \u2014 backfilling missed events before re-opening stream`);
    try {
      const backfillRes = await fetch(
        `https://api.anthropic.com/v1/sessions/${remoteSessionId}/events?limit=50`,
        {
          headers: {
            "x-api-key": apiKey,
            "anthropic-version": "2023-06-01",
            "anthropic-beta": "managed-agents-2026-04-01"
          }
        }
      );
      if (backfillRes.ok) {
        const backfillBody = await backfillRes.json();
        const backfillEvents = backfillBody.data ?? [];
        let backfilled = 0;
        const typeMap = {
          "agent": "agent.message",
          "status_running": "session.status_running",
          "status_idle": "session.status_idle",
          "model_request_start": "span.model_request_start",
          "model_request_end": "span.model_request_end"
        };
        for (const evt of backfillEvents) {
          const evtId = evt.id ?? "";
          if (!evtId || seenIds.has(evtId)) continue;
          const evtType = evt.type ?? "";
          if (evtType === "user" || evtType === "user.message" || evtType === "user.custom_tool_result") continue;
          seenIds.add(evtId);
          const localType = typeMap[evtType] ?? evtType;
          appendEvent(localSessionId, {
            type: localType,
            payload: evt,
            origin: "server",
            processedAt: Date.now()
          });
          backfilled++;
        }
        teeLog(`[tee] backfilled ${backfilled} events from Anthropic`);
      }
    } catch (err) {
      teeLog(`[tee] backfill failed:`, err);
    }
    reentryCount++;
  }
  if (reentryCount > MAX_TEE_REENTRIES) {
    console.warn(`[tee] max re-entry depth (${MAX_TEE_REENTRIES}) exceeded for session ${localSessionId}`);
  }
}
var TextBlock = z.object({ type: z.literal("text"), text: z.string() });
var UserMessage = z.object({
  type: z.literal("user.message"),
  content: z.array(TextBlock).min(1)
});
var UserInterrupt = z.object({ type: z.literal("user.interrupt") });
var UserToolConfirmation = z.object({
  type: z.literal("user.tool_confirmation"),
  tool_use_id: z.string().optional(),
  result: z.enum(["allow", "deny"]).optional(),
  deny_message: z.string().optional()
});
var UserCustomToolResult = z.object({
  type: z.literal("user.custom_tool_result"),
  custom_tool_use_id: z.string(),
  content: z.array(z.unknown())
});
var UserDefineOutcome = z.object({
  type: z.literal("user.define_outcome"),
  description: z.string().min(1),
  rubric: z.union([
    z.string(),
    z.object({ type: z.literal("text"), content: z.string() }),
    z.object({ type: z.literal("file"), file_id: z.string() })
  ]).optional(),
  max_iterations: z.number().int().min(1).max(20).optional()
});
var UserEvent = z.union([
  UserMessage,
  UserInterrupt,
  UserToolConfirmation,
  UserCustomToolResult,
  UserDefineOutcome
]);
var BatchSchema = z.object({
  events: z.array(UserEvent).min(1)
});
function handlePostEvents(request, sessionId) {
  return routeWrap(request, async ({ auth }) => {
    assertSessionTenant(auth, sessionId);
    if (isProxied(sessionId)) {
      const remoteId = resolveRemoteSessionId(sessionId);
      const localSession = getSession(sessionId);
      if (localSession) {
        const rawBody = await request.text();
        try {
          const body2 = JSON.parse(rawBody);
          if (body2?.events) {
            for (const evt of body2.events) {
              appendEvent(sessionId, {
                type: evt.type === "user.message" ? "user.message" : evt.type,
                payload: evt,
                origin: "user",
                processedAt: Date.now()
              });
            }
          }
        } catch {
        }
        const resolvedKey = resolveAnthropicKey({ sessionId });
        const proxyRes = await forwardToAnthropic(
          request,
          `/v1/sessions/${remoteId}/events`,
          { body: rawBody, apiKey: resolvedKey?.value }
        );
        if (!proxyRes.ok && (proxyRes.status >= 500 || proxyRes.status === 429 || proxyRes.status === 401)) {
          reportUpstreamFailure(resolvedKey?.poolId ?? null);
        } else if (proxyRes.ok) {
          reportUpstreamSuccess(resolvedKey?.poolId ?? null);
        }
        teeRemoteStream(sessionId, remoteId).catch(() => {
        });
        return proxyRes;
      }
      return forwardToAnthropic(request, `/v1/sessions/${remoteId}/events`);
    }
    const session = getSession(sessionId);
    if (!session) throw notFound(`session ${sessionId} not found`);
    const body = await request.json().catch(() => null);
    const parsed = BatchSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    for (const event of parsed.data.events) {
      if (event.type === "user.tool_confirmation") {
        const agent = getAgent(session.agent.id, session.agent.version);
        if (!agent?.confirmation_mode) {
          throw badRequest(
            "user.tool_confirmation is not supported: this agent does not have confirmation_mode enabled. Set confirmation_mode: true on the agent to use tool confirmation."
          );
        }
      }
    }
    const idemHeader = request.headers.get("idempotency-key") || request.headers.get("Idempotency-Key");
    const actor = getActor(sessionId);
    const hasInterrupt = parsed.data.events.some((e) => e.type === "user.interrupt");
    if (hasInterrupt) {
      interruptSession(sessionId);
    }
    const appended = await actor.enqueue(async () => {
      const rows = [];
      const pendingForTurn = [];
      let sawInterrupt = false;
      for (const [idx, event] of parsed.data.events.entries()) {
        const ik = idemHeader ? `${idemHeader}:${idx}` : null;
        if (event.type === "user.interrupt") {
          const row = appendEvent(sessionId, {
            type: "user.interrupt",
            payload: {},
            origin: "user",
            idempotencyKey: ik,
            processedAt: nowMs()
          });
          rows.push(row);
          sawInterrupt = true;
          continue;
        }
        if (event.type === "user.message") {
          const text = event.content.map((b) => b.text).join("");
          const row = appendEvent(sessionId, {
            type: "user.message",
            payload: { content: event.content },
            origin: "user",
            idempotencyKey: ik,
            processedAt: null
          });
          rows.push(row);
          const inp = { kind: "text", eventId: row.id, text };
          const currentStatus = getSessionRow(sessionId)?.status ?? "idle";
          if (currentStatus === "running" || sawInterrupt) {
            pushPendingUserInput({ sessionId, input: inp });
          } else {
            pendingForTurn.push(inp);
          }
          continue;
        }
        if (event.type === "user.custom_tool_result") {
          const row = appendEvent(sessionId, {
            type: "user.custom_tool_result",
            payload: {
              custom_tool_use_id: event.custom_tool_use_id,
              content: event.content
            },
            origin: "user",
            idempotencyKey: ik,
            processedAt: nowMs()
          });
          rows.push(row);
          const currentStatus = getSessionRow(sessionId)?.status ?? "idle";
          if (currentStatus === "running") {
            const { writeToolBridgeResponse } = await import("./sessions/driver.js");
            void writeToolBridgeResponse(
              sessionId,
              event.content
            ).catch((err) => {
              console.warn(`[events] writeToolBridgeResponse failed:`, err);
            });
          } else {
            const inp = {
              kind: "tool_result",
              eventId: row.id,
              custom_tool_use_id: event.custom_tool_use_id,
              content: event.content
            };
            pendingForTurn.push(inp);
          }
          continue;
        }
        if (event.type === "user.tool_confirmation") {
          const confirmResult = event.result ?? "allow";
          const row = appendEvent(sessionId, {
            type: "user.tool_confirmation",
            payload: {
              tool_use_id: event.tool_use_id ?? null,
              result: confirmResult,
              deny_message: event.deny_message ?? null
            },
            origin: "user",
            idempotencyKey: ik,
            processedAt: nowMs()
          });
          rows.push(row);
          void writePermissionResponse(
            sessionId,
            confirmResult,
            event.deny_message ?? void 0
          ).catch((err) => {
            console.warn(`[events] writePermissionResponse failed:`, err);
          });
          continue;
        }
        if (event.type === "user.define_outcome") {
          const { newId: genId } = await import("./util/ids.js");
          const outcomeId = genId("outc");
          let rubricText;
          if (typeof event.rubric === "string") {
            rubricText = event.rubric;
          } else if (event.rubric && event.rubric.type === "text") {
            rubricText = event.rubric.content;
          } else if (event.rubric && event.rubric.type === "file") {
            const { getFile: getFileRow } = await import("./db/files.js");
            const { readFile: readStoredFile } = await import("./files/storage.js");
            const fileRow = getFileRow(event.rubric.file_id);
            if (!fileRow) throw badRequest(`Rubric file not found: ${event.rubric.file_id}`);
            rubricText = readStoredFile(fileRow.storage_path).toString("utf-8");
          } else {
            rubricText = "";
          }
          const maxIterations = event.max_iterations ?? 3;
          const processedAt = nowMs();
          const outcomeData = {
            outcome_id: outcomeId,
            description: event.description,
            rubric: rubricText,
            max_iterations: maxIterations,
            grader_iteration: 0,
            status: "running"
          };
          setOutcomeCriteria(sessionId, outcomeData);
          const row = appendEvent(sessionId, {
            type: "user.define_outcome",
            payload: {
              outcome_id: outcomeId,
              description: event.description,
              rubric: rubricText,
              max_iterations: maxIterations,
              processed_at: processedAt
            },
            origin: "user",
            idempotencyKey: ik,
            processedAt
          });
          rows.push(row);
          const descRow = appendEvent(sessionId, {
            type: "user.message",
            payload: { content: [{ type: "text", text: event.description }] },
            origin: "user",
            processedAt: null
          });
          const inp = { kind: "text", eventId: descRow.id, text: event.description };
          const currentStatus = getSessionRow(sessionId)?.status ?? "idle";
          if (currentStatus === "running" || sawInterrupt) {
            pushPendingUserInput({ sessionId, input: inp });
          } else {
            pendingForTurn.push(inp);
          }
          continue;
        }
      }
      return { rows, pendingForTurn };
    });
    if (appended.pendingForTurn.length > 0) {
      const row = getSessionRow(sessionId);
      if (row) {
        const env = getEnvironment(row.environment_id);
        const canExecuteInline = !!getConfig().defaultProvider || !!env?.config?.provider;
        if (env?.config?.type === "self_hosted" && !canExecuteInline) {
          const { createWorkItem } = await import("./db/work.js");
          const { updateSessionStatus } = await import("./db/sessions.js");
          const inputsJson = JSON.stringify(appended.pendingForTurn);
          const envRow = getEnvironmentRow(row.environment_id);
          createWorkItem(row.environment_id, sessionId, {
            inputsJson,
            tenantId: envRow?.tenant_id ?? void 0
          });
          updateSessionStatus(sessionId, "running");
          appendEvent(sessionId, {
            type: "session.status_running",
            payload: {},
            origin: "server",
            processedAt: nowMs()
          });
        } else {
          void enqueueTurn(row.environment_id, () => runTurn(sessionId, appended.pendingForTurn)).catch(
            (err) => {
              console.error(`[events] enqueueTurn failed:`, err);
            }
          );
        }
      }
    }
    return jsonOk({ data: appended.rows.map(rowToManagedEvent) });
  });
}
function handleListEvents(request, sessionId) {
  return routeWrap(request, async ({ auth }) => {
    assertSessionTenant(auth, sessionId);
    if (isProxied(sessionId)) {
      const localSession = getSession(sessionId);
      if (!localSession) {
        const remoteId = resolveRemoteSessionId(sessionId);
        return forwardToAnthropic(request, `/v1/sessions/${remoteId}/events`);
      }
    }
    const session = getSession(sessionId);
    if (!session) throw notFound(`session ${sessionId} not found`);
    const url = new URL(request.url);
    const limit = Number(url.searchParams.get("limit") ?? "50");
    const order = url.searchParams.get("order") === "desc" ? "desc" : "asc";
    const afterSeq = Number(url.searchParams.get("after_seq") ?? url.searchParams.get("page") ?? "0");
    const rows = listEvents(sessionId, { limit, order, afterSeq });
    const data = rows.map(rowToManagedEvent);
    return paginatedOk(data, limit);
  });
}

export {
  activeTees,
  executeServerSideTool,
  handlePostEvents,
  handleListEvents
};
