{"version":3,"sources":["../src/detect.ts","../src/adapters/v1.ts","../src/adapters/v2.ts","../src/modules/logging.ts","../src/modules/runtime-versions.ts","../package.json","../src/engine/registry.ts","../src/modules/validation.ts","../src/modules/internal.ts","../src/modules/constants.ts","../src/modules/context-parameters.ts","../src/modules/handles.ts","../src/thirdparty/ksuid/index.js","../src/thirdparty/ksuid/base-convert-int-array.js","../src/thirdparty/ksuid/base62.js","../src/modules/tools.ts","../src/modules/handle-injection.ts","../src/engine/innerTap.ts","../src/engine/listWrap.ts","../src/engine/callWrap.ts","../src/modules/eventQueue.ts","../src/modules/session.ts","../src/modules/redaction.ts","../src/modules/pendingEvent.ts","../src/modules/sanitization.ts","../src/modules/truncation.ts","../src/modules/compatibility.ts","../src/modules/diagnostics.ts","../src/modules/backgroundTasks.ts","../src/modules/exceptions.ts","../src/modules/extra-projection.ts","../src/modules/mcp-sdk-compat.ts","../src/engine/registrationPatch.ts","../src/engine/index.ts","../src/modules/exporters/trace-context.ts","../src/modules/exporters/otlp.ts","../src/modules/exporters/datadog.ts","../src/modules/exporters/sentry.ts","../src/modules/exporters/posthog.ts","../src/modules/telemetry.ts","../src/types.ts","../src/index.ts"],"sourcesContent":["import { HighLevelMCPServerLike, MCPServerLike } from \"./types.js\";\n\nexport type SdkMajor = 1 | 2;\nexport type ServerFlavor = \"high\" | \"low\";\n\nexport interface Detection {\n  major: SdkMajor;\n  flavor: ServerFlavor;\n  lowLevel: MCPServerLike;\n  highLevel?: HighLevelMCPServerLike;\n  /** Raw feature-detection signals — logged for fleet-level change detection. */\n  signals: Record<string, boolean>;\n}\n\n/**\n * Per-object feature detection. No module resolution, no SDK imports:\n * the object in hand is the only evidence.\n *\n * v1 high-level: has .tool() (removed in v2).\n * v2 high-level: no .tool(), has registerTool().\n * v2 low-level:  has projectCallToolResult() (v2-only Server method) or the\n *                _negotiatedWireCodec internal; otherwise v1 low-level.\n */\n/**\n * Single source of truth for the probe list: both detection and the\n * shape-fingerprint beacon read the same signals, so they cannot drift.\n */\nfunction collectSignals(s: any): {\n  signals: Record<string, boolean>;\n  low: any;\n} {\n  const signals: Record<string, boolean> = {\n    hasServerProp: !!(s.server && typeof s.server === \"object\"),\n    hasTool: typeof s.tool === \"function\",\n    hasRegisterTool: typeof s.registerTool === \"function\",\n  };\n  const low = signals.hasServerProp ? s.server : s;\n  signals.hasSetRequestHandler = typeof low?.setRequestHandler === \"function\";\n  signals.hasRequestHandlersMap = low?._requestHandlers instanceof Map;\n  signals.hasProjectCallToolResult =\n    typeof low?.projectCallToolResult === \"function\";\n  signals.hasNegotiatedWireCodec =\n    typeof low?._negotiatedWireCodec === \"function\";\n  return { signals, low };\n}\n\nexport function detectServer(server: unknown): Detection | null {\n  if (!server || typeof server !== \"object\") return null;\n  const s = server as any;\n\n  const { signals, low } = collectSignals(s);\n\n  if (!signals.hasSetRequestHandler || !signals.hasRequestHandlersMap) {\n    return null;\n  }\n\n  const flavor: ServerFlavor = signals.hasServerProp ? \"high\" : \"low\";\n  let major: SdkMajor;\n  if (flavor === \"high\") {\n    if (signals.hasTool) major = 1;\n    else if (signals.hasRegisterTool) major = 2;\n    else return null;\n  } else {\n    major =\n      signals.hasProjectCallToolResult || signals.hasNegotiatedWireCodec\n        ? 2\n        : 1;\n  }\n\n  return {\n    major,\n    flavor,\n    lowLevel: low as MCPServerLike,\n    highLevel: flavor === \"high\" ? (s as HighLevelMCPServerLike) : undefined,\n    signals,\n  };\n}\n\nexport function describeSignals(signals: Record<string, boolean>): string {\n  return Object.entries(signals)\n    .filter(([, v]) => v)\n    .map(([k]) => k)\n    .join(\",\");\n}\n\n/**\n * Shape-fingerprint for diagnostics: the exact signals detection computed,\n * rendered for the log. Emitted when a server shape is unrecognized so a\n * fleet-level \"new SDK shape appeared\" change is visible in the beacon\n * stream. Empty string when the input is not an object.\n */\nexport function fingerprintServerShape(server: unknown): string {\n  if (!server || typeof server !== \"object\") return \"\";\n  return describeSignals(collectSignals(server as any).signals);\n}\n","import { VersionAdapter } from \"../engine/registry.js\";\n\n/**\n * v1 (@modelcontextprotocol/sdk): McpServer dispatch reads tool.handler\n * (SDK 1.24+) or tool.callback (≤1.23) live from the registry entry.\n */\nexport const v1Adapter: VersionAdapter = {\n  major: 1,\n  tapKeys: [\"handler\", \"callback\"],\n};\n","import { VersionAdapter } from \"../engine/registry.js\";\n\n/**\n * v2 (@modelcontextprotocol/server): McpServer dispatch invokes\n * tool.executor(args, ctx) — a closure capturing the handler at\n * registration. Wrapping handler/callback is a silent no-op on v2;\n * executor is the property read live at dispatch time.\n */\nexport const v2Adapter: VersionAdapter = {\n  major: 2,\n  tapKeys: [\"executor\"],\n};\n","import { createRequire } from \"module\";\nimport { getVersionLogPrefix } from \"./runtime-versions.js\";\n\n// Lazy-loaded module references for Node.js file logging\n// These are loaded dynamically to support edge environments (Cloudflare Workers, etc.)\nlet fsModule: typeof import(\"fs\") | null = null;\nlet logFilePath: string | null = null;\nlet initAttempted = false;\nlet useConsoleFallback = false;\n\nlet diagnosticsSink: ((entry: string) => void) | null = null;\n\nexport function setDiagnosticsSink(fn: ((entry: string) => void) | null): void {\n  diagnosticsSink = fn;\n}\n\nexport type LogTarget =\n  | { kind: \"file\"; fs: typeof import(\"fs\"); path: string }\n  | { kind: \"console\" }\n  | { kind: \"silent\" };\n\n/**\n * Decides where log lines go. Pure so the decision is testable:\n *\n * - `file`: Node-like runtime with a resolvable home directory.\n * - `console`: fs/os modules unavailable — an edge isolate (Workers), where\n *   console is the only sink and no stdio protocol channel exists.\n * - `silent`: a Node-like runtime whose home directory cannot be resolved\n *   (containers running an arbitrary UID with no passwd entry, HOME unset).\n *   Logging is dropped entirely rather than falling back to console:\n *   stdout IS the JSON-RPC wire for stdio-transport MCP servers, and one\n *   stray line per event would corrupt the protocol stream. The diagnostics\n *   sink still receives every entry.\n */\nexport function resolveLogTarget(\n  loadModules: () => {\n    fs: typeof import(\"fs\");\n    os: { homedir?: () => string | undefined };\n    path: { join: (...parts: string[]) => string };\n  },\n): LogTarget {\n  let mods;\n  try {\n    mods = loadModules();\n  } catch {\n    return { kind: \"console\" };\n  }\n  try {\n    const home = mods.os.homedir?.();\n    if (home) {\n      return {\n        kind: \"file\",\n        fs: mods.fs,\n        path: mods.path.join(home, \"agentcat.log\"),\n      };\n    }\n  } catch {\n    // homedir threw (ENOENT on no-passwd-entry containers) — silent below.\n  }\n  return { kind: \"silent\" };\n}\n\n/**\n * Attempts to initialize Node.js file logging.\n */\nfunction tryInitSync(): void {\n  if (initAttempted) return;\n  initAttempted = true;\n\n  const target = resolveLogTarget(() => {\n    // Use createRequire for ESM compatibility\n    // Works in Node.js ESM/CJS, throws in Workers/edge environments\n    const require = createRequire(import.meta.url);\n    return { fs: require(\"fs\"), os: require(\"os\"), path: require(\"path\") };\n  });\n  if (target.kind === \"file\") {\n    fsModule = target.fs;\n    logFilePath = target.path;\n  } else if (target.kind === \"console\") {\n    useConsoleFallback = true;\n  }\n  // \"silent\": all state stays null — writeToLog drops messages after the\n  // diagnostics tee.\n}\n\nexport function writeToLog(message: string): void {\n  tryInitSync();\n\n  const timestamp = new Date().toISOString();\n  const logEntry = `[${timestamp}] ${getVersionLogPrefix()} ${message}`;\n\n  // Tee to diagnostics if registered. Must never break logging.\n  try {\n    diagnosticsSink?.(logEntry);\n  } catch {\n    // diagnostics must never break logging\n  }\n\n  if (useConsoleFallback) {\n    console.log(`[agentcat] ${logEntry}`);\n    return;\n  }\n\n  // Node.js environment: write to file\n  if (!logFilePath || !fsModule) {\n    return;\n  }\n\n  try {\n    if (!fsModule.existsSync(logFilePath)) {\n      fsModule.writeFileSync(logFilePath, logEntry + \"\\n\");\n    } else {\n      fsModule.appendFileSync(logFilePath, logEntry + \"\\n\");\n    }\n  } catch {\n    // Silently fail to avoid breaking the server\n  }\n}\n","// src/modules/runtime-versions.ts\nimport { createRequire } from \"module\";\nimport packageJson from \"../../package.json\" with { type: \"json\" };\n\nexport interface RuntimeVersions {\n  sdk: string;\n  node: string | null;\n  mcpV1: string | null;\n  mcpV2: string | null;\n}\n\nexport function loadNodeModule<T>(name: string): T | null {\n  try {\n    return createRequire(import.meta.url)(name) as T;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Reads an installed package's version even when its exports map seals\n * \"./package.json\" (the v2 MCP packages do): resolve the entry module,\n * then walk up the real directory tree to the package manifest.\n */\nexport function readInstalledPackageVersion(name: string): string | null {\n  const direct = loadNodeModule<{ version?: string }>(`${name}/package.json`);\n  if (direct?.version) return direct.version;\n  try {\n    const req = createRequire(import.meta.url);\n    const path = loadNodeModule<typeof import(\"path\")>(\"path\");\n    const fs = loadNodeModule<typeof import(\"fs\")>(\"fs\");\n    if (!path || !fs) return null;\n    // Anchor on the package entry; some packages (e.g. v1 SDK >= 1.30) have\n    // no root \".\" export, but do export \"./package.json\" (as a dist stub) —\n    // its dirname is an equally valid starting point for the walk-up.\n    let anchor: string;\n    try {\n      anchor = req.resolve(name);\n    } catch {\n      anchor = req.resolve(`${name}/package.json`);\n    }\n    let dir = path.dirname(anchor);\n    for (let i = 0; i < 6; i++) {\n      const candidate = path.join(dir, \"package.json\");\n      try {\n        if (fs.existsSync(candidate)) {\n          const pkg = JSON.parse(fs.readFileSync(candidate, \"utf8\"));\n          if (pkg?.name === name) return pkg.version ?? null;\n        }\n      } catch {\n        // malformed or unreadable manifest at this level; keep climbing\n      }\n      const parent = path.dirname(dir);\n      if (parent === dir) break;\n      dir = parent;\n    }\n  } catch {\n    // best-effort\n  }\n  return null;\n}\n\n// Resolved once per process: MCP resolution walks the filesystem, and\n// writeToLog stamps every line, so this must not re-run per call.\nlet cachedVersions: RuntimeVersions | null = null;\nlet cachedPrefix: string | null = null;\n\n// workerd cannot resolve node_modules; attempting it there makes test pools\n// and dev tooling log loud module-resolution failures. Cloudflare documents\n// this userAgent value as the supported runtime detection.\nfunction isCloudflareWorkers(): boolean {\n  try {\n    const nav = (globalThis as { navigator?: { userAgent?: string } })\n      .navigator;\n    return nav?.userAgent === \"Cloudflare-Workers\";\n  } catch {\n    return false;\n  }\n}\n\nexport function getRuntimeVersions(): RuntimeVersions {\n  if (cachedVersions) return cachedVersions;\n  let node: string | null = null;\n  try {\n    node = globalThis.process?.version ?? null;\n  } catch {\n    node = null;\n  }\n  const resolvePackages = !isCloudflareWorkers();\n  cachedVersions = {\n    sdk: packageJson.version,\n    node,\n    mcpV1: resolvePackages\n      ? readInstalledPackageVersion(\"@modelcontextprotocol/sdk\")\n      : null,\n    mcpV2: resolvePackages\n      ? readInstalledPackageVersion(\"@modelcontextprotocol/server\")\n      : null,\n  };\n  return cachedVersions;\n}\n\n/**\n * \"[sdk=… node=… mcp=…( mcp2=…)]\" — stamped onto every log line so a single\n * pasted line identifies the SDK, runtime, and MCP SDK that produced it.\n * Never throws: writeToLog must stay safe on edge runtimes.\n */\nexport function getVersionLogPrefix(): string {\n  if (cachedPrefix) return cachedPrefix;\n  try {\n    const v = getRuntimeVersions();\n    const parts = [`sdk=${v.sdk}`, `node=${v.node ?? \"unknown\"}`];\n    if (v.mcpV1) parts.push(`mcp=${v.mcpV1}`);\n    if (v.mcpV2) parts.push(`mcp2=${v.mcpV2}`);\n    if (!v.mcpV1 && !v.mcpV2) parts.push(\"mcp=unknown\");\n    cachedPrefix = `[${parts.join(\" \")}]`;\n  } catch {\n    cachedPrefix = \"[sdk=unknown node=unknown mcp=unknown]\";\n  }\n  return cachedPrefix;\n}\n\nexport function _resetVersionCacheForTest(): void {\n  cachedVersions = null;\n  cachedPrefix = null;\n}\n","{\n  \"name\": \"agentcat\",\n  \"version\": \"2.1.0\",\n  \"description\": \"Analytics tool for MCP (Model Context Protocol) servers and AI agents - tracks tool usage patterns and provides insights\",\n  \"type\": \"module\",\n  \"main\": \"dist/index.cjs\",\n  \"module\": \"dist/index.mjs\",\n  \"types\": \"dist/index.d.ts\",\n  \"sideEffects\": false,\n  \"engines\": {\n    \"node\": \">=20\"\n  },\n  \"files\": [\n    \"dist\",\n    \"CONTRIBUTING.md\",\n    \"MIGRATION.md\"\n  ],\n  \"exports\": {\n    \".\": {\n      \"workerd\": \"./dist/index.workerd.mjs\",\n      \"import\": {\n        \"types\": \"./dist/index.d.ts\",\n        \"default\": \"./dist/index.mjs\"\n      },\n      \"require\": {\n        \"types\": \"./dist/index.d.cts\",\n        \"default\": \"./dist/index.cjs\"\n      }\n    }\n  },\n  \"scripts\": {\n    \"build\": \"tsup\",\n    \"dev\": \"tsup --watch\",\n    \"test\": \"pnpm run test:v1 && pnpm run test:v2\",\n    \"test:v1\": \"vitest run --project v1\",\n    \"test:v2\": \"vitest run --project v2 --passWithNoTests\",\n    \"test:e2e:http\": \"vitest run --project e2e-http\",\n    \"test:workers\": \"pnpm run build && vitest run --config vitest.workers.config.ts\",\n    \"test:watch\": \"vitest --project v1\",\n    \"test:compatibility\": \"vitest run --project v1 src/tests/mcp-version-compatibility.test.ts\",\n    \"test:esm-consume\": \"vitest run --project v1 src/tests/esm-consumer.test.ts\",\n    \"test:coverage\": \"vitest run --coverage\",\n    \"lint\": \"eslint src/\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"prepack\": \"pnpm run build\",\n    \"prepare\": \"husky\",\n    \"prepublishOnly\": \"pnpm run build && pnpm run test && pnpm run lint && pnpm run typecheck\"\n  },\n  \"keywords\": [\n    \"ai\",\n    \"authentication\",\n    \"mcp\",\n    \"observability\",\n    \"ai-agents\",\n    \"ai-platform\",\n    \"ai-agent\",\n    \"mcps\",\n    \"aiagents\",\n    \"ai-agent-tools\",\n    \"mcp-servers\",\n    \"mcp-server\",\n    \"mcp-tools\",\n    \"agent-runtime\",\n    \"mcp-framework\",\n    \"mcp-analytics\",\n    \"agentcat\",\n    \"agentcat-analytics\"\n  ],\n  \"author\": \"AgentCat, Inc.\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/agentcathq/agentcat-typescript-sdk.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/agentcathq/agentcat-typescript-sdk/issues\"\n  },\n  \"homepage\": \"https://github.com/agentcathq/agentcat-typescript-sdk#readme\",\n  \"packageManager\": \"pnpm@10.11.0\",\n  \"devDependencies\": {\n    \"@cloudflare/vitest-pool-workers\": \"^0.19.0\",\n    \"@cloudflare/workers-types\": \"^5.20260729.1\",\n    \"@modelcontextprotocol/client\": \"^2.0.0\",\n    \"@modelcontextprotocol/node\": \"^2.0.0\",\n    \"@modelcontextprotocol/sdk\": \"~1.30.0\",\n    \"@modelcontextprotocol/server\": \"^2.0.0\",\n    \"@types/node\": \"^22.15.21\",\n    \"@types/uuid\": \"^11.0.0\",\n    \"@typescript-eslint/eslint-plugin\": \"^8.32.1\",\n    \"@typescript-eslint/parser\": \"^8.32.1\",\n    \"@vitest/coverage-v8\": \"^4.0.14\",\n    \"@vitest/ui\": \"^4.0.14\",\n    \"eslint\": \"^9.39.1\",\n    \"husky\": \"^9.1.7\",\n    \"lint-staged\": \"^16.1.0\",\n    \"prettier\": \"^3.5.3\",\n    \"tsup\": \"^8.5.0\",\n    \"typescript\": \"^5.8.3\",\n    \"uuid\": \"^14.0.0\",\n    \"vitest\": \"^4.0.14\",\n    \"zod\": \"^3.25\",\n    \"zod4\": \"npm:zod@^4.2.0\"\n  },\n  \"peerDependencies\": {\n    \"@modelcontextprotocol/sdk\": \">=1.11 <2\",\n    \"@modelcontextprotocol/server\": \">=2.0.0 <3\"\n  },\n  \"peerDependenciesMeta\": {\n    \"@modelcontextprotocol/sdk\": {\n      \"optional\": true\n    },\n    \"@modelcontextprotocol/server\": {\n      \"optional\": true\n    }\n  },\n  \"lint-staged\": {\n    \"*.{ts,js}\": [\n      \"eslint --fix\",\n      \"prettier --write\"\n    ],\n    \"*.{json,md,yml,yaml}\": [\n      \"prettier --write\"\n    ]\n  },\n  \"pnpm\": {\n    \"overrides\": {\n      \"js-yaml\": \">=4.1.1\",\n      \"vite\": \">=7.3.5\",\n      \"body-parser\": \">=2.2.1\",\n      \"brace-expansion\": \"2.1.2\",\n      \"undici\": \">=7.29.0 <8\"\n    },\n    \"overridesComments\": {\n      \"js-yaml\": \"Fixes GHSA-mh29-5h37-fv8m (prototype pollution in merge) - via eslint\",\n      \"vite\": \"Fixes GHSA-fx2h-pf6j-xcff, GHSA-v2wj-q39q-566r, GHSA-p9ff-h696-f583 (server.fs.deny bypasses, dev server file read) and earlier vite security issues - via vitest\",\n      \"body-parser\": \"Fixes GHSA-wqch-xfxh-vrr4 (DoS via url encoding) - via @modelcontextprotocol/sdk\",\n      \"brace-expansion\": \"Fixes GHSA-v6h2-p8h4-qcjw (ReDoS vulnerability) and GHSA-3jxr-9vmj-r5cp (exponential expansion DoS) - via eslint\",\n      \"undici\": \"Fixes GHSA-4cwx-7wf7-3272 (cache poisoning info disclosure) - miniflare pins undici exactly, capped <8 to stay on its undici 7 line\"\n    }\n  },\n  \"dependencies\": {\n    \"agentcat-api\": \"1.0.1\"\n  }\n}\n","import { HighLevelMCPServerLike } from \"../types.js\";\nimport { writeToLog } from \"../modules/logging.js\";\n\n/** toolName -> names AgentCat actually injected into that tool's schema. */\nexport type InjectedParamsRegistry = Map<string, Set<string>>;\n\nconst registries = new WeakMap<object, InjectedParamsRegistry>();\n\nexport function setInjectedParamsRegistry(\n  server: object,\n  registry: InjectedParamsRegistry,\n): void {\n  registries.set(server, registry);\n}\n\nexport function getInjectedParamsRegistry(\n  server: object,\n): InjectedParamsRegistry | undefined {\n  return registries.get(server);\n}\n\n/** toolName set: tools whose declared outputSchema received mcp_session. */\nexport type OutputInjectionRegistry = Set<string>;\n\nconst outputRegistries = new WeakMap<object, OutputInjectionRegistry>();\n\nexport function setOutputInjectionRegistry(\n  server: object,\n  registry: OutputInjectionRegistry,\n): void {\n  outputRegistries.set(server, registry);\n}\n\nexport function getOutputInjectionRegistry(\n  server: object,\n): OutputInjectionRegistry | undefined {\n  return outputRegistries.get(server);\n}\n\n/** Tool names whose session_id collision has already been reported. */\nconst reportedConflicts = new WeakMap<object, Set<string>>();\n\nexport function getReportedConflicts(key: object): Set<string> {\n  let set = reportedConflicts.get(key);\n  if (!set) {\n    set = new Set<string>();\n    reportedConflicts.set(key, set);\n  }\n  return set;\n}\n\n/**\n * Tool names whose input schema declares `session_id` itself — the customer's\n * parameter, never ours to read. This is the positive signal for ownership:\n * \"we recorded an injection\" would misclassify every tool injection skipped\n * for schema shape (oneOf/allOf/anyOf), which has no injection record but no\n * customer `session_id` either. Membership only ever grows, so a tool that\n * once declared the name stays foreign until the process restarts; the\n * conservative direction, since the alternative is adopting a value that is\n * not ours.\n */\nconst declaredSessionParams = new WeakMap<object, Set<string>>();\n\nexport function getDeclaredSessionParams(key: object): Set<string> {\n  let set = declaredSessionParams.get(key);\n  if (!set) {\n    set = new Set<string>();\n    declaredSessionParams.set(key, set);\n  }\n  return set;\n}\n\n/**\n * Marks that this server registered its own get_more_tools tool while\n * enableReportMissing is on. Dispatch still answers with AgentCat's canned\n * response (report-missing keeps working), but the shadowing must be\n * discoverable rather than silent — warned once per tracking-data lifetime.\n */\nconst customerOwnedReportMissing = new WeakSet<object>();\n\nexport function recordCustomerOwnedReportMissing(key: object): void {\n  if (customerOwnedReportMissing.has(key)) return;\n  customerOwnedReportMissing.add(key);\n  writeToLog(\n    `WARN: This server registers its own \"get_more_tools\" tool, which is shadowed by AgentCat's report-missing tool: calls to it are answered by AgentCat and never reach your handler. Rename your tool, or set enableReportMissing: false to keep yours reachable.`,\n  );\n}\n\n// ── Engine state ────────────────────────────────────────────────────────────\n\nexport interface VersionAdapter {\n  major: 1 | 2;\n  /** Tool-registry property that dispatch actually invokes; first present wins. */\n  tapKeys: readonly string[];\n}\n\nexport type AnyHandler = (request: any, extra?: any) => Promise<any>;\n\nexport interface EngineState {\n  adapter: VersionAdapter;\n  highLevel?: HighLevelMCPServerLike;\n  /** Stored original handlers — each wrapper closes over the one it wrapped. */\n  originalList?: AnyHandler;\n  originalCall?: AnyHandler;\n  /** Our current wrappers, for idempotent re-arm checks. */\n  listWrapper?: AnyHandler;\n  callWrapper?: AnyHandler;\n}\n\nconst engineStates = new WeakMap<object, EngineState>();\n\nexport function initEngineState(server: object, state: EngineState): void {\n  engineStates.set(server, state);\n}\n\nexport function getEngineState(server: object): EngineState | undefined {\n  return engineStates.get(server);\n}\n","import { writeToLog } from \"./logging.js\";\n\nconst TAG_KEY_REGEX = /^[a-zA-Z0-9$_.:\\- ]+$/;\nconst MAX_TAG_KEY_LENGTH = 32;\nconst MAX_TAG_VALUE_LENGTH = 200;\nconst MAX_TAG_ENTRIES = 50;\n\n/**\n * Validates and filters a tags object against AgentCat tag constraints.\n * Invalid entries are logged as warnings and dropped.\n * Returns null if no valid entries remain.\n */\nexport function validateTags(\n  tags: Record<string, string>,\n): Record<string, string> | null {\n  const entries = Object.entries(tags);\n\n  if (entries.length === 0) {\n    return null;\n  }\n\n  const valid: [string, string][] = [];\n\n  for (const [key, value] of entries) {\n    // Key validation\n    if (typeof key !== \"string\" || !TAG_KEY_REGEX.test(key)) {\n      writeToLog(\n        `Dropping invalid tag: \"${String(key)}\" — key contains invalid characters or is empty`,\n      );\n      continue;\n    }\n\n    if (key.length > MAX_TAG_KEY_LENGTH) {\n      writeToLog(\n        `Dropping invalid tag: \"${key}\" — key exceeds max length of ${MAX_TAG_KEY_LENGTH}`,\n      );\n      continue;\n    }\n\n    // Value validation\n    if (typeof value !== \"string\") {\n      writeToLog(\n        `Dropping invalid tag: \"${key}\" — non-string value (got ${typeof value})`,\n      );\n      continue;\n    }\n\n    if (value.length > MAX_TAG_VALUE_LENGTH) {\n      writeToLog(\n        `Dropping invalid tag: \"${key}\" — value exceeds max length of ${MAX_TAG_VALUE_LENGTH}`,\n      );\n      continue;\n    }\n\n    if (value.includes(\"\\n\")) {\n      writeToLog(\n        `Dropping invalid tag: \"${key}\" — value contains newline character`,\n      );\n      continue;\n    }\n\n    valid.push([key, value]);\n  }\n\n  if (valid.length === 0) {\n    return null;\n  }\n\n  if (valid.length > MAX_TAG_ENTRIES) {\n    const dropped = valid.length - MAX_TAG_ENTRIES;\n    writeToLog(\n      `Dropping ${dropped} tag(s) — exceeds maximum of ${MAX_TAG_ENTRIES} entries per event`,\n    );\n    valid.length = MAX_TAG_ENTRIES;\n  }\n\n  return Object.fromEntries(valid);\n}\n","import {\n  AgentCatData,\n  MCPServerLike,\n  UserIdentity,\n  CompatibleRequestHandlerExtra,\n} from \"../types.js\";\nimport { writeToLog } from \"./logging.js\";\nimport { validateTags } from \"./validation.js\";\n\n// Internal tracking storage\nconst _serverTracking = new WeakMap<MCPServerLike, AgentCatData>();\n\nexport function getServerTrackingData(\n  server: MCPServerLike,\n): AgentCatData | undefined {\n  return _serverTracking.get(server);\n}\n\nexport function setServerTrackingData(\n  server: MCPServerLike,\n  data: AgentCatData,\n): void {\n  _serverTracking.set(server, data);\n}\n\n/**\n * Resolves the eventTags callback, validates the result, and returns validated tags.\n * Returns null if no callback configured, callback returns nullish, or callback throws.\n */\nexport async function resolveEventTags(\n  data: AgentCatData,\n  request: any,\n  extra?: CompatibleRequestHandlerExtra,\n): Promise<Record<string, string> | null> {\n  if (!data.options.eventTags) return null;\n  try {\n    const raw = (await data.options.eventTags(request, extra)) ?? null;\n    if (!raw) return null;\n    return validateTags(raw);\n  } catch (e) {\n    writeToLog(`eventTags callback error: ${e}`);\n    return null;\n  }\n}\n\n/**\n * Resolves the eventProperties callback and returns the result.\n * Returns null if no callback configured, callback returns nullish, or callback throws.\n */\nexport async function resolveEventProperties(\n  data: AgentCatData,\n  request: any,\n  extra?: CompatibleRequestHandlerExtra,\n): Promise<Record<string, any> | null> {\n  if (!data.options.eventProperties) return null;\n  try {\n    return (await data.options.eventProperties(request, extra)) ?? null;\n  } catch (e) {\n    writeToLog(`eventProperties callback error: ${e}`);\n    return null;\n  }\n}\n\n/**\n * Runs the customer's identify callback for this request and returns the\n * result. No cache, no identify event, no server mutation — the caller stamps\n * the identity onto the event it is building. Never throws.\n */\nexport async function resolveIdentity(\n  data: AgentCatData,\n  request: any,\n  extra?: CompatibleRequestHandlerExtra,\n): Promise<UserIdentity | null> {\n  if (!data.options.identify) return null;\n  try {\n    return (await data.options.identify(request, extra)) ?? null;\n  } catch (error) {\n    writeToLog(`Error: identify callback threw - ${error}`);\n    return null;\n  }\n}\n","// AgentCat Settings\nexport const DEFAULT_CONTEXT_PARAMETER_DESCRIPTION = `Explain why you are calling this tool and how it fits into the user's overall goal. This parameter is used for analytics and user intent tracking. YOU MUST provide 15-25 words (count carefully). NEVER use first person ('I', 'we', 'you') - maintain third-person perspective. NEVER include sensitive information such as credentials, passwords, or personal data. Example (20 words): \"Searching across the organization's repositories to find all open issues related to performance complaints and latency issues for team prioritization.\"`;\nexport const AGENTCAT_CUSTOM_EVENT_TYPE = \"agentcat:custom\";\nexport const AGENTCAT_SOURCE = \"agentcat\";\n\nexport const DIAGNOSTICS_SCOPE_NAME = \"agentcat-diagnostics\";\nexport const DEFAULT_DIAGNOSTICS_ENDPOINT = \"https://otel.agentcat.com\";\n\n// Public shared ingestion key for SDK diagnostics. NOT a secret — it ships in the\n// published package. It exists to deter drive-by traffic to the collector, paired with\n// a server-side rate limit. Override with DIAGNOSTICS_TOKEN to point at a\n// self-hosted collector. Must match the collector's bearertokenauth token.\nexport const DEFAULT_DIAGNOSTICS_TOKEN =\n  \"dgk_sdk_diag_3f9a2c7e1b8d4065af2e9c1d7b6a4f80\";\n\n// ── Explicit handles: agent-facing copy ─────────────────────────────────────\n// This copy is read by agents, not humans — its exact wording drives whether\n// agents echo handles back correctly. Do not reword casually.\n\nexport const SESSION_ID_PARAM_DESCRIPTION =\n  \"Session continuity handle, one of two values: the ses_ ID issued for the task underway, or start. This server cannot link your calls between requests on its own, so session continuity travels in this parameter instead. If you were handed a session_id for this task — for example by the agent that spawned you — send that exact value from your first call. Otherwise send start on your first call; the server will issue an opaque correlation ID in the mcp_session field of the result, or in a text block at the start of the result beginning [session_id issued. Then send that exact ses_ value on every later call and hand it to any subagents working the same task. start always begins a new, unrelated task — never send it mid-task. If you send a value this server does not recognize, the result reports it: mcp_session.status of unrecognized, or a text block beginning [session_id unrecognized; re-send the ID issued for this task, or start if none was issued yet. Never invent a ses_ value.\";\n\n// Machine-enforceable value contract for the injected session_id parameter,\n// advertised as the JSON Schema \"pattern\" of the injected property: the start\n// sentinel or a ses_ KSUID. Intentionally equal to the isValidSessionId shape\n// with the start alternative added — do not loosen or widen it.\nexport const SESSION_ID_PARAM_PATTERN = \"^(start|ses_[0-9A-Za-z]{27})$\";\n\n// Sentinel an agent sends as session_id to explicitly begin a new, unrelated\n// task. Compared case-insensitively after trimming, and resolved exactly like\n// an omitted session_id: minted path, status issued, minted text block.\nexport const SESSION_START_SENTINEL = \"start\";\n\nexport const AGENT_ID_PARAM_DESCRIPTION =\n  \"Agent identity handle, required on every call including your first. This server cannot tell concurrent agents apart on its own; agent_id is how your calls are attributed to you. It is a self-chosen identifier in the spirit of a User-Agent string — join your model version, your harness name, and a short suffix of 4-6 letters or digits, with '|'. Example: opus-4.80-1m|claude-code|k3n9x. Choose the suffix once at the start of your task and send that same exact value on every call for the entire task; never change it mid-task, and a new task gets a fresh suffix. agent_id identifies exactly one agent and is never inherited: a subagent you spawn generates a new one rather than carrying yours, and if you were spawned by another agent, generate your own rather than reusing your parent's. A call without agent_id cannot be attributed to you.\";\n\n// Issuance and unrecognized-value text blocks, prepended as the first content\n// element so the id survives client-side truncation of long results.\nexport const MINT_BACK_HEADER_ISSUED =\n  \"[session_id issued — see this tool's session_id parameter description]\";\n\nexport const MINT_BACK_ISSUED_BODY =\n  \"This is the first-call issuance described in this tool's session_id parameter description.\";\n\nexport const MINT_BACK_HEADER_UNRECOGNIZED =\n  \"[session_id unrecognized — see this tool's session_id parameter description]\";\n\nexport const MINT_BACK_UNRECOGNIZED_BODY =\n  \"The value sent was not issued by this server. Re-send the session_id issued earlier for this task; if none was issued yet, send start and one will be issued.\";\n\nexport const mintBackSessionLine = (sessionId: string): string =>\n  `session_id: ${sessionId}`;\n\n// ── Structured mint-back: mirrored into structuredContent ───────────────────\n// Wire key for the SDK-authored field injected into declared outputSchemas\n// and mirrored as the first key of structuredContent whenever there is handle\n// state to report.\nexport const MCP_SESSION_KEY = \"mcp_session\";\n\nexport const MCP_SESSION_FIELD_DESCRIPTION =\n  \"Session continuity and agent attribution state for this task, returned on completed responses that carry structured output. This server cannot link your calls between requests on its own, so session continuity travels here instead.\";\n\nexport const MCP_SESSION_FIELD_DESCRIPTION_HOOK_MODE =\n  \"Agent attribution state for this task, returned on completed responses that carry structured output.\";\n\nexport const MCP_SESSION_SESSION_ID_DESCRIPTION =\n  \"Opaque correlation ID for this task, issued by this server. Use this as the session_id argument of every later call, and hand it to any subagents working the same task. Absent when status is unrecognized; no replacement is issued in that response — recovery is described under status.\";\n\nexport const MCP_SESSION_AGENT_ID_DESCRIPTION =\n  \"Present only when you sent agent_id on this call. Your agent_id, echoed as received. Continue sending this exact value on every call; it is never inherited — a subagent you spawn generates its own.\";\n\nexport const MCP_SESSION_STATUS_DESCRIPTION =\n  \"issued: first call of a task; the session_id above was just created. active: the session_id you sent was accepted; keep sending it. unrecognized: the value sent was not issued by this server — re-send the one issued earlier for this task; if none was issued yet, send start to be issued a new one.\";\n\n// ── Explicit handles: wire keys ─────────────────────────────────────────────\nexport const META_CLIENT_INFO_KEY = \"io.modelcontextprotocol/clientInfo\";\nexport const META_PROTOCOL_VERSION_KEY =\n  \"io.modelcontextprotocol/protocolVersion\";\n\nexport const AGENTCAT_TAG_AGENT_ID = \"agentcat_agent_id\";\nexport const AGENTCAT_TAG_SESSION_SOURCE = \"agentcat_session_id_source\";\nexport const AGENTCAT_TAG_AGENT_SOURCE = \"agentcat_agent_id_source\";\nexport const AGENTCAT_TAG_PROTOCOL_VERSION = \"agentcat_protocol_version\";\nexport const AGENTCAT_TAG_MRTR = \"agentcat_mrtr\";\n","import { RegisteredTool } from \"../types\";\nimport { DEFAULT_CONTEXT_PARAMETER_DESCRIPTION } from \"./constants\";\n// Type-only import: handle-injection.ts imports from tools.ts at runtime, so a\n// value import here would create a runtime cycle.\nimport type { InjectedParamsRegistry } from \"./handle-injection.js\";\nimport { writeToLog } from \"./logging.js\";\n\n/**\n * Adds a context parameter to a tool's JSON Schema.\n * This function is called AFTER the MCP SDK has converted Zod schemas to JSON Schema,\n * so we only need to handle JSON Schema format.\n *\n * Skips injection (with warning) for:\n * - Tools that already have a 'context' parameter\n * - Complex schemas (oneOf/allOf/anyOf) that can't safely have properties added\n * - Schemas with additionalProperties: false\n */\nexport function addContextParameterToTool(\n  tool: RegisteredTool,\n  customContextDescription?: string,\n  registry?: InjectedParamsRegistry,\n): RegisteredTool {\n  // Create a shallow copy of the tool to avoid modifying the original\n  const modifiedTool = { ...tool };\n  const toolName = (tool as any).name || \"unknown\";\n  const schema = modifiedTool.inputSchema as Record<string, any> | undefined;\n\n  // Check if tool already has context parameter - skip to avoid collision\n  if (schema?.properties?.context) {\n    writeToLog(\n      `WARN: Tool \"${toolName}\" already has 'context' parameter. Skipping context injection.`,\n    );\n    return modifiedTool;\n  }\n\n  // Skip complex schemas that can't safely have properties added at root level\n  if (schema?.oneOf || schema?.allOf || schema?.anyOf) {\n    writeToLog(\n      `WARN: Tool \"${toolName}\" has complex schema (oneOf/allOf/anyOf). Skipping context injection.`,\n    );\n    return modifiedTool;\n  }\n\n  // Note: If additionalProperties is false, we'll need to remove that constraint\n  // when adding context, otherwise the schema would be invalid. We handle this\n  // after the deep copy below.\n\n  if (!modifiedTool.inputSchema) {\n    modifiedTool.inputSchema = {\n      type: \"object\",\n      properties: {},\n      required: [],\n    };\n  }\n\n  const contextDescription =\n    customContextDescription || DEFAULT_CONTEXT_PARAMETER_DESCRIPTION;\n\n  // Deep copy the inputSchema to avoid mutations\n  modifiedTool.inputSchema = JSON.parse(\n    JSON.stringify(modifiedTool.inputSchema),\n  );\n\n  // Ensure properties object exists\n  if (!modifiedTool.inputSchema.properties) {\n    modifiedTool.inputSchema.properties = {};\n  }\n\n  // Handle additionalProperties: false - must remove this constraint since we're adding context\n  // The MCP SDK adds this constraint when converting Zod schemas to JSON Schema\n  if (modifiedTool.inputSchema.additionalProperties === false) {\n    delete modifiedTool.inputSchema.additionalProperties;\n  }\n\n  // Add context property\n  modifiedTool.inputSchema.properties.context = {\n    type: \"string\",\n    description: contextDescription,\n  };\n\n  if (registry) {\n    const existing = registry.get(toolName);\n    if (existing) existing.add(\"context\");\n    else registry.set(toolName, new Set([\"context\"]));\n  }\n\n  // Add context to required array\n  if (Array.isArray(modifiedTool.inputSchema.required)) {\n    if (!modifiedTool.inputSchema.required.includes(\"context\")) {\n      modifiedTool.inputSchema.required.push(\"context\");\n    }\n  } else {\n    modifiedTool.inputSchema.required = [\"context\"];\n  }\n\n  return modifiedTool;\n}\n\nexport function addContextParameterToTools(\n  tools: RegisteredTool[],\n  customContextDescription?: string,\n  registry?: InjectedParamsRegistry,\n): RegisteredTool[] {\n  return tools.map((tool) => {\n    // Skip get_more_tools - it has its own special context parameter\n    if ((tool as any)?.name === \"get_more_tools\") {\n      return tool;\n    }\n    try {\n      return addContextParameterToTool(\n        tool,\n        customContextDescription,\n        registry,\n      );\n    } catch (error) {\n      // One tool's schema must never poison the listing: serve it unmodified\n      // and roll back the registry record so stripping matches the schema.\n      const toolName = (tool as any)?.name || \"unknown\";\n      registry?.get(toolName)?.delete(\"context\");\n      writeToLog(\n        `WARN: Context injection failed for tool \"${toolName}\"; listing it unmodified - ${error}`,\n      );\n      return tool;\n    }\n  });\n}\n","import { createHash } from \"crypto\";\nimport KSUID from \"../thirdparty/ksuid/index.js\";\nimport {\n  MINT_BACK_HEADER_ISSUED,\n  MINT_BACK_ISSUED_BODY,\n  MINT_BACK_HEADER_UNRECOGNIZED,\n  MINT_BACK_UNRECOGNIZED_BODY,\n  mintBackSessionLine,\n  SESSION_START_SENTINEL,\n  MCP_SESSION_KEY,\n  AGENTCAT_TAG_AGENT_ID,\n  AGENTCAT_TAG_SESSION_SOURCE,\n  AGENTCAT_TAG_AGENT_SOURCE,\n  AGENTCAT_TAG_PROTOCOL_VERSION,\n} from \"./constants.js\";\nimport { AgentCatOptions, CompatibleRequestHandlerExtra } from \"../types.js\";\nimport { writeToLog } from \"./logging.js\";\n\nexport const SESSION_ID_PARAM = \"session_id\";\nexport const AGENT_ID_PARAM = \"agent_id\";\n\nexport function newSessionId(): string {\n  return KSUID.withPrefix(\"ses\").randomSync();\n}\n\n/**\n * Deterministically derives a Session ID from a customer-supplied identifier.\n * The same id + project always yields the same ses_ KSUID, across processes\n * and restarts.\n *\n * @param id - The customer-supplied identifier to derive from\n * @param projectId - Optional AgentCat project ID to include in the hash\n * @returns A KSUID with \"ses\" prefix derived deterministically from the inputs\n */\nexport function deriveSessionId(id: string, projectId?: string): string {\n  const input = projectId ? `${id}:${projectId}` : id;\n  const hash = createHash(\"sha256\").update(input).digest();\n\n  // Fixed epoch plus a hash-derived offset (max 1 year) keeps the timestamp\n  // deterministic while staying inside a valid KSUID range.\n  const EPOCH_2024 = new Date(\"2024-01-01T00:00:00Z\").getTime();\n  const timestampOffset = hash.readUInt32BE(0) % (365 * 24 * 60 * 60 * 1000);\n  const payload = hash.subarray(4, 20);\n\n  return KSUID.withPrefix(\"ses\").fromParts(\n    EPOCH_2024 + timestampOffset,\n    payload,\n  );\n}\n\n/**\n * Reads a supplied handle off tool-call arguments. Trimmed, non-empty strings\n * only; anything else counts as \"omitted\". Values are trusted verbatim — no\n * shape validation.\n *\n * @param args - The tool call arguments, of unknown shape\n * @param name - The argument name to read (SESSION_ID_PARAM or AGENT_ID_PARAM)\n * @returns The trimmed handle, or undefined when absent or not a usable string\n */\nexport function extractHandle(args: unknown, name: string): string | undefined {\n  if (!args || typeof args !== \"object\") return undefined;\n  const value = (args as Record<string, unknown>)[name];\n  if (typeof value !== \"string\") return undefined;\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * True only for a session ID this SDK issued. Both issuing paths —\n * newSessionId() and deriveSessionId() — satisfy this by construction, so a\n * value that fails was invented by the agent or belongs to someone else.\n */\nexport function isValidSessionId(value: string): boolean {\n  return /^ses_[0-9A-Za-z]{27}$/.test(value);\n}\n\nexport type SessionSource =\n  \"hook\" | \"supplied\" | \"minted\" | \"invalid\" | \"foreign\";\nexport type AgentSource = \"supplied\";\n\nexport interface HandleResolution {\n  sessionId: string;\n  sessionSource: SessionSource;\n  /** True when resolveSessionId is configured: no task prompting anywhere. */\n  hookMode: boolean;\n  agentId?: string;\n  agentSource?: AgentSource;\n}\n\n/**\n * Builds the issuance block for a task minted on this call, or the\n * unrecognized-value block when the agent sent a session_id this server never\n * issued. Returns null when nothing needs announcing. The block never appears\n * in hook mode — even when a hook-null forced a silent mint. agent_id is\n * self-chosen by the agent and never announced here.\n *\n * @param res - The resolved handles for this call\n * @returns The text block, or null when nothing needs saying\n */\nexport function buildMintBackText(res: HandleResolution): string | null {\n  if (res.hookMode) return null;\n  if (res.sessionSource === \"minted\") {\n    return [\n      MINT_BACK_HEADER_ISSUED,\n      mintBackSessionLine(res.sessionId),\n      MINT_BACK_ISSUED_BODY,\n    ].join(\"\\n\");\n  }\n  if (res.sessionSource === \"invalid\") {\n    return [MINT_BACK_HEADER_UNRECOGNIZED, MINT_BACK_UNRECOGNIZED_BODY].join(\n      \"\\n\",\n    );\n  }\n  return null;\n}\n\n/**\n * Prepends the mint-back block to a CallToolResult as the first content\n * element — IDs at the end of long responses can be truncated away by\n * clients. Applies to isError results too (the retry after an error must\n * carry the same task). Only requirement: an array `content`. Never mutates\n * the input.\n *\n * @param result - The tool result to prepend to\n * @param text - The mint-back block to prepend as a text content block\n * @returns A shallow copy carrying the extra block, or the input untouched\n */\nexport function appendMintBack(result: any, text: string): any {\n  if (!result || typeof result !== \"object\" || !Array.isArray(result.content)) {\n    return result;\n  }\n  return { ...result, content: [{ type: \"text\", text }, ...result.content] };\n}\n\nexport interface StructuredMintBack {\n  session_id?: string;\n  agent_id?: string;\n  status?: \"issued\" | \"active\" | \"unrecognized\";\n}\n\n/**\n * Builds the structured mint-back mirrored into structuredContent. Unlike\n * buildMintBackText (issuance announcements only), this is persistent handle\n * state, present on every response with something to report — supplied\n * handles are re-echoed, so an agent can re-read its own session_id/agent_id\n * mid-conversation. In prompted mode the session state is a machine-readable\n * status: \"issued\" (just created, session_id alongside), \"active\" (the value\n * sent was accepted, session_id alongside), or \"unrecognized\" (no session_id\n * — no replacement is issued). Handles the agent cannot echo are never named:\n * no session_id or status in hook mode, none for \"foreign\" (that parameter is\n * the customer's, not ours to speak about), and no agent_id when the agent\n * didn't supply one. Returns null when the payload would be empty.\n *\n * Suppression is per-handle, not per-response: on a foreign tool AgentCat\n * still injected agent_id, so that half stays ours to echo even though\n * session_id is not.\n *\n * @param res - The resolved handles for this call\n * @returns The structured mint-back payload, or null\n */\nexport function buildStructuredMintBack(\n  res: HandleResolution,\n): StructuredMintBack | null {\n  const sessionOurs = !res.hookMode && res.sessionSource !== \"foreign\";\n  const mint: StructuredMintBack = {};\n  if (sessionOurs && res.sessionSource !== \"invalid\") {\n    mint[SESSION_ID_PARAM] = res.sessionId;\n  }\n  if (res.agentId) mint[AGENT_ID_PARAM] = res.agentId;\n  if (sessionOurs) {\n    mint.status =\n      res.sessionSource === \"minted\"\n        ? \"issued\"\n        : res.sessionSource === \"invalid\"\n          ? \"unrecognized\"\n          : \"active\";\n  }\n  return Object.keys(mint).length > 0 ? mint : null;\n}\n\n/**\n * Mirrors the structured mint-back into result.structuredContent as its FIRST\n * key, so the handle state survives client-side truncation of long results.\n * Requires a plain-object structuredContent to extend; an already-present key\n * is customer data and always wins. Never mutates the input.\n *\n * @param result - The tool result to mirror into\n * @param mint - The structured mint-back payload\n * @returns A shallow copy carrying the field, or the input untouched\n */\nexport function mirrorStructuredMintBack(\n  result: any,\n  mint: StructuredMintBack,\n): any {\n  const sc = result?.structuredContent;\n  if (!sc || typeof sc !== \"object\" || Array.isArray(sc)) return result;\n  if (MCP_SESSION_KEY in sc) return result;\n  return {\n    ...result,\n    structuredContent: { [MCP_SESSION_KEY]: mint, ...sc },\n  };\n}\n\n/**\n * Builds the SDK-owned tags for a call. Applied AFTER validateTags(customerTags)\n * — these are exempt from the 50-tag cap.\n *\n * @param res - The resolved handles for this call\n * @param protocolVersion - Optional negotiated MCP protocol version\n * @returns The tag map to merge over customer tags\n */\nexport function buildHandleTags(\n  res: HandleResolution,\n  protocolVersion?: string,\n): Record<string, string> {\n  const tags: Record<string, string> = {\n    [AGENTCAT_TAG_SESSION_SOURCE]: res.sessionSource,\n  };\n  if (res.agentId && res.agentSource) {\n    // Tag channel contract: SDK tags bypass validateTags/redaction/truncation,\n    // so the tag copy is clamped (200 chars, newlines -> space). The handle\n    // itself (resolution, Event.sessionId) stays verbatim.\n    tags[AGENTCAT_TAG_AGENT_ID] = res.agentId\n      .replace(/[\\r\\n]/g, \" \")\n      .slice(0, 200);\n    tags[AGENTCAT_TAG_AGENT_SOURCE] = res.agentSource;\n  }\n  if (protocolVersion) tags[AGENTCAT_TAG_PROTOCOL_VERSION] = protocolVersion;\n  return tags;\n}\n\n/**\n * Resolves both handles for one request. Stateless: nothing is stored on the\n * server, so concurrent requests cannot clobber each other.\n *\n * @param options - The AgentCat options; resolveSessionId selects hook mode\n * @param projectId - Optional AgentCat project ID, used when deriving in hook mode\n * @param request - The MCP request whose arguments may carry supplied handles\n * @param extra - Optional MCP request handler extra, forwarded to the hook\n * @param sessionParamIsOurs - False when the tool declares its own session_id\n *   param (AgentCat never injected one), so nothing in the arguments is ours\n *   to read. Defaults to true.\n * @returns The resolved handles for this call\n */\nexport function resolveHandles(\n  options: AgentCatOptions,\n  projectId: string | undefined,\n  request: any,\n  extra?: CompatibleRequestHandlerExtra,\n  sessionParamIsOurs: boolean = true,\n): HandleResolution {\n  void projectId; // derivation moved to sessionFromHookValue (background)\n  void extra;\n  const args = request?.params?.arguments;\n  const hookMode = typeof options.resolveSessionId === \"function\";\n\n  let sessionId: string;\n  let sessionSource: SessionSource;\n\n  if (hookMode) {\n    // Provisional: the customer hook is fired by the caller and awaited only\n    // in the background event pipeline (sessionFromHookValue finalizes the\n    // id and source there). Every on-path consumer — buildMintBackText,\n    // buildStructuredMintBack — gates on hookMode alone, so provisional\n    // sessionId/sessionSource are wire-invisible.\n    sessionId = \"\";\n    sessionSource = \"hook\";\n  } else if (!sessionParamIsOurs) {\n    // The tool declares its own session_id. AgentCat never injected one here,\n    // so nothing in the arguments is ours to read. Sessionless until the\n    // customer adopts resolveSessionId.\n    sessionId = \"\";\n    sessionSource = \"foreign\";\n  } else {\n    // The start sentinel is checked before shape validation, and only here —\n    // on the path where the session param is ours. A foreign customer-owned\n    // value is never interpreted as a sentinel.\n    const supplied = extractHandle(args, SESSION_ID_PARAM);\n    if (supplied && supplied.toLowerCase() !== SESSION_START_SENTINEL) {\n      if (isValidSessionId(supplied)) {\n        sessionId = supplied;\n        sessionSource = \"supplied\";\n      } else {\n        // Not an ID this server issued. Publish sessionless rather than adopt\n        // it: Event.sessionId is exempt from both redaction hooks.\n        sessionId = \"\";\n        sessionSource = \"invalid\";\n      }\n    } else {\n      // Absent, empty, or the explicit start sentinel: begin a new task.\n      // Omission keeps minting so stale schemas and scripted callers that\n      // never learned the parameter cannot error.\n      sessionId = newSessionId();\n      sessionSource = \"minted\";\n    }\n  }\n\n  const resolution: HandleResolution = {\n    sessionId,\n    sessionSource,\n    hookMode,\n  };\n\n  // agent_id is self-chosen by the agent (schema-required when tracking is\n  // on). Soft enforcement: an omitted agent_id never rejects the call — the\n  // event is simply published without agent identity.\n  if (options.enableAgentTracking === true) {\n    const suppliedAgent = extractHandle(args, AGENT_ID_PARAM);\n    if (suppliedAgent) {\n      resolution.agentId = suppliedAgent;\n      resolution.agentSource = \"supplied\";\n    }\n  }\n\n  return resolution;\n}\n\n/**\n * Fires the customer's resolveSessionId hook, contained: a synchronous throw,\n * a rejection, or a nullish value all resolve to null (logged), and the\n * rejection handler is attached at creation so the returned promise can be\n * left un-awaited with no unhandled-rejection window. Never rejects.\n *\n * @param options - The AgentCat options; resolveSessionId must be configured\n * @param request - The MCP request, forwarded to the hook\n * @param extra - Optional MCP request handler extra, forwarded to the hook\n * @returns The hook's raw value, or null on any failure\n */\nexport function invokeSessionHook(\n  options: AgentCatOptions,\n  request: any,\n  extra?: CompatibleRequestHandlerExtra,\n): Promise<string | null> {\n  try {\n    return Promise.resolve(options.resolveSessionId!(request, extra)).then(\n      (value) => value ?? null,\n      (error) => {\n        writeToLog(`resolveSessionId hook error: ${error}`);\n        return null;\n      },\n    );\n  } catch (error) {\n    writeToLog(`resolveSessionId hook error: ${error}`);\n    return Promise.resolve(null);\n  }\n}\n\n/**\n * Finalizes a hook-mode session from the hook's raw value: a non-empty string\n * derives the deterministic session id; null (hook failure, timeout, or a\n * deliberate null return) mints silently — no parameter exists in hook mode,\n * so the agent can never learn a minted ID. One single-event task per null.\n *\n * @param hookValue - The settled resolveSessionId value\n * @param projectId - Optional AgentCat project ID, salt for derivation\n * @returns The final session id and its source\n */\nexport function sessionFromHookValue(\n  hookValue: string | null,\n  projectId?: string,\n): { sessionId: string; sessionSource: \"hook\" | \"minted\" } {\n  if (typeof hookValue === \"string\" && hookValue.trim().length > 0) {\n    return {\n      sessionId: deriveSessionId(hookValue.trim(), projectId),\n      sessionSource: \"hook\",\n    };\n  }\n  return { sessionId: newSessionId(), sessionSource: \"minted\" };\n}\n","\"use strict\";\nimport { randomBytes } from \"node:crypto\";\nimport { inspect } from \"node:util\";\nimport { promisify } from \"node:util\";\nimport * as base62 from \"./base62.js\";\n\nconst customInspectSymbol = inspect.custom;\n\nconst asyncRandomBytes = promisify(randomBytes);\n\n// KSUID's epoch starts more recently so that the 32-bit number space gives a\n// significantly higher useful lifetime of around 136 years from March 2014.\n// This number (14e11) was picked to be easy to remember.\nconst EPOCH_IN_MS = 14e11;\n\nconst MAX_TIME_IN_MS = 1e3 * (2 ** 32 - 1) + EPOCH_IN_MS;\n\n// Timestamp is a uint32\nconst TIMESTAMP_BYTE_LENGTH = 4;\n\n// Payload is 16-bytes\nconst PAYLOAD_BYTE_LENGTH = 16;\n\n// KSUIDs are 20 bytes when binary encoded\nconst BYTE_LENGTH = TIMESTAMP_BYTE_LENGTH + PAYLOAD_BYTE_LENGTH;\n\n// The length of a KSUID when string (base62) encoded\nconst STRING_ENCODED_LENGTH = 27;\n\nconst TIME_IN_MS_ASSERTION =\n  `Valid KSUID timestamps must be in milliseconds since ${new Date(0).toISOString()},\n  no earlier than ${new Date(EPOCH_IN_MS).toISOString()} and no later than ${new Date(MAX_TIME_IN_MS).toISOString()}\n`\n    .trim()\n    .replace(/(\\n|\\s)+/g, \" \")\n    .replace(/\\.000Z/g, \"Z\");\n\nconst VALID_ENCODING_ASSERTION = `Valid encoded KSUIDs are ${STRING_ENCODED_LENGTH} characters`;\n\nconst VALID_BUFFER_ASSERTION = `Valid KSUID buffers are ${BYTE_LENGTH} bytes`;\n\nconst VALID_PAYLOAD_ASSERTION = `Valid KSUID payloads are ${PAYLOAD_BYTE_LENGTH} bytes`;\n\nfunction fromParts(timeInMs, payload) {\n  const timestamp = Math.floor((timeInMs - EPOCH_IN_MS) / 1e3);\n  const timestampBuffer = Buffer.allocUnsafe(TIMESTAMP_BYTE_LENGTH);\n  timestampBuffer.writeUInt32BE(timestamp, 0);\n\n  return Buffer.concat([timestampBuffer, payload], BYTE_LENGTH);\n}\n\nconst bufferLookup = new WeakMap();\n\nclass KSUID {\n  constructor(buffer) {\n    if (!KSUID.isValid(buffer)) {\n      throw new TypeError(VALID_BUFFER_ASSERTION);\n    }\n\n    bufferLookup.set(this, buffer);\n    Object.defineProperty(this, \"buffer\", {\n      enumerable: true,\n      get() {\n        return Buffer.from(buffer);\n      },\n    });\n  }\n\n  get raw() {\n    return Buffer.from(bufferLookup.get(this).slice(0));\n  }\n\n  get date() {\n    return new Date(1e3 * this.timestamp + EPOCH_IN_MS);\n  }\n\n  get timestamp() {\n    return bufferLookup.get(this).readUInt32BE(0);\n  }\n\n  get payload() {\n    const payload = bufferLookup\n      .get(this)\n      .slice(TIMESTAMP_BYTE_LENGTH, BYTE_LENGTH);\n    return Buffer.from(payload);\n  }\n\n  get string() {\n    const encoded = base62.encode(\n      bufferLookup.get(this),\n      STRING_ENCODED_LENGTH,\n    );\n    return encoded.padStart(STRING_ENCODED_LENGTH, \"0\");\n  }\n\n  compare(other) {\n    if (!bufferLookup.has(other)) {\n      return 0;\n    }\n\n    return bufferLookup\n      .get(this)\n      .compare(bufferLookup.get(other), 0, BYTE_LENGTH);\n  }\n\n  equals(other) {\n    return (\n      this === other || (bufferLookup.has(other) && this.compare(other) === 0)\n    );\n  }\n\n  toString() {\n    return `${this[Symbol.toStringTag]} { ${this.string} }`;\n  }\n\n  toJSON() {\n    return this.string;\n  }\n\n  [customInspectSymbol]() {\n    return this.toString();\n  }\n\n  static async random(time = Date.now()) {\n    const payload = await asyncRandomBytes(PAYLOAD_BYTE_LENGTH);\n    return new KSUID(fromParts(Number(time), payload));\n  }\n\n  static randomSync(time = Date.now()) {\n    const payload = randomBytes(PAYLOAD_BYTE_LENGTH);\n    return new KSUID(fromParts(Number(time), payload));\n  }\n\n  static fromParts(timeInMs, payload) {\n    if (\n      !Number.isInteger(timeInMs) ||\n      timeInMs < EPOCH_IN_MS ||\n      timeInMs > MAX_TIME_IN_MS\n    ) {\n      throw new TypeError(TIME_IN_MS_ASSERTION);\n    }\n    if (\n      !Buffer.isBuffer(payload) ||\n      payload.byteLength !== PAYLOAD_BYTE_LENGTH\n    ) {\n      throw new TypeError(VALID_PAYLOAD_ASSERTION);\n    }\n\n    return new KSUID(fromParts(timeInMs, payload));\n  }\n\n  static isValid(buffer) {\n    return Buffer.isBuffer(buffer) && buffer.byteLength === BYTE_LENGTH;\n  }\n\n  static parse(string) {\n    if (string.length !== STRING_ENCODED_LENGTH) {\n      throw new TypeError(VALID_ENCODING_ASSERTION);\n    }\n\n    const decoded = base62.decode(string, BYTE_LENGTH);\n    if (decoded.byteLength === BYTE_LENGTH) {\n      return new KSUID(decoded);\n    }\n\n    const buffer = Buffer.allocUnsafe(BYTE_LENGTH);\n    const padEnd = BYTE_LENGTH - decoded.byteLength;\n    buffer.fill(0, 0, padEnd);\n    decoded.copy(buffer, padEnd);\n    return new KSUID(buffer);\n  }\n}\nObject.defineProperty(KSUID.prototype, Symbol.toStringTag, { value: \"KSUID\" });\n// A string-encoded maximum value for a KSUID\nObject.defineProperty(KSUID, \"MAX_STRING_ENCODED\", {\n  value: \"aWgEPTl1tmebfsQzFP4bxwgy80V\",\n});\n// A string-encoded minimum value for a KSUID\nObject.defineProperty(KSUID, \"MIN_STRING_ENCODED\", {\n  value: \"000000000000000000000000000\",\n});\n\n// Add prefix functionality\nKSUID.withPrefix = function (prefix) {\n  return {\n    random: async (time = Date.now()) => {\n      const ksuid = await KSUID.random(time);\n      return `${prefix}_${ksuid.string}`;\n    },\n    randomSync: (time = Date.now()) => {\n      const ksuid = KSUID.randomSync(time);\n      return `${prefix}_${ksuid.string}`;\n    },\n    fromParts: (timeInMs, payload) => {\n      const ksuid = KSUID.fromParts(timeInMs, payload);\n      return `${prefix}_${ksuid.string}`;\n    },\n  };\n};\n\nexport default KSUID;\n","\"use strict\";\n\nconst maxLength = (array, from, to) =>\n  Math.ceil((array.length * Math.log2(from)) / Math.log2(to));\n\nfunction baseConvertIntArray(array, { from, to, fixedLength = null }) {\n  const length =\n    fixedLength === null ? maxLength(array, from, to) : fixedLength;\n  const result = new Array(length);\n\n  // Each iteration prepends the resulting value, so start the offset at the end.\n  let offset = length;\n  let input = array;\n  while (input.length > 0) {\n    if (offset === 0) {\n      throw new RangeError(\n        `Fixed length of ${fixedLength} is too small, expected at least ${maxLength(array, from, to)}`,\n      );\n    }\n\n    const quotients = [];\n    let remainder = 0;\n\n    for (const digit of input) {\n      const acc = digit + remainder * from;\n      const q = Math.floor(acc / to);\n      remainder = acc % to;\n\n      if (quotients.length > 0 || q > 0) {\n        quotients.push(q);\n      }\n    }\n\n    result[--offset] = remainder;\n    input = quotients;\n  }\n\n  // Trim leading padding, unless length is fixed.\n  if (fixedLength === null) {\n    return offset > 0 ? result.slice(offset) : result;\n  }\n\n  // Fill in any holes in the result array.\n  while (offset > 0) {\n    result[--offset] = 0;\n  }\n  return result;\n}\nexport default baseConvertIntArray;\n","\"use strict\";\nimport baseConvertIntArray from \"./base-convert-int-array.js\";\n\nconst CHARS = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nfunction encode(buffer, fixedLength) {\n  return baseConvertIntArray(buffer, { from: 256, to: 62, fixedLength })\n    .map((value) => CHARS[value])\n    .join(\"\");\n}\n\nfunction decode(string, fixedLength) {\n  // Optimization from https://github.com/andrew/base62.js/pull/31.\n  const input = Array.from(string, (char) => {\n    const charCode = char.charCodeAt(0);\n    if (charCode < 58) return charCode - 48;\n    if (charCode < 91) return charCode - 55;\n    return charCode - 61;\n  });\n  return Buffer.from(\n    baseConvertIntArray(input, { from: 62, to: 256, fixedLength }),\n  );\n}\nexport { encode, decode };\n","import { writeToLog } from \"./logging.js\";\n\nexport const GET_MORE_TOOLS_NAME = \"get_more_tools\" as const;\n\nexport function getReportMissingToolDescriptor() {\n  return {\n    name: GET_MORE_TOOLS_NAME,\n    description:\n      \"Check for additional tools whenever your task might benefit from specialized capabilities - even if existing tools could work as a fallback.\",\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        context: {\n          type: \"string\",\n          description:\n            \"A description of your goal and what kind of tool would help accomplish it.\",\n        },\n      },\n      required: [\"context\"],\n    },\n    // Spec defaults assume the worst (destructive, open-world); declare the\n    // honest hints so annotation-aware clients skip confirmation prompts.\n    annotations: {\n      title: \"Get More Tools\",\n      readOnlyHint: true,\n      destructiveHint: false,\n      idempotentHint: true,\n      openWorldHint: false,\n    },\n  } as const;\n}\n\nexport function handleReportMissing(args: { context: string }) {\n  writeToLog(\n    `Missing tool reported (context length: ${args?.context?.length ?? 0})`,\n  );\n\n  return {\n    content: [\n      {\n        type: \"text\" as const,\n        text: `Unfortunately, we have shown you the full tool list. We have noted your feedback and will work to improve the tool list in the future.`,\n      },\n    ],\n  };\n}\n","import { RegisteredTool } from \"../types.js\";\nimport { SESSION_ID_PARAM, AGENT_ID_PARAM } from \"./handles.js\";\nimport {\n  SESSION_ID_PARAM_DESCRIPTION,\n  SESSION_ID_PARAM_PATTERN,\n  AGENT_ID_PARAM_DESCRIPTION,\n  MCP_SESSION_KEY,\n  MCP_SESSION_FIELD_DESCRIPTION,\n  MCP_SESSION_FIELD_DESCRIPTION_HOOK_MODE,\n  MCP_SESSION_SESSION_ID_DESCRIPTION,\n  MCP_SESSION_AGENT_ID_DESCRIPTION,\n  MCP_SESSION_STATUS_DESCRIPTION,\n} from \"./constants.js\";\nimport { GET_MORE_TOOLS_NAME } from \"./tools.js\";\nimport { writeToLog } from \"./logging.js\";\n\nexport {\n  InjectedParamsRegistry,\n  OutputInjectionRegistry,\n  setInjectedParamsRegistry,\n  getInjectedParamsRegistry,\n  setOutputInjectionRegistry,\n  getOutputInjectionRegistry,\n} from \"../engine/registry.js\";\nimport type {\n  InjectedParamsRegistry,\n  OutputInjectionRegistry,\n} from \"../engine/registry.js\";\n\nconst CONTEXT_PARAM = \"context\";\nconst ALL_INJECTABLE = [SESSION_ID_PARAM, AGENT_ID_PARAM, CONTEXT_PARAM];\n\nfunction recordInjected(\n  registry: InjectedParamsRegistry,\n  toolName: string,\n  param: string,\n): void {\n  const existing = registry.get(toolName);\n  if (existing) existing.add(param);\n  else registry.set(toolName, new Set([param]));\n}\n\n/**\n * Adds a param to the schema's required array: created if absent, appended\n * without duplicating, customer entries never removed or reordered.\n * Requiredness rides injection exactly — only a param AgentCat injected on\n * this tool is ever added — and enforcement stays soft: callWrap tolerates\n * omission (session minted / event without agent identity), so the flag\n * drives schema-aware clients only.\n */\nfunction addToRequired(schema: Record<string, any>, param: string): void {\n  const required = schema.required;\n  if (Array.isArray(required)) {\n    if (!required.includes(param)) required.push(param);\n  } else {\n    schema.required = [param];\n  }\n}\n\nexport interface HandleInjectionOptions {\n  injectSessionId: boolean; // false in hook mode\n  injectAgentId: boolean; // false when enableAgentTracking is false\n  /** Tools already reported for a session_id collision; prevents log spam. */\n  reportedConflicts?: Set<string>;\n  /**\n   * Collects the tools whose schema declares `session_id` itself. callWrap\n   * reads it to decide whether the argument is ours: a tool NOT in here is\n   * ours (nothing declared it), including tools we skipped for schema shape.\n   */\n  declaredSessionParams?: Set<string>;\n}\n\n/**\n * Injects session_id/agent_id into each tool's JSON Schema (post-Zod), both\n * schema-required with soft enforcement (see addToRequired).\n * Order: customer params, session_id, agent_id — context is appended afterwards\n * by addContextParameterToTools, so this MUST run first. Unlike the context\n * injector, get_more_tools is NOT exempt: its calls publish events, so it\n * must be able to carry handles.\n */\nexport function addHandleParametersToTools(\n  tools: RegisteredTool[],\n  opts: HandleInjectionOptions,\n  registry: InjectedParamsRegistry,\n  outputRegistry?: OutputInjectionRegistry,\n): RegisteredTool[] {\n  if (!opts.injectSessionId && !opts.injectAgentId) return tools;\n  return tools.map((tool) => {\n    try {\n      return addHandleParametersToTool(tool, opts, registry, outputRegistry);\n    } catch (error) {\n      // One tool's schema must never poison the listing: serve it unmodified\n      // and roll back any partial registry writes so call-time stripping and\n      // output mirroring never act on state the advertised schema lacks.\n      const toolName = (tool as any)?.name || \"unknown\";\n      registry.delete(toolName);\n      outputRegistry?.delete(toolName);\n      writeToLog(\n        `WARN: Handle injection failed for tool \"${toolName}\"; listing it unmodified - ${error}`,\n      );\n      return tool;\n    }\n  });\n}\n\nfunction addHandleParametersToTool(\n  tool: RegisteredTool,\n  opts: HandleInjectionOptions,\n  registry: InjectedParamsRegistry,\n  outputRegistry?: OutputInjectionRegistry,\n): RegisteredTool {\n  const modifiedTool = { ...tool };\n  const toolName = (tool as any).name || \"unknown\";\n  const schema = modifiedTool.inputSchema as Record<string, any> | undefined;\n\n  if (schema?.oneOf || schema?.allOf || schema?.anyOf) {\n    // Injection is skipped, but ownership still has to be recorded: a schema\n    // that composes AND declares session_id at its root is the customer's\n    // parameter, not ours to read at call time. (Only the root bag is\n    // visible here — a session_id nested inside a branch is unreachable,\n    // same limitation as the injection itself.)\n    if (opts.injectSessionId && schema.properties?.[SESSION_ID_PARAM]) {\n      opts.declaredSessionParams?.add(toolName);\n    }\n    writeToLog(\n      `WARN: Tool \"${toolName}\" has complex schema (oneOf/allOf/anyOf). Skipping handle injection.`,\n    );\n    return modifiedTool;\n  }\n\n  if (!modifiedTool.inputSchema) {\n    modifiedTool.inputSchema = { type: \"object\", properties: {}, required: [] };\n  }\n  modifiedTool.inputSchema = JSON.parse(\n    JSON.stringify(modifiedTool.inputSchema),\n  );\n  if (!modifiedTool.inputSchema.properties)\n    modifiedTool.inputSchema.properties = {};\n  if (modifiedTool.inputSchema.additionalProperties === false) {\n    delete modifiedTool.inputSchema.additionalProperties;\n  }\n  const properties = modifiedTool.inputSchema.properties;\n\n  if (opts.injectSessionId) {\n    if (properties[SESSION_ID_PARAM]) {\n      // The customer owns this name on this tool: record it so call-time\n      // resolution never reads their value as an AgentCat handle.\n      opts.declaredSessionParams?.add(toolName);\n      if (!opts.reportedConflicts?.has(toolName)) {\n        opts.reportedConflicts?.add(toolName);\n        writeToLog(\n          `ERROR: Tool \"${toolName}\" already declares a '${SESSION_ID_PARAM}' parameter. ` +\n            `AgentCat will not inject its own, and calls to this tool are published without a session, ` +\n            `so they cannot be correlated. Your parameter is untouched and still reaches your handler. ` +\n            `If you already manage sessions, pass a resolveSessionId hook to track() — AgentCat will ` +\n            `derive its session from your identifier and stop injecting ${SESSION_ID_PARAM} entirely.`,\n        );\n      }\n    } else {\n      properties[SESSION_ID_PARAM] = {\n        type: \"string\",\n        description: SESSION_ID_PARAM_DESCRIPTION,\n        pattern: SESSION_ID_PARAM_PATTERN,\n      };\n      recordInjected(registry, toolName, SESSION_ID_PARAM);\n      addToRequired(modifiedTool.inputSchema, SESSION_ID_PARAM);\n    }\n  }\n\n  if (opts.injectAgentId) {\n    if (properties[AGENT_ID_PARAM]) {\n      writeToLog(\n        `WARN: Tool \"${toolName}\" already has '${AGENT_ID_PARAM}' parameter. Skipping agent_id injection.`,\n      );\n    } else {\n      properties[AGENT_ID_PARAM] = {\n        type: \"string\",\n        // One description for both modes: the copy never references the\n        // session_id parameter, so it reads the same with or without one.\n        description: AGENT_ID_PARAM_DESCRIPTION,\n      };\n      recordInjected(registry, toolName, AGENT_ID_PARAM);\n      // agent_id is self-chosen by the agent (no pattern to advertise), and\n      // schema-required like session_id above — see addToRequired for the\n      // soft-enforcement contract.\n      addToRequired(modifiedTool.inputSchema, AGENT_ID_PARAM);\n    }\n  }\n\n  if (outputRegistry) {\n    addMcpSessionToOutputSchema(modifiedTool, opts, outputRegistry, toolName);\n  }\n  return modifiedTool;\n}\n\n/**\n * Injects the optional mcp_session property into a declared plain-object\n * outputSchema so validating clients accept the mirrored field. The MCP TS\n * client ajv-validates structuredContent against the listed schema, and\n * zod-to-json-schema emits additionalProperties: false for plain z.object —\n * an undeclared key would fail the whole result, so declaration is what makes\n * mirroring safe. Composed schemas (oneOf/allOf/anyOf) have no single\n * properties bag to extend and are skipped, same policy as the input side.\n * Sub-properties mirror the modes: no session_id or status in hook mode, no\n * agent_id when tracking is off — every response state the schema\n * pre-announces is one the agent can actually receive.\n */\nfunction addMcpSessionToOutputSchema(\n  tool: RegisteredTool,\n  opts: HandleInjectionOptions,\n  outputRegistry: OutputInjectionRegistry,\n  toolName: string,\n): void {\n  const schema = (tool as any).outputSchema as Record<string, any> | undefined;\n  if (!schema) return;\n  if (schema.oneOf || schema.allOf || schema.anyOf) {\n    writeToLog(\n      `WARN: Tool \"${toolName}\" has complex outputSchema (oneOf/allOf/anyOf). Skipping ${MCP_SESSION_KEY} injection; mint-back stays content-only for this tool.`,\n    );\n    return;\n  }\n  const copy = JSON.parse(JSON.stringify(schema));\n  if (!copy.properties) copy.properties = {};\n  if (copy.properties[MCP_SESSION_KEY]) {\n    writeToLog(\n      `WARN: Tool \"${toolName}\" already declares '${MCP_SESSION_KEY}' in outputSchema. Skipping injection.`,\n    );\n    return;\n  }\n  const subProperties: Record<string, any> = {};\n  if (opts.injectSessionId) {\n    subProperties[SESSION_ID_PARAM] = {\n      type: \"string\",\n      description: MCP_SESSION_SESSION_ID_DESCRIPTION,\n    };\n  }\n  if (opts.injectAgentId) {\n    subProperties[AGENT_ID_PARAM] = {\n      type: \"string\",\n      description: MCP_SESSION_AGENT_ID_DESCRIPTION,\n    };\n  }\n  if (opts.injectSessionId) {\n    subProperties.status = {\n      type: \"string\",\n      enum: [\"issued\", \"active\", \"unrecognized\"],\n      description: MCP_SESSION_STATUS_DESCRIPTION,\n    };\n  }\n  copy.properties[MCP_SESSION_KEY] = {\n    type: \"object\",\n    description: opts.injectSessionId\n      ? MCP_SESSION_FIELD_DESCRIPTION\n      : MCP_SESSION_FIELD_DESCRIPTION_HOOK_MODE,\n    properties: subProperties,\n  };\n  (tool as any).outputSchema = copy;\n  outputRegistry.add(toolName);\n}\n\n/**\n * Strips ONLY the params AgentCat injected for this tool. Without a registry\n * entry (tools/call before any tools/list), falls back to stripping all three\n * names — except get_more_tools' bespoke context, which is a real parameter.\n */\nexport function stripInjectedArguments(\n  args: any,\n  toolName: string,\n  registry?: InjectedParamsRegistry,\n): any {\n  if (!args || typeof args !== \"object\") return args;\n  let names: Iterable<string>;\n  const recorded = registry?.get(toolName);\n  if (recorded) {\n    names = recorded;\n  } else {\n    names =\n      toolName === GET_MORE_TOOLS_NAME\n        ? [SESSION_ID_PARAM, AGENT_ID_PARAM]\n        : ALL_INJECTABLE;\n  }\n  const cleaned = { ...(args as Record<string, unknown>) };\n  for (const name of names) delete cleaned[name];\n  return cleaned;\n}\n\n/** Clones request with stripped arguments; the original (kept on the event) is untouched. */\nexport function cloneRequestWithStrippedArguments(\n  request: any,\n  registry?: InjectedParamsRegistry,\n): any {\n  const args = request?.params?.arguments;\n  if (!args || typeof args !== \"object\") return request;\n  return {\n    ...request,\n    params: {\n      ...request.params,\n      arguments: stripInjectedArguments(args, request.params?.name, registry),\n    },\n  };\n}\n","import { HighLevelMCPServerLike, MCPServerLike } from \"../types.js\";\nimport { writeToLog } from \"../modules/logging.js\";\nimport { stripInjectedArguments } from \"../modules/handle-injection.js\";\nimport { VersionAdapter, getInjectedParamsRegistry } from \"./registry.js\";\n\n// Marks both originals and wrappers so re-sweeps and re-registrations of\n// already-wrapped functions are no-ops.\nconst wrappedFns = new WeakSet<Function>();\n\n/**\n * Wraps the tool function the SDK actually dispatches (adapter.tapKeys),\n * IN PLACE — never a copy: v2's update()/enable()/disable() closures mutate\n * the original object, and copies would diverge from what tools/list serves.\n *\n * The wrap adds two behaviors around the customer function:\n * - strips any AgentCat-injected args that survived SDK validation\n *   (defense-in-depth: callWrap already strips pre-validation; permissive\n *   validators like zod .loose() can still pass them through), and\n * - stashes thrown Errors on extra.__agentcat_error so callWrap can publish\n *   full stack traces after the SDK converts the throw to an isError result.\n */\nexport function wrapToolEntry(\n  tool: any,\n  toolName: string,\n  server: MCPServerLike,\n  adapter: VersionAdapter,\n): void {\n  if (!tool || typeof tool !== \"object\") return;\n  for (const key of adapter.tapKeys) {\n    const fn = tool[key];\n    if (typeof fn !== \"function\") continue;\n    if (wrappedFns.has(fn)) return; // already ours, or already wrapped\n    const wrapped = async function (this: unknown, ...params: any[]) {\n      // Preserve the CALL ARITY of the dispatch invocation: v2 always\n      // invokes executor(args, ctx) with two positional arguments — even\n      // for schema-less tools, where args is undefined but ctx must stay\n      // in position 2. Only the v1 no-args callback convention (dispatch\n      // calls cb(extra)) passes a single argument.\n      const twoArg = params.length >= 2;\n      let args: any;\n      let extra: any;\n      if (twoArg) {\n        args = params[0];\n        extra = params[1];\n      } else {\n        args = undefined;\n        extra = params[0];\n      }\n      const registry = getInjectedParamsRegistry(server);\n      const cleaned =\n        args === undefined\n          ? undefined\n          : stripInjectedArguments(args, toolName, registry);\n      try {\n        return twoArg\n          ? await fn.call(this, cleaned, extra)\n          : await fn.call(this, extra);\n      } catch (error) {\n        if (error instanceof Error && extra && typeof extra === \"object\") {\n          (extra as any).__agentcat_error = error;\n        }\n        throw error;\n      }\n    };\n    wrappedFns.add(wrapped);\n    wrappedFns.add(fn);\n    tool[key] = wrapped;\n    return; // first present key wins\n  }\n}\n\n/** Idempotent sweep over every registered tool. Called from listWrap. */\nexport function rewrapAllTools(\n  server: MCPServerLike,\n  highLevel: HighLevelMCPServerLike,\n  adapter: VersionAdapter,\n): void {\n  try {\n    const tools = highLevel._registeredTools;\n    if (!tools || typeof tools !== \"object\") return;\n    for (const [name, tool] of Object.entries(tools)) {\n      wrapToolEntry(tool, name, server, adapter);\n    }\n  } catch (error) {\n    writeToLog(`Warning: inner-tap sweep failed - ${error}`);\n  }\n}\n\n/**\n * Proxies _registeredTools so tools registered AFTER track() get the inner\n * tap immediately and the engine re-arms its map wraps (covers v2's lazy\n * setToolRequestHandlers on first registerTool).\n */\nexport function installRegistryProxy(\n  server: MCPServerLike,\n  highLevel: HighLevelMCPServerLike,\n  adapter: VersionAdapter,\n  onRegistration: () => void,\n): void {\n  try {\n    const original = highLevel._registeredTools || {};\n    highLevel._registeredTools = new Proxy(original, {\n      set(target, property, value): boolean {\n        try {\n          if (\n            typeof property === \"string\" &&\n            value &&\n            typeof value === \"object\"\n          ) {\n            wrapToolEntry(value, property, server, adapter);\n          }\n          const ok = Reflect.set(target, property, value);\n          onRegistration();\n          return ok;\n        } catch (error) {\n          writeToLog(\n            `Warning: Error in registry proxy for tool ${String(property)} - ${error}`,\n          );\n          return Reflect.set(target, property, value);\n        }\n      },\n    });\n    writeToLog(\"Successfully set up listener for new tool registrations\");\n  } catch (error) {\n    writeToLog(\n      `Warning: Failed to setup listener for registered tools - ${error}`,\n    );\n  }\n}\n","import { AgentCatData, MCPServerLike } from \"../types.js\";\nimport { writeToLog } from \"../modules/logging.js\";\nimport { getServerTrackingData } from \"../modules/internal.js\";\nimport { addContextParameterToTools } from \"../modules/context-parameters.js\";\nimport { addHandleParametersToTools } from \"../modules/handle-injection.js\";\nimport {\n  GET_MORE_TOOLS_NAME,\n  getReportMissingToolDescriptor,\n} from \"../modules/tools.js\";\nimport {\n  InjectedParamsRegistry,\n  OutputInjectionRegistry,\n  getDeclaredSessionParams,\n  getEngineState,\n  getReportedConflicts,\n  recordCustomerOwnedReportMissing,\n  setInjectedParamsRegistry,\n  setOutputInjectionRegistry,\n} from \"./registry.js\";\nimport { rewrapAllTools } from \"./innerTap.js\";\n\nexport interface InjectedList {\n  tools: any[];\n  registry: InjectedParamsRegistry;\n  outputRegistry: OutputInjectionRegistry;\n}\n\n/**\n * The injection pipeline, pure: (config, listed tools) -> (advertised tools,\n * registries). Deterministic and config-derived, so rebuild-on-demand\n * (callWrap) can reproduce registries exactly on a fresh per-request\n * instance that never served tools/list.\n */\nexport function buildInjectedList(\n  data: AgentCatData,\n  tools: any[],\n): InjectedList {\n  let result = [...tools];\n\n  // Append get_more_tools BEFORE injection so it receives handle params.\n  // The context injector skips it by name (bespoke context), so early\n  // placement cannot double-inject context.\n  if (data.options.enableReportMissing) {\n    const alreadyPresent = result.some(\n      (t: any) => t?.name === GET_MORE_TOOLS_NAME,\n    );\n    if (!alreadyPresent) result.push(getReportMissingToolDescriptor());\n    else recordCustomerOwnedReportMissing(data);\n  }\n\n  // Order matters: handles first, then context ->\n  // { ...customerParams, session_id, agent_id, context }\n  // enableTracing:false skips handle injection wholesale (spec guard).\n  const tracingEnabled = data.options.enableTracing !== false;\n  const registry: InjectedParamsRegistry = new Map();\n  const outputRegistry: OutputInjectionRegistry = new Set();\n  result = addHandleParametersToTools(\n    result,\n    {\n      injectSessionId: tracingEnabled && !data.options.resolveSessionId,\n      injectAgentId:\n        tracingEnabled && data.options.enableAgentTracking === true,\n      reportedConflicts: getReportedConflicts(data),\n      declaredSessionParams: getDeclaredSessionParams(data),\n    },\n    registry,\n    outputRegistry,\n  );\n  if (data.options.enableToolCallContext) {\n    result = addContextParameterToTools(\n      result,\n      data.options.customContextDescription,\n      registry,\n    );\n  }\n  // Tools that received zero injections still get an (empty) entry: the\n  // strip fallback must apply only to tools never seen in any listing.\n  for (const t of result) {\n    const name = (t as any)?.name;\n    if (name && !registry.has(name)) registry.set(name, new Set());\n  }\n  return { tools: result, registry, outputRegistry };\n}\n\n/**\n * Wraps the stored tools/list handler via the _requestHandlers map seam.\n * Idempotent: re-invoking after a customer re-registration captures the new\n * handler; when our wrapper is already current, no-op.\n */\nexport function installListWrap(server: MCPServerLike): void {\n  const st = getEngineState(server);\n  if (!st) return;\n  const handlers = server._requestHandlers;\n  const current = handlers.get(\"tools/list\");\n  if (!current) return; // no handler yet; registrationPatch re-arms us\n  if (st.listWrapper && current === st.listWrapper) return;\n\n  const originalHandler = current;\n  st.originalList = originalHandler;\n\n  const wrapper = async (request: any, extra?: any) => {\n    const originalResponse = await originalHandler(request, extra);\n    const data = getServerTrackingData(server);\n    if (!data) {\n      writeToLog(\n        \"Warning: AgentCat is unable to find server tracking data. Please ensure you have called track(server, options) before using tool calls.\",\n      );\n      return originalResponse;\n    }\n    const tools = originalResponse?.tools;\n    if (!Array.isArray(tools) || tools.length === 0) {\n      writeToLog(\n        \"Warning: No tools found in the original list. This is likely due to the tools not being registered before AgentCat.track().\",\n      );\n      return originalResponse;\n    }\n\n    // Injection failure must degrade to the customer's own listing — the\n    // tools/call path already contains the identical pipeline (ensureRegistries);\n    // tools/list gets the same policy.\n    try {\n      const injected = buildInjectedList(data, tools);\n      setInjectedParamsRegistry(server, injected.registry);\n      setOutputInjectionRegistry(server, injected.outputRegistry);\n\n      // Inner-tap re-sweep: catches tools registered or update()d since the\n      // last wrap pass (v2 update() regenerates executor).\n      if (st.highLevel) rewrapAllTools(server, st.highLevel, st.adapter);\n\n      // Spread: nextCursor, result _meta, and any future fields pass through.\n      return { ...originalResponse, tools: injected.tools };\n    } catch (error) {\n      writeToLog(\n        `Warning: AgentCat tool-list injection failed; serving the original tool list unmodified - ${error}`,\n      );\n      return originalResponse;\n    }\n  };\n\n  st.listWrapper = wrapper;\n  handlers.set(\"tools/list\", wrapper);\n}\n","import {\n  MCPServerLike,\n  PendingEventFields,\n  UnredactedEvent,\n  ServerClientInfoLike,\n} from \"../types.js\";\nimport { writeToLog } from \"../modules/logging.js\";\nimport {\n  getServerTrackingData,\n  resolveEventTags,\n  resolveEventProperties,\n  resolveIdentity,\n} from \"../modules/internal.js\";\nimport { PublishEventRequestEventTypeEnum } from \"agentcat-api\";\nimport { publishEvent } from \"../modules/eventQueue.js\";\nimport { captureException } from \"../modules/exceptions.js\";\nimport {\n  resolveHandles,\n  invokeSessionHook,\n  buildHandleTags,\n  buildMintBackText,\n  appendMintBack,\n  buildStructuredMintBack,\n  mirrorStructuredMintBack,\n  HandleResolution,\n} from \"../modules/handles.js\";\nimport { cloneRequestWithStrippedArguments } from \"../modules/handle-injection.js\";\nimport { projectExtraForEvent } from \"../modules/extra-projection.js\";\nimport {\n  getClientInfoForRequest,\n  getProtocolVersion,\n} from \"../modules/session.js\";\nimport { GET_MORE_TOOLS_NAME, handleReportMissing } from \"../modules/tools.js\";\nimport { AGENTCAT_TAG_MRTR } from \"../modules/constants.js\";\nimport {\n  getDeclaredSessionParams,\n  getEngineState,\n  getInjectedParamsRegistry,\n  getOutputInjectionRegistry,\n  setInjectedParamsRegistry,\n  setOutputInjectionRegistry,\n} from \"./registry.js\";\nimport { buildInjectedList } from \"./listWrap.js\";\n\nfunction isToolResultError(result: any): boolean {\n  return result && typeof result === \"object\" && result.isError === true;\n}\n\n/** 2026-era intermediate result of a multi-round-trip tools/call. */\nexport function isInputRequiredShape(result: unknown): boolean {\n  return (\n    typeof result === \"object\" &&\n    result !== null &&\n    !Array.isArray(result) &&\n    (result as { resultType?: unknown }).resultType === \"input_required\"\n  );\n}\n\n/** Tag for a retry round carrying the client's input responses. */\nexport function mrtrContinuationTags(extra: unknown): Record<string, string> {\n  const inputResponses = (extra as any)?.mcpReq?.inputResponses;\n  return inputResponses && typeof inputResponses === \"object\"\n    ? { [AGENTCAT_TAG_MRTR]: \"continuation\" }\n    : {};\n}\n\n/**\n * The rebuild runs the CUSTOMER's list handler on the tools/call request\n * path, so it must be time-bounded: a hanging list handler would otherwise\n * hang every tool call on this instance. On timeout the call proceeds with\n * the heuristic strip fallback; the next call retries the rebuild.\n */\nconst REGISTRY_REBUILD_TIMEOUT_MS = 5_000;\n\n/**\n * Registry rebuild-on-demand: a tools/call on an instance that never served\n * tools/list (per-request 2026-era topology) rebuilds the registries by\n * running the original list handler through the same pure injection\n * pipeline. Deterministic, so the rebuilt registries match what any listing\n * instance advertised.\n */\nasync function ensureRegistries(\n  server: MCPServerLike,\n  extra: any,\n): Promise<void> {\n  if (getInjectedParamsRegistry(server)) return;\n  const data = getServerTrackingData(server);\n  const originalList = getEngineState(server)?.originalList;\n  if (!data || !originalList) return; // heuristic strip fallback applies\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  try {\n    const listPromise = Promise.resolve(\n      originalList({ method: \"tools/list\", params: {} }, extra),\n    );\n    // The abandoned promise must never surface as an unhandled rejection.\n    listPromise.catch(() => {});\n    const response: any = await Promise.race([\n      listPromise,\n      new Promise((_, reject) => {\n        timer = setTimeout(\n          () =>\n            reject(\n              new Error(\n                `tools/list did not respond within ${REGISTRY_REBUILD_TIMEOUT_MS}ms`,\n              ),\n            ),\n          REGISTRY_REBUILD_TIMEOUT_MS,\n        );\n      }),\n    ]);\n    const tools = response?.tools;\n    if (!Array.isArray(tools)) return;\n    const injected = buildInjectedList(data, tools);\n    setInjectedParamsRegistry(server, injected.registry);\n    setOutputInjectionRegistry(server, injected.outputRegistry);\n    writeToLog(\n      \"Rebuilt injection registries on demand (tools/call before tools/list on this instance)\",\n    );\n  } catch (error) {\n    writeToLog(`Warning: registry rebuild-on-demand failed - ${error}`);\n  } finally {\n    if (timer !== undefined) clearTimeout(timer);\n  }\n}\n\n/**\n * Wraps the stored tools/call handler via the _requestHandlers map seam.\n * Outermost layer, run exactly once per request: resolution, event build,\n * publish, and mint-back all live here. The inner tap (innerTap.ts) only\n * strips leftovers and captures stack traces.\n */\nexport function installCallWrap(server: MCPServerLike): void {\n  const st = getEngineState(server);\n  if (!st) return;\n  const handlers = server._requestHandlers;\n  const current = handlers.get(\"tools/call\");\n  if (!current) return; // registrationPatch re-arms when it appears\n  if (st.callWrapper && current === st.callWrapper) return;\n\n  const originalHandler = current;\n  st.originalCall = originalHandler;\n\n  const wrapper = async (request: any, extra: any) => {\n    const data = getServerTrackingData(server);\n    // The report-missing intercept answers by NAME, so it must be gated on\n    // the feature actually being on — otherwise a customer's own\n    // get_more_tools tool would be unreachable with the feature disabled.\n    // (When enabled, AgentCat answers even for a customer-owned name; the\n    // listing warns once about the shadowing.)\n    const interceptReportMissing = (name: any) =>\n      data?.options?.enableReportMissing === true &&\n      name === GET_MORE_TOOLS_NAME;\n\n    // Tracing off: no resolution, no mint-back, no event.\n    if (data && data.options.enableTracing === false) {\n      if (interceptReportMissing(request?.params?.name)) {\n        return handleReportMissing({\n          context: request?.params?.arguments?.context,\n        });\n      }\n      return originalHandler(request, extra);\n    }\n\n    const startTime = new Date();\n\n    let tracing: {\n      event: UnredactedEvent;\n      resolution: HandleResolution;\n      clientInfo: ServerClientInfoLike | undefined;\n    } | null = null;\n\n    if (!data) {\n      writeToLog(\n        \"Warning: AgentCat is unable to find server tracking data. Please ensure you have called track(server, options) before using tool calls.\",\n      );\n    } else {\n      try {\n        await ensureRegistries(server, extra);\n        // A session_id is the customer's only when their own schema declared\n        // it — recorded at the collision site during listing. Everything else\n        // is ours, including tools we skipped for schema shape\n        // (oneOf/allOf/anyOf), which carry no injection record but no\n        // customer session_id either. A tool never seen in any listing is\n        // likewise ours, so a pre-listing call still validates (spec:\n        // degrades to `invalid`, not `foreign`).\n        const toolName = request?.params?.name;\n        const sessionParamIsOurs = !(\n          toolName && getDeclaredSessionParams(data).has(toolName)\n        );\n\n        const resolution = resolveHandles(\n          data.options,\n          data.projectId || undefined,\n          request,\n          extra,\n          sessionParamIsOurs,\n        );\n        const clientInfo = getClientInfoForRequest(server, request, extra);\n\n        // Fire the customer hooks NOW, awaited only in the background event\n        // pipeline — a slow or hanging hook can never hold up the tool call.\n        // Each invocation yields a non-rejecting promise (the internal.ts\n        // resolvers catch everything; invokeSessionHook contains sync throws\n        // with its rejection handler attached at creation), so leaving them\n        // un-awaited cannot surface an unhandled rejection. Hooks receive the\n        // raw request: injected params are visible to them by contract.\n        const pending: PendingEventFields = {};\n        if (resolution.hookMode) {\n          pending.sessionHookValue = invokeSessionHook(\n            data.options,\n            request,\n            extra,\n          );\n        }\n        if (data.options.identify) {\n          pending.identity = resolveIdentity(data, request, extra);\n        }\n        if (data.options.eventTags) {\n          pending.tags = resolveEventTags(data, request, extra);\n        }\n        if (data.options.eventProperties) {\n          pending.properties = resolveEventProperties(data, request, extra);\n        }\n\n        const event: UnredactedEvent = {\n          sessionId: resolution.sessionId,\n          resourceName: request?.params?.name || \"Unknown Tool\",\n          // Raw request on purpose: the event records exactly what the agent\n          // sent, handles included. Stripping applies only to the handler copy.\n          // extra is projected at capture time: v2's live web Request (and\n          // v1's URL instance) become plain JSON the pipeline walkers can\n          // traverse — headers would otherwise flatten to {}. Contract: the\n          // redactEvent hook sees this projection, i.e. what ships.\n          parameters: { request, extra: projectExtraForEvent(extra) },\n          eventType: PublishEventRequestEventTypeEnum.mcpToolsCall,\n          timestamp: startTime,\n          redactionFn: data.options.redactSensitiveInformation,\n        };\n        if (Object.keys(pending).length > 0) event.pending = pending;\n\n        // On-path tags are SDK-owned only. Customer eventTags resolve in the\n        // background and merge UNDER these (SDK tags stay last-writer).\n        event.tags = {\n          ...mrtrContinuationTags(extra),\n          ...buildHandleTags(resolution, getProtocolVersion(request, extra)),\n        };\n\n        if (\n          data.options.enableToolCallContext &&\n          request?.params?.name !== GET_MORE_TOOLS_NAME &&\n          request?.params?.arguments &&\n          typeof request.params.arguments === \"object\" &&\n          \"context\" in request.params.arguments\n        ) {\n          event.userIntent = request.params.arguments.context;\n        }\n\n        tracing = { event, resolution, clientInfo };\n      } catch (error) {\n        writeToLog(\n          `Warning: AgentCat tracing failed for tool ${request?.params?.name}, falling back to original handler - ${error}`,\n        );\n      }\n    }\n\n    // Degraded path: run the tool unstripped — no event, no mint-back.\n    if (!tracing) {\n      if (interceptReportMissing(request?.params?.name)) {\n        return handleReportMissing({\n          context: request?.params?.arguments?.context,\n        });\n      }\n      return originalHandler(request, extra);\n    }\n\n    const { event, resolution, clientInfo } = tracing;\n\n    const finish = (result: any) => {\n      // The handler has already succeeded: nothing in this stage may reach\n      // the client as an error. Any failure here forfeits decoration and\n      // analytics for this call and returns the customer's result untouched.\n      try {\n        let finalResult = result;\n        if (isInputRequiredShape(result)) {\n          // Intermediate round: tag it, decorate nothing — the completing\n          // round carries the mint-back.\n          event.tags = { ...event.tags, [AGENTCAT_TAG_MRTR]: \"input_required\" };\n        } else {\n          const text = buildMintBackText(resolution);\n          finalResult = text ? appendMintBack(result, text) : result;\n          // Structured mirror, gated by the output-injection registry.\n          // ensureRegistries makes a missing registry rare (rebuild failed);\n          // in that case mirror anyway — the client cannot have a declared\n          // schema we know about.\n          const outputRegistry = getOutputInjectionRegistry(server);\n          if (!outputRegistry || outputRegistry.has(request?.params?.name)) {\n            const mint = buildStructuredMintBack(resolution);\n            if (mint) finalResult = mirrorStructuredMintBack(finalResult, mint);\n          }\n        }\n        if (isToolResultError(result)) {\n          event.isError = true;\n          const capturedError = (extra as any)?.__agentcat_error;\n          if (capturedError) {\n            event.error = captureException(capturedError);\n            delete (extra as any).__agentcat_error;\n          } else {\n            event.error = captureException(result);\n          }\n        }\n        // Mint-back is wire-only: the event records the customer's original result.\n        event.response = result;\n        event.duration = new Date().getTime() - startTime.getTime();\n        publishEvent(server, event, { clientInfo });\n        return finalResult;\n      } catch (error) {\n        writeToLog(\n          `Warning: AgentCat post-handler processing failed for tool ${request?.params?.name}; returning the customer's result untouched - ${error}`,\n        );\n        return result;\n      }\n    };\n\n    try {\n      if (interceptReportMissing(request?.params?.name)) {\n        event.userIntent = request?.params?.arguments?.context;\n        return finish(\n          await handleReportMissing({\n            context: request?.params?.arguments?.context,\n          }),\n        );\n      }\n      // STRIPPED request through: injected params never reach SDK validation\n      // (fixes strict-schema rejection). The event keeps the raw request.\n      const strippedRequest = cloneRequestWithStrippedArguments(\n        request,\n        getInjectedParamsRegistry(server),\n      );\n      return finish(await originalHandler(strippedRequest, extra));\n    } catch (error) {\n      event.isError = true;\n      event.error = captureException(error);\n      event.duration = new Date().getTime() - startTime.getTime();\n      publishEvent(server, event, { clientInfo });\n      throw error;\n    }\n  };\n\n  st.callWrapper = wrapper;\n  handlers.set(\"tools/call\", wrapper);\n}\n","import {\n  Configuration,\n  EventsApi,\n  PublishEventRequest,\n  PublishEventRequestEventTypeEnum,\n} from \"agentcat-api\";\nimport {\n  Event,\n  UnredactedEvent,\n  MCPServerLike,\n  ServerClientInfoLike,\n} from \"../types.js\";\nimport { writeToLog } from \"./logging.js\";\nimport { getServerTrackingData } from \"./internal.js\";\nimport { buildSessionInfo } from \"./session.js\";\nimport { applyEventRedaction, redactEvent } from \"./redaction.js\";\nimport { applyPendingEventFields } from \"./pendingEvent.js\";\nimport { sanitizeEvent } from \"./sanitization.js\";\nimport { truncateEvent } from \"./truncation.js\";\nimport KSUID from \"../thirdparty/ksuid/index.js\";\nimport { getMCPCompatibleErrorMessage } from \"./compatibility.js\";\nimport { TelemetryManager } from \"./telemetry.js\";\nimport { flushDiagnostics } from \"./diagnostics.js\";\nimport { registerBackgroundTask } from \"./backgroundTasks.js\";\n\ninterface QueuedEvent {\n  event: UnredactedEvent;\n  delivery: Promise<void>;\n  settle: () => void;\n}\n\nclass EventQueue {\n  private queue: QueuedEvent[] = [];\n  private processing = false;\n  private maxRetries = 3;\n  private maxQueueSize = 10000; // Prevent unbounded growth\n  private concurrency = 5; // Max parallel requests\n  private activeRequests = 0;\n  private apiClient: EventsApi;\n  private telemetryManager?: TelemetryManager;\n\n  constructor() {\n    const config = new Configuration({ basePath: \"https://api.agentcat.com\" });\n    this.apiClient = new EventsApi(config);\n  }\n\n  configure(apiBaseUrl: string): void {\n    const config = new Configuration({ basePath: apiBaseUrl });\n    this.apiClient = new EventsApi(config);\n  }\n\n  setTelemetryManager(telemetryManager: TelemetryManager): void {\n    this.telemetryManager = telemetryManager;\n  }\n\n  add(event: UnredactedEvent): void {\n    let settleDelivery: () => void = () => {};\n    const delivery = new Promise<void>((resolve) => {\n      settleDelivery = resolve;\n    });\n    const queuedEvent: QueuedEvent = {\n      event,\n      delivery,\n      settle: settleDelivery,\n    };\n\n    // Drop oldest events if queue is full (or implement your preferred strategy)\n    if (this.queue.length >= this.maxQueueSize) {\n      writeToLog(\"Event queue full, dropping oldest event\");\n      this.queue.shift()?.settle();\n    }\n\n    this.queue.push(queuedEvent);\n\n    // Only AgentCat ingestion is protected. Telemetry-only events and custom\n    // exporters retain their existing best-effort lifecycle.\n    if (event.projectId) {\n      registerBackgroundTask(delivery);\n    }\n\n    void this.process();\n  }\n\n  private async process(): Promise<void> {\n    if (this.processing) return;\n\n    this.processing = true;\n\n    while (this.queue.length > 0 && this.activeRequests < this.concurrency) {\n      const queuedEvent = this.queue.shift();\n      if (!queuedEvent) continue;\n\n      this.activeRequests++;\n      void this.processEvent(queuedEvent);\n    }\n\n    this.processing = false;\n  }\n\n  private async processEvent(queuedEvent: QueuedEvent): Promise<void> {\n    const { event } = queuedEvent;\n\n    try {\n      // Stage 0: resolve deferred hook results. Detach FIRST so no later\n      // stage, hook input, or serializer can ever see the promises.\n      const pending = event.pending;\n      if (pending) {\n        delete event.pending;\n        try {\n          await applyPendingEventFields(event, pending);\n        } catch (error) {\n          writeToLog(`Failed to resolve pending hook results: ${error}`);\n        }\n      }\n\n      if (event.eventRedactionFn) {\n        const eventRedactionFn = event.eventRedactionFn;\n        event.eventRedactionFn = undefined;\n        try {\n          if (!(await applyEventRedaction(event, eventRedactionFn))) {\n            writeToLog(\"Event dropped by redactEvent hook\");\n            return;\n          }\n        } catch (error) {\n          writeToLog(`Failed to redact event (event-level hook): ${error}`);\n          return;\n        }\n      }\n\n      if (event.redactionFn) {\n        try {\n          const redactedEvent = await redactEvent(event, event.redactionFn);\n          event.redactionFn = undefined;\n          Object.assign(event, redactedEvent);\n        } catch (error) {\n          writeToLog(`Failed to redact event: ${error}`);\n          return;\n        }\n      }\n\n      try {\n        Object.assign(event, sanitizeEvent(event));\n      } catch (error) {\n        writeToLog(`Failed to sanitize event: ${error}`);\n        return;\n      }\n\n      try {\n        Object.assign(event, truncateEvent(event));\n      } catch (error) {\n        writeToLog(`Failed to truncate event: ${error}`);\n        return;\n      }\n\n      event.id = event.id || (await KSUID.withPrefix(\"evt\").random());\n      await this.sendEvent(event as Event);\n    } catch (error) {\n      writeToLog(\n        `Failed to deliver AgentCat event after retries: ${getMCPCompatibleErrorMessage(error)}`,\n      );\n    } finally {\n      queuedEvent.settle();\n      this.activeRequests--;\n      void this.process();\n    }\n  }\n\n  private toPublishEventRequest(event: Event): PublishEventRequest {\n    return {\n      // Core fields\n      id: event.id,\n      // Safe: sendEvent only publishes when event.projectId is truthy\n      projectId: event.projectId!,\n      sessionId: event.sessionId || null,\n      timestamp: event.timestamp,\n      duration: event.duration,\n\n      // Event data\n      eventType: event.eventType as PublishEventRequestEventTypeEnum,\n      resourceName: event.resourceName,\n      parameters: event.parameters,\n      response: event.response,\n      userIntent: event.userIntent,\n      isError: event.isError,\n      error: event.error,\n\n      // Actor fields\n      identifyActorGivenId: event.identifyActorGivenId,\n      identifyActorName: event.identifyActorName,\n      identifyData: event.identifyActorData,\n\n      // Session info\n      ipAddress: event.ipAddress,\n      sdkLanguage: event.sdkLanguage,\n      agentcatVersion: event.agentcatVersion,\n      serverName: event.serverName,\n      serverVersion: event.serverVersion,\n      clientName: event.clientName,\n      clientVersion: event.clientVersion,\n\n      // Legacy fields\n      actorId: event.actorId || event.identifyActorGivenId,\n      eventId: event.eventId,\n\n      // Customer-defined metadata\n      tags: event.tags ?? undefined,\n      properties: event.properties ?? undefined,\n    };\n  }\n\n  private async sendEvent(event: Event, retries = 0): Promise<void> {\n    // Export to telemetry if configured (fire-and-forget)\n    if (this.telemetryManager) {\n      this.telemetryManager.export(event).catch((error) => {\n        writeToLog(\n          `Telemetry export error: ${getMCPCompatibleErrorMessage(error)}`,\n        );\n      });\n    }\n\n    // Send to AgentCat API if projectId is provided\n    if (event.projectId) {\n      try {\n        const publishRequest = this.toPublishEventRequest(event);\n        await this.apiClient.publishEvent({\n          publishEventRequest: publishRequest,\n        });\n        writeToLog(\n          `Successfully sent event ${event.id} | ${event.eventType} | session ${event.sessionId} | ${event.projectId} | ${event.duration} ms | ${event.identifyActorGivenId || \"anonymous\"}`,\n        );\n      } catch (error) {\n        writeToLog(\n          `Failed to send event ${event.id}, retrying... [Error: ${getMCPCompatibleErrorMessage(error)}]`,\n        );\n        if (retries < this.maxRetries) {\n          // Exponential backoff: 1s, 2s, 4s\n          await this.delay(Math.pow(2, retries) * 1000);\n          return this.sendEvent(event, retries + 1);\n        }\n        throw error;\n      }\n    }\n  }\n\n  private delay(ms: number): Promise<void> {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n  }\n\n  // Get queue stats for monitoring\n  getStats() {\n    return {\n      queueLength: this.queue.length,\n      activeRequests: this.activeRequests,\n      isProcessing: this.processing,\n    };\n  }\n\n  // Graceful shutdown - wait for active requests\n  async destroy(): Promise<void> {\n    // Stop accepting new events\n    this.add = () => {\n      writeToLog(\"Queue is shutting down, event dropped\");\n    };\n\n    // Wait for queue to drain (with timeout)\n    const timeout = 5000; // 5 seconds\n    const start = Date.now();\n\n    while (\n      (this.queue.length > 0 || this.activeRequests > 0) &&\n      Date.now() - start < timeout\n    ) {\n      await this.delay(100);\n    }\n\n    if (this.queue.length > 0) {\n      writeToLog(\n        `Shutting down with ${this.queue.length} events still in queue`,\n      );\n    }\n  }\n}\n\nexport const eventQueue = new EventQueue();\n\n/**\n * Signal-driven shutdown: drain the queue and diagnostics, then RESTORE the\n * signal's default behavior. Installing any SIGINT/SIGTERM listener disables\n * Node's default exit, so without the re-raise the first Ctrl+C / kill would\n * leave the customer's server running as an unkillable zombie until a second\n * signal — AgentCat must not change process lifecycle. The re-raise is\n * skipped when the customer has their own listener for the signal: then they\n * own termination, exactly as they did without AgentCat.\n *\n * Exported for tests; the deps parameter exists only as a test seam.\n */\nexport async function runSignalShutdown(\n  signal: NodeJS.Signals,\n  deps: {\n    destroy: () => Promise<void>;\n    flush: () => Promise<void>;\n    listenerCount: (s: NodeJS.Signals) => number;\n    reRaise: (s: NodeJS.Signals) => void;\n  } = {\n    destroy: () => eventQueue.destroy(),\n    flush: () => flushDiagnostics(),\n    listenerCount: (s) => process.listenerCount(s),\n    reRaise: (s) => process.kill(process.pid, s),\n  },\n): Promise<void> {\n  await Promise.allSettled([deps.destroy(), deps.flush()]);\n  try {\n    if (deps.listenerCount(signal) === 0) deps.reRaise(signal);\n  } catch {\n    // Re-raise is best effort; never throw from a signal handler.\n  }\n}\n\n// Register graceful shutdown handlers if available (Node.js only)\n// Edge environments (Cloudflare Workers, etc.) don't have process signals\ntry {\n  if (typeof process !== \"undefined\" && typeof process.once === \"function\") {\n    process.once(\"SIGINT\", () => void runSignalShutdown(\"SIGINT\"));\n    process.once(\"SIGTERM\", () => void runSignalShutdown(\"SIGTERM\"));\n    process.once(\"beforeExit\", () => {\n      // Natural exit path: flush only — no signal to restore.\n      void eventQueue.destroy();\n      void flushDiagnostics();\n    });\n  }\n} catch {\n  // process.once not available in this environment - graceful shutdown handlers not registered\n}\n\nlet currentTelemetryManager: TelemetryManager | undefined;\n\nexport function setTelemetryManager(telemetryManager: TelemetryManager): void {\n  currentTelemetryManager = telemetryManager;\n  eventQueue.setTelemetryManager(telemetryManager);\n}\n\nexport function getTelemetryManager(): TelemetryManager | undefined {\n  return currentTelemetryManager;\n}\n\nexport interface PublishEventContext {\n  clientInfo?: ServerClientInfoLike;\n}\n\nexport function publishEvent(\n  server: MCPServerLike,\n  eventInput: UnredactedEvent,\n  context?: PublishEventContext,\n): void {\n  const data = getServerTrackingData(server);\n  if (!data) {\n    writeToLog(\n      \"Warning: Server tracking data not found. Event will not be published.\",\n    );\n    return;\n  }\n\n  if (!data.options.enableTracing) {\n    return;\n  }\n\n  // Identity is no longer passed at publish time: the identify hook is\n  // deferred, and its result lands via event.pending in the queue's stage 0.\n  // buildSessionInfo's anonymous defaults are the correct pre-identity state.\n  const sessionInfo = buildSessionInfo(\n    server,\n    null,\n    context?.clientInfo ?? server.getClientVersion(),\n  );\n\n  // Calculate duration if not provided\n  const duration =\n    eventInput.duration ||\n    (eventInput.timestamp\n      ? new Date().getTime() - eventInput.timestamp.getTime()\n      : undefined);\n\n  // Build complete Event object with all fields explicit\n  const fullEvent: UnredactedEvent = {\n    // Core fields (id will be generated later in the queue)\n    id: eventInput.id || \"\",\n    sessionId: eventInput.sessionId || \"\",\n    projectId: data.projectId,\n\n    // Event metadata\n    eventType: eventInput.eventType || \"\",\n    timestamp: eventInput.timestamp || new Date(),\n    duration: duration,\n\n    // Session context from sessionInfo\n    ipAddress: sessionInfo.ipAddress,\n    sdkLanguage: sessionInfo.sdkLanguage,\n    agentcatVersion: sessionInfo.agentcatVersion,\n    serverName: sessionInfo.serverName,\n    serverVersion: sessionInfo.serverVersion,\n    clientName: sessionInfo.clientName,\n    clientVersion: sessionInfo.clientVersion,\n\n    // Actor information from sessionInfo\n    identifyActorGivenId: sessionInfo.identifyActorGivenId,\n    identifyActorName: sessionInfo.identifyActorName,\n    identifyActorData: sessionInfo.identifyActorData,\n\n    // Event-specific data from input\n    resourceName: eventInput.resourceName,\n    parameters: eventInput.parameters,\n    response: eventInput.response,\n    userIntent: eventInput.userIntent,\n    isError: eventInput.isError,\n    error: eventInput.error,\n\n    // Preserve redaction functions\n    redactionFn: eventInput.redactionFn,\n    eventRedactionFn: eventInput.eventRedactionFn ?? data.options.redactEvent,\n\n    // Deferred hook results, resolved in the queue's stage 0\n    pending: eventInput.pending,\n\n    // Customer-defined metadata\n    tags: eventInput.tags,\n    properties: eventInput.properties,\n  };\n\n  eventQueue.add(fullEvent);\n}\n","import {\n  MCPServerLike,\n  ServerClientInfoLike,\n  SessionInfo,\n  UserIdentity,\n} from \"../types.js\";\nimport packageJson from \"../../package.json\" with { type: \"json\" };\n\nimport {\n  META_CLIENT_INFO_KEY,\n  META_PROTOCOL_VERSION_KEY,\n} from \"./constants.js\";\n\nfunction narrowClientInfo(value: unknown): ServerClientInfoLike | undefined {\n  if (\n    value &&\n    typeof value === \"object\" &&\n    (typeof (value as any).name === \"string\" ||\n      typeof (value as any).version === \"string\")\n  ) {\n    const v = value as { name?: unknown; version?: unknown };\n    // Narrow per field: a non-string name/version must not reach the payload.\n    return {\n      name: typeof v.name === \"string\" ? v.name : undefined,\n      version: typeof v.version === \"string\" ? v.version : undefined,\n    };\n  }\n  return undefined;\n}\n\n/**\n * Client identity, resolved per request and never cached by us:\n * 1. ctx.mcpReq.envelope[\"io.modelcontextprotocol/clientInfo\"] — v2 lifts\n *    the reserved io.modelcontextprotocol/* keys out of _meta before\n *    dispatch, verbatim under their fully-qualified names; the envelope is\n *    the only place they exist on a v2 server.\n * 2. _meta clientInfo — v1 passes the keys through untouched.\n * 3. server.getClientVersion() — legacy initialize capture (backfilled from\n *    the envelope by v2's createMcpHandler; undefined on 2026-pinned stdio).\n */\nexport function getClientInfoForRequest(\n  server: MCPServerLike,\n  request: any,\n  extra?: unknown,\n): ServerClientInfoLike | undefined {\n  const fromEnvelope = narrowClientInfo(\n    (extra as any)?.mcpReq?.envelope?.[META_CLIENT_INFO_KEY],\n  );\n  if (fromEnvelope) return fromEnvelope;\n  const fromMeta = narrowClientInfo(\n    request?.params?._meta?.[META_CLIENT_INFO_KEY],\n  );\n  if (fromMeta) return fromMeta;\n  return server.getClientVersion();\n}\n\nexport function getProtocolVersion(\n  request: any,\n  extra?: unknown,\n): string | undefined {\n  const env = (extra as any)?.mcpReq?.envelope?.[META_PROTOCOL_VERSION_KEY];\n  if (typeof env === \"string\" && env.length > 0) return env;\n  const value = request?.params?._meta?.[META_PROTOCOL_VERSION_KEY];\n  return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * Builds the session metadata stamped onto one event, from values resolved\n * for THIS request. Pure: reads the server, writes nothing.\n */\nexport function buildSessionInfo(\n  server: MCPServerLike,\n  identity: UserIdentity | null | undefined,\n  clientInfo: ServerClientInfoLike | undefined,\n): SessionInfo {\n  return {\n    ipAddress: undefined, // grab from django\n    sdkLanguage: \"TypeScript\", // hardcoded for now\n    agentcatVersion: packageJson.version,\n    serverName: server._serverInfo?.name,\n    serverVersion: server._serverInfo?.version,\n    clientName: clientInfo?.name,\n    clientVersion: clientInfo?.version,\n    identifyActorGivenId: identity?.userId,\n    identifyActorName: identity?.userName,\n    identifyActorData: identity?.userData || {},\n  };\n}\n","import {\n  Event,\n  RedactEventFunction,\n  RedactFunction,\n  UnredactedEvent,\n} from \"../types.js\";\n\n/**\n * Set of field names that should be protected from redaction.\n * These fields contain system-level identifiers and metadata that\n * need to be preserved for analytics tracking.\n */\nconst PROTECTED_FIELDS = new Set([\n  \"sessionId\",\n  \"id\",\n  \"projectId\",\n  \"server\",\n  \"serverName\",\n  \"serverVersion\",\n  \"clientName\",\n  \"clientVersion\",\n  \"identifyActorGivenId\",\n  \"identifyActorName\",\n  \"identifyData\",\n  \"resourceName\",\n  \"eventType\",\n  \"actorId\",\n  \"tags\",\n  \"properties\",\n]);\n\n/**\n * Recursively applies a redaction function to all string values in an object.\n * This ensures that sensitive information is removed from all string fields\n * before events are sent to the analytics service.\n *\n * @param obj - The object to redact strings from\n * @param redactFn - The redaction function to apply to each string\n * @param path - The current path in the object tree (used to check protected fields)\n * @param isProtected - Whether the current object/value is within a protected field\n * @param seen - Clones of objects already visited on this walk. Cycles in\n *   customer-supplied data (hook payloads, tool responses) must terminate:\n *   because each level suspends at an await, an unguarded cycle starves the\n *   event loop and dies in an uncatchable V8 heap-limit abort rather than a\n *   stack overflow. Same policy as normalize() in truncation.ts.\n * @returns A new object with all strings redacted\n */\nasync function redactStringsInObject(\n  obj: any,\n  redactFn: RedactFunction,\n  path: string = \"\",\n  isProtected: boolean = false,\n  seen: WeakMap<object, any> = new WeakMap(),\n): Promise<any> {\n  if (obj === null || obj === undefined) {\n    return obj;\n  }\n\n  // Handle strings\n  if (typeof obj === \"string\") {\n    // Don't redact if this field or any parent field is protected\n    if (isProtected) {\n      return obj;\n    }\n    return await redactFn(obj);\n  }\n\n  // Handle arrays\n  if (Array.isArray(obj)) {\n    const existing = seen.get(obj);\n    if (existing) return existing;\n    const redactedArr: any[] = [];\n    // Register the clone BEFORE descending so a back-edge resolves to it.\n    seen.set(obj, redactedArr);\n    for (let index = 0; index < obj.length; index++) {\n      redactedArr[index] = await redactStringsInObject(\n        obj[index],\n        redactFn,\n        `${path}[${index}]`,\n        isProtected,\n        seen,\n      );\n    }\n    return redactedArr;\n  }\n\n  // Handle dates (don't redact)\n  if (obj instanceof Date) {\n    return obj;\n  }\n\n  // Handle objects\n  if (typeof obj === \"object\") {\n    const existing = seen.get(obj);\n    if (existing) return existing;\n    const redactedObj: any = {};\n    // Register the clone BEFORE descending so a back-edge resolves to it.\n    seen.set(obj, redactedObj);\n\n    for (const [key, value] of Object.entries(obj)) {\n      // Skip functions and undefined values\n      if (typeof value === \"function\" || value === undefined) {\n        continue;\n      }\n\n      // Build the path for nested fields\n      const fieldPath = path ? `${path}.${key}` : key;\n      // Check if this field is protected (only check at top level)\n      const isFieldProtected =\n        isProtected || (path === \"\" && PROTECTED_FIELDS.has(key));\n      redactedObj[key] = await redactStringsInObject(\n        value,\n        redactFn,\n        fieldPath,\n        isFieldProtected,\n        seen,\n      );\n    }\n\n    return redactedObj;\n  }\n\n  // For all other types (numbers, booleans, etc.), return as-is\n  return obj;\n}\n\n/**\n * Applies the customer's redaction function to all string fields in an Event object.\n * This is the main entry point for redacting sensitive information from events\n * before they are sent to the analytics service.\n *\n * @param event - The event to redact\n * @param redactFn - The customer's redaction function\n * @returns A new event object with all strings redacted\n */\nexport async function redactEvent(\n  event: UnredactedEvent,\n  redactFn: RedactFunction,\n): Promise<Event> {\n  return redactStringsInObject(event, redactFn, \"\", false) as Promise<Event>;\n}\n\n/**\n * Set of system-managed fields that are restored after the event-level\n * redaction hook runs. These are required for ingestion and session/project\n * attribution, so consumer changes to them are ignored.\n */\nconst RESTORED_FIELDS = [\n  \"id\",\n  \"sessionId\",\n  \"projectId\",\n  \"eventType\",\n  \"timestamp\",\n] as const;\n\n/**\n * Applies the customer's event-level redaction hook to an event, in place.\n * The hook receives the full event (without internal function fields) and may\n * return a modified event, or null/undefined to drop the event entirely.\n *\n * The event object is rewritten rather than replaced: the queue pipeline and\n * its observers hold references to the same object across processing steps,\n * and clearing before assigning ensures fields the hook deleted stay deleted.\n * System-managed fields are restored from the original, and the string-level\n * `redactionFn` is preserved so it still runs afterwards.\n *\n * @param event - The event to run the hook on; mutated with the hook's result\n * @param eventRedactFn - The customer's event-level redaction hook\n * @returns True if the event was kept, false if the hook dropped it\n */\nexport async function applyEventRedaction(\n  event: UnredactedEvent,\n  eventRedactFn: RedactEventFunction,\n): Promise<boolean> {\n  const { redactionFn, eventRedactionFn: _e, ...hookInput } = event;\n  const result = await eventRedactFn(hookInput as Event);\n\n  if (result === null || result === undefined) {\n    return false;\n  }\n\n  const redactedEvent: UnredactedEvent = { ...result, redactionFn };\n  delete redactedEvent.eventRedactionFn;\n\n  // System-managed fields are not consumer-settable\n  for (const field of RESTORED_FIELDS) {\n    if (event[field] === undefined) {\n      delete redactedEvent[field];\n    } else {\n      (redactedEvent as any)[field] = event[field];\n    }\n  }\n\n  for (const key of Object.keys(event)) {\n    delete event[key as keyof UnredactedEvent];\n  }\n  Object.assign(event, redactedEvent);\n  return true;\n}\n","import { PendingEventFields, UnredactedEvent } from \"../types.js\";\nimport { sessionFromHookValue } from \"./handles.js\";\nimport { AGENTCAT_TAG_SESSION_SOURCE } from \"./constants.js\";\nimport { writeToLog } from \"./logging.js\";\n\n/**\n * Budget for a deferred customer hook to settle once its event reaches the\n * background pipeline. Hooks are fired at request start, so by the time an\n * event is processed most have long settled; the budget only matters for a\n * hook that hangs — the event then publishes without that hook's data\n * instead of pinning a queue slot forever.\n */\nexport const PENDING_HOOK_TIMEOUT_MS = 30_000;\n\nconst TIMED_OUT = Symbol(\"agentcat.pending.timeout\");\n\n/**\n * Races a hook promise against the fixed budget. The inputs are constructed\n * non-rejecting (invokeSessionHook / the internal.ts resolvers), so the\n * catch here is belt-and-braces. The timer is cleared on settle so fast\n * hooks never hold the event loop open.\n */\nasync function settleWithTimeout<T>(\n  promise: Promise<T>,\n  label: string,\n): Promise<T | null> {\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  try {\n    const result = await Promise.race([\n      promise,\n      new Promise<typeof TIMED_OUT>((resolve) => {\n        timer = setTimeout(() => resolve(TIMED_OUT), PENDING_HOOK_TIMEOUT_MS);\n      }),\n    ]);\n    if (result === TIMED_OUT) {\n      writeToLog(\n        `Warning: ${label} hook did not settle within ${PENDING_HOOK_TIMEOUT_MS}ms; publishing event without it`,\n      );\n      return null;\n    }\n    return result as T;\n  } catch (error) {\n    writeToLog(`Warning: ${label} hook failed in background - ${error}`);\n    return null;\n  } finally {\n    if (timer !== undefined) clearTimeout(timer);\n  }\n}\n\n/**\n * Applies deferred hook results to an event, in place. Runs as stage 0 of\n * the queue pipeline — before the redactEvent hook, so redaction sees the\n * resolved sessionId/identity/tags/properties, and before sanitization and\n * truncation, so customer-supplied values still go through both.\n *\n * The four hooks are awaited concurrently: worst case adds one budget to\n * the event's background latency, not four.\n */\nexport async function applyPendingEventFields(\n  event: UnredactedEvent,\n  pending: PendingEventFields,\n): Promise<void> {\n  const [hookValue, identity, customerTags, properties] = await Promise.all([\n    pending.sessionHookValue\n      ? settleWithTimeout(pending.sessionHookValue, \"resolveSessionId\")\n      : null,\n    pending.identity ? settleWithTimeout(pending.identity, \"identify\") : null,\n    pending.tags ? settleWithTimeout(pending.tags, \"eventTags\") : null,\n    pending.properties\n      ? settleWithTimeout(pending.properties, \"eventProperties\")\n      : null,\n  ]);\n\n  if (pending.sessionHookValue) {\n    const { sessionId, sessionSource } = sessionFromHookValue(\n      hookValue,\n      event.projectId || undefined,\n    );\n    event.sessionId = sessionId;\n    event.tags = {\n      ...(event.tags ?? {}),\n      [AGENTCAT_TAG_SESSION_SOURCE]: sessionSource,\n    };\n  }\n\n  if (identity) {\n    event.identifyActorGivenId = identity.userId;\n    event.identifyActorName = identity.userName;\n    event.identifyActorData = identity.userData || {};\n  }\n\n  // SDK tags stay last-writer: the on-path tags (MRTR, handle, protocol —\n  // including the session-source finalized above) win name collisions.\n  if (customerTags) {\n    event.tags = { ...customerTags, ...(event.tags ?? {}) };\n  }\n\n  if (properties) {\n    event.properties = properties;\n  }\n}\n","import { Event, UnredactedEvent } from \"../types.js\";\n\nconst BASE64_PATTERN = /^[A-Za-z0-9+/\\n\\r]+=*$/;\nconst SIZE_GATE = 10240; // 10KB - skip strings shorter than this\n\n/**\n * Sanitizes an event by redacting non-text content blocks from responses\n * and large base64-encoded strings from parameters.\n *\n * This is a synchronous operation that returns a new object without mutating the original.\n * It should run after customer redaction in the event pipeline.\n */\nexport function sanitizeEvent<T extends Event | UnredactedEvent>(event: T): T {\n  const result = { ...event };\n\n  if (result.response != null) {\n    result.response = sanitizeResponse(result.response);\n  }\n\n  if (result.parameters != null) {\n    result.parameters = sanitizeParameters(result.parameters);\n  }\n\n  return result;\n}\n\n/**\n * Sanitizes response content blocks by replacing non-text content types\n * with informative redaction messages.\n */\nfunction sanitizeResponse(response: any): any {\n  if (response == null || typeof response !== \"object\") {\n    return response;\n  }\n\n  const result = { ...response };\n\n  if (Array.isArray(result.content)) {\n    result.content = result.content.map(sanitizeContentBlock);\n  }\n\n  if (\n    result.structuredContent != null &&\n    typeof result.structuredContent === \"object\"\n  ) {\n    result.structuredContent = sanitizeParameters(result.structuredContent);\n  }\n\n  return result;\n}\n\n/**\n * Sanitizes a single content block based on its type discriminator.\n */\nfunction sanitizeContentBlock(block: any): any {\n  if (block == null || typeof block !== \"object\") {\n    return block;\n  }\n\n  switch (block.type) {\n    case \"text\":\n      return block;\n\n    case \"image\":\n      return {\n        type: \"text\",\n        text: \"[image content redacted - not supported by AgentCat]\",\n      };\n\n    case \"audio\":\n      return {\n        type: \"text\",\n        text: \"[audio content redacted - not supported by AgentCat]\",\n      };\n\n    case \"resource\":\n      return sanitizeResourceBlock(block);\n\n    case \"resource_link\":\n      return block;\n\n    default:\n      return {\n        type: \"text\",\n        text: `[unsupported content type \"${block.type}\" redacted - not supported by AgentCat]`,\n      };\n  }\n}\n\n/**\n * Sanitizes an embedded resource content block.\n * BlobResourceContents (has `blob` field) are redacted.\n * TextResourceContents (has `text` field) pass through.\n */\nfunction sanitizeResourceBlock(block: any): any {\n  if (block.resource && block.resource.blob !== undefined) {\n    return {\n      type: \"text\",\n      text: \"[binary resource content redacted - not supported by AgentCat]\",\n    };\n  }\n  return block;\n}\n\n/**\n * Recursively scans parameters for large base64-encoded strings and replaces them.\n * Uses a size gate (10KB) to avoid regex testing on small strings.\n */\nfunction sanitizeParameters(obj: any): any {\n  if (obj == null) {\n    return obj;\n  }\n\n  if (typeof obj === \"string\") {\n    if (obj.length >= SIZE_GATE && BASE64_PATTERN.test(obj)) {\n      return \"[binary data redacted - not supported by AgentCat]\";\n    }\n    return obj;\n  }\n\n  if (Array.isArray(obj)) {\n    return obj.map(sanitizeParameters);\n  }\n\n  if (obj instanceof Date) {\n    return obj;\n  }\n\n  if (typeof obj === \"object\") {\n    const result: any = {};\n    for (const [key, value] of Object.entries(obj)) {\n      result[key] = sanitizeParameters(value);\n    }\n    return result;\n  }\n\n  return obj;\n}\n","import { Event, UnredactedEvent, StackFrame } from \"../types.js\";\n\n// --- Constants ---\nexport const MAX_DEPTH = 10;\nexport const MAX_BREADTH = 100;\nexport const MAX_STRING_LENGTH = 32_768; // 32KB\nexport const MAX_EVENT_BYTES = 102_400; // 100KB\n\n// --- Field-level limit constants ---\nconst MAX_USER_INTENT_LENGTH = 2_048;\nconst MAX_ERROR_MESSAGE_LENGTH = 2_048;\nconst MAX_RESOURCE_NAME_LENGTH = 256;\nconst MAX_METADATA_LENGTH = 256;\nconst MAX_STACK_FRAMES = 50;\nconst MAX_CONTENT_TEXT_LENGTH = 32_768;\n\n// --- Truncation markers ---\nconst TRUNCATION_SUFFIX = \"...\";\n\n/**\n * Recursively normalizes a value, handling:\n * - String truncation (> MAX_STRING_LENGTH)\n * - Non-serializable values (functions, symbols, undefined, BigInt, NaN, Infinity)\n * - Date objects -> ISO string\n * - Circular reference detection\n * - Depth limiting\n * - Breadth limiting\n */\nexport function normalize(\n  input: unknown,\n  depth: number = MAX_DEPTH,\n  maxBreadth: number = MAX_BREADTH,\n  maxStringLength: number = MAX_STRING_LENGTH,\n): unknown {\n  const memo = new WeakSet<object>();\n  return visit(input, depth, maxBreadth, maxStringLength, memo);\n}\n\nfunction visit(\n  value: unknown,\n  remainingDepth: number,\n  maxBreadth: number,\n  maxStringLength: number,\n  memo: WeakSet<object>,\n): unknown {\n  // null\n  if (value === null) return null;\n\n  // undefined\n  if (value === undefined) return \"[undefined]\";\n\n  // boolean\n  if (typeof value === \"boolean\") return value;\n\n  // number (including NaN, Infinity)\n  if (typeof value === \"number\") {\n    if (Number.isNaN(value)) return \"[NaN]\";\n    if (!Number.isFinite(value))\n      return value > 0 ? \"[Infinity]\" : \"[-Infinity]\";\n    return value;\n  }\n\n  // bigint\n  if (typeof value === \"bigint\") return `[BigInt: ${value}]`;\n\n  // string\n  if (typeof value === \"string\") {\n    if (value.length > maxStringLength) {\n      return value.slice(0, maxStringLength) + TRUNCATION_SUFFIX;\n    }\n    return value;\n  }\n\n  // symbol\n  if (typeof value === \"symbol\") {\n    const desc = value.description;\n    return desc ? `[Symbol(${desc})]` : \"[Symbol()]\";\n  }\n\n  // function\n  if (typeof value === \"function\") {\n    const name = value.name || \"<anonymous>\";\n    return `[Function: ${name}]`;\n  }\n\n  // Date\n  if (value instanceof Date) {\n    return Number.isNaN(value.getTime())\n      ? \"[Invalid Date]\"\n      : value.toISOString();\n  }\n\n  // Objects and arrays from here — need depth/breadth/circular checks\n  if (typeof value === \"object\") {\n    // Circular reference detection\n    if (memo.has(value)) return \"[Circular ~]\";\n\n    // Depth limit\n    if (remainingDepth <= 0) {\n      return Array.isArray(value) ? \"[Array]\" : \"[Object]\";\n    }\n\n    memo.add(value);\n\n    let result: unknown;\n    if (Array.isArray(value)) {\n      result = visitArray(\n        value,\n        remainingDepth - 1,\n        maxBreadth,\n        maxStringLength,\n        memo,\n      );\n    } else {\n      result = visitObject(\n        value as Record<string, unknown>,\n        remainingDepth - 1,\n        maxBreadth,\n        maxStringLength,\n        memo,\n      );\n    }\n\n    memo.delete(value);\n    return result;\n  }\n\n  // Fallback: coerce to string\n  return String(value);\n}\n\nfunction visitArray(\n  arr: unknown[],\n  remainingDepth: number,\n  maxBreadth: number,\n  maxStringLength: number,\n  memo: WeakSet<object>,\n): unknown[] {\n  const result: unknown[] = [];\n  for (let i = 0; i < arr.length; i++) {\n    if (i >= maxBreadth) {\n      result.push(\"[MaxProperties ~]\");\n      break;\n    }\n    result.push(\n      visit(arr[i], remainingDepth, maxBreadth, maxStringLength, memo),\n    );\n  }\n  return result;\n}\n\nfunction visitObject(\n  obj: Record<string, unknown>,\n  remainingDepth: number,\n  maxBreadth: number,\n  maxStringLength: number,\n  memo: WeakSet<object>,\n): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  const keys = Object.keys(obj);\n  let count = 0;\n\n  for (const key of keys) {\n    if (count >= maxBreadth) {\n      result[\"...\"] = \"[MaxProperties ~]\";\n      break;\n    }\n    // Skip undefined values — matches JSON.stringify behavior (omits undefined properties)\n    if (obj[key] === undefined) continue;\n    result[key] = visit(\n      obj[key],\n      remainingDepth,\n      maxBreadth,\n      maxStringLength,\n      memo,\n    );\n    count++;\n  }\n\n  return result;\n}\n\n// --- Field-level truncation helpers ---\n\nfunction truncateString(\n  str: string | undefined,\n  maxLength: number,\n): string | undefined {\n  if (str == null) return str;\n  if (str.length <= maxLength) return str;\n  return str.slice(0, maxLength) + TRUNCATION_SUFFIX;\n}\n\nfunction truncateStackFrames(\n  frames: StackFrame[] | undefined,\n): StackFrame[] | undefined {\n  if (!frames || frames.length <= MAX_STACK_FRAMES) return frames;\n  const half = Math.floor(MAX_STACK_FRAMES / 2);\n  return [...frames.slice(0, half), ...frames.slice(-half)];\n}\n\nfunction truncateResponseContent(response: any): any {\n  if (response == null || typeof response !== \"object\") return response;\n  const result = { ...response };\n  if (Array.isArray(result.content)) {\n    result.content = result.content.map((block: any) => {\n      if (\n        block?.type === \"text\" &&\n        typeof block.text === \"string\" &&\n        block.text.length > MAX_CONTENT_TEXT_LENGTH\n      ) {\n        return {\n          ...block,\n          text:\n            block.text.slice(0, MAX_CONTENT_TEXT_LENGTH) + TRUNCATION_SUFFIX,\n        };\n      }\n      return block;\n    });\n  }\n  return result;\n}\n\n/**\n * Calculates the UTF-8 byte size of a JSON-serialized value.\n */\nconst textEncoder = new TextEncoder();\n\nfunction jsonByteSize(value: unknown): number {\n  return textEncoder.encode(JSON.stringify(value)).length;\n}\n\n/**\n * Finds and truncates the largest string values in an object to fit within a byte budget.\n * Last-resort mechanism when depth reduction alone isn't enough.\n * Iterates until the result fits or no further reduction is possible.\n */\nfunction truncateLargestFields(obj: any, maxBytes: number): any {\n  let result = structuredClone(obj);\n\n  for (let attempt = 0; attempt < 10; attempt++) {\n    const currentSize = jsonByteSize(result);\n    if (currentSize <= maxBytes) return result;\n\n    const excess = currentSize - maxBytes;\n\n    // Find all string values and their sizes, sorted largest first\n    const stringPaths: Array<{ path: string[]; length: number }> = [];\n    collectStringPaths(result, [], stringPaths);\n    stringPaths.sort((a, b) => b.length - a.length);\n\n    if (stringPaths.length === 0) break; // no strings left to truncate\n\n    // Distribute the reduction across the largest strings\n    let remaining = excess + 200; // buffer for JSON overhead from added \"...\" suffixes\n    let truncated = false;\n\n    for (const { path, length } of stringPaths) {\n      if (remaining <= 0) break;\n      const reduction = Math.min(remaining, Math.floor(length * 0.5));\n      if (reduction < 10) continue; // not worth truncating tiny strings\n      const newLength = length - reduction;\n      setNestedValue(\n        result,\n        path,\n        getNestedValue(result, path).slice(0, newLength) + TRUNCATION_SUFFIX,\n      );\n      remaining -= reduction;\n      truncated = true;\n    }\n\n    if (!truncated) break; // no progress possible\n  }\n\n  return result;\n}\n\nfunction collectStringPaths(\n  obj: any,\n  currentPath: string[],\n  results: Array<{ path: string[]; length: number }>,\n): void {\n  if (typeof obj === \"string\" && obj.length > 100) {\n    results.push({ path: [...currentPath], length: obj.length });\n    return;\n  }\n  if (Array.isArray(obj)) {\n    obj.forEach((item, i) =>\n      collectStringPaths(item, [...currentPath, String(i)], results),\n    );\n    return;\n  }\n  if (obj != null && typeof obj === \"object\") {\n    for (const [key, value] of Object.entries(obj)) {\n      collectStringPaths(value, [...currentPath, key], results);\n    }\n  }\n}\n\nfunction getNestedValue(obj: any, path: string[]): any {\n  let current = obj;\n  for (const key of path) current = current[key];\n  return current;\n}\n\nfunction setNestedValue(obj: any, path: string[], value: any): void {\n  let current = obj;\n  for (let i = 0; i < path.length - 1; i++) current = current[path[i]];\n  current[path[path.length - 1]] = value;\n}\n\n/**\n * Ensures an event fits within MAX_EVENT_BYTES by progressively reducing\n * normalization depth, then truncating largest string fields as a last resort.\n */\nfunction truncateToSize(event: any): any {\n  // Check if already within budget\n  if (jsonByteSize(event) <= MAX_EVENT_BYTES) return event;\n\n  // Progressive depth reduction\n  for (let depth = MAX_DEPTH - 1; depth >= 1; depth--) {\n    const reduced: any = { ...event };\n    if (reduced.parameters != null)\n      reduced.parameters = normalize(reduced.parameters, depth);\n    if (reduced.response != null)\n      reduced.response = normalize(reduced.response, depth);\n    if (reduced.identifyActorData != null)\n      reduced.identifyActorData = normalize(reduced.identifyActorData, depth);\n    if (reduced.error != null) reduced.error = normalize(reduced.error, depth);\n\n    if (jsonByteSize(reduced) <= MAX_EVENT_BYTES) return reduced;\n  }\n\n  // Last resort: truncate largest string fields\n  const minimal: any = { ...event };\n  if (minimal.parameters != null)\n    minimal.parameters = normalize(minimal.parameters, 1);\n  if (minimal.response != null)\n    minimal.response = normalize(minimal.response, 1);\n  if (minimal.identifyActorData != null)\n    minimal.identifyActorData = normalize(minimal.identifyActorData, 1);\n  if (minimal.error != null) minimal.error = normalize(minimal.error, 1);\n\n  return truncateLargestFields(minimal, MAX_EVENT_BYTES);\n}\n\n/**\n * Applies layered truncation to an event:\n * 1. Field-level string limits (userIntent, resourceName, metadata fields, error.message)\n * 2. Error frame limiting (first 25 + last 25 if > 50)\n * 3. Response content text limits (32KB per text block)\n * 4. Recursive normalization on user-controlled fields\n * 5. Size-targeted truncation (progressive depth reduction + last-resort string truncation)\n */\nexport function truncateEvent<T extends Event | UnredactedEvent>(event: T): T {\n  const result: any = { ...event };\n\n  // Layer 1: Field-level string limits\n  result.userIntent = truncateString(result.userIntent, MAX_USER_INTENT_LENGTH);\n  result.resourceName = truncateString(\n    result.resourceName,\n    MAX_RESOURCE_NAME_LENGTH,\n  );\n  result.serverName = truncateString(result.serverName, MAX_METADATA_LENGTH);\n  result.serverVersion = truncateString(\n    result.serverVersion,\n    MAX_METADATA_LENGTH,\n  );\n  result.clientName = truncateString(result.clientName, MAX_METADATA_LENGTH);\n  result.clientVersion = truncateString(\n    result.clientVersion,\n    MAX_METADATA_LENGTH,\n  );\n\n  // Error field limits\n  if (result.error != null && typeof result.error === \"object\") {\n    result.error = { ...result.error };\n    result.error.message = truncateString(\n      result.error.message,\n      MAX_ERROR_MESSAGE_LENGTH,\n    );\n    if (result.error.frames !== undefined) {\n      result.error.frames = truncateStackFrames(result.error.frames);\n    }\n  }\n\n  // Response content text limits\n  result.response = truncateResponseContent(result.response);\n\n  // Layer 2: Recursive normalization on user-controlled fields\n  if (result.parameters != null) {\n    result.parameters = normalize(result.parameters);\n  }\n  if (result.response != null) {\n    result.response = normalize(result.response);\n  }\n  if (result.identifyActorData != null) {\n    result.identifyActorData = normalize(result.identifyActorData);\n  }\n  if (result.error != null) {\n    result.error = normalize(result.error);\n  }\n\n  // Layer 3: Size-targeted normalization\n  return truncateToSize(result) as T;\n}\n","import { HighLevelMCPServerLike, MCPServerLike } from \"../types.js\";\nimport { detectServer, fingerprintServerShape } from \"../detect.js\";\nimport { writeToLog } from \"./logging.js\";\n\n/**\n * AgentCat Compatibility Module\n *\n * Ensures compatibility with the Model Context Protocol TypeScript SDK.\n * AgentCat supports SDK v1.11+ (@modelcontextprotocol/sdk) and v2\n * (@modelcontextprotocol/server). Flavor/major discrimination is owned by\n * detectServer(); this module validates the detected low-level server's\n * internals and produces every compatibility-facing error message.\n */\n\nexport const SUPPORT_MATRIX_SUFFIX =\n  \"AgentCat supports MCP TypeScript SDK v1.11+ (@modelcontextprotocol/sdk) and v2 (@modelcontextprotocol/server).\";\n\n// Function to log compatibility information\nexport function logCompatibilityWarning(): void {\n  writeToLog(`AgentCat SDK Compatibility: ${SUPPORT_MATRIX_SUFFIX}`);\n}\n\n// Check if server has high-level structure (wrapper with .server property)\nexport function isHighLevelServer(server: any): boolean {\n  return (\n    server &&\n    typeof server === \"object\" &&\n    server.server &&\n    typeof server.server === \"object\"\n  );\n}\n\n// Check if server has low-level structure (no .server property)\nexport function isLowLevelServer(server: any): boolean {\n  return server && typeof server === \"object\" && !server.server;\n}\n\n// Type guard function that validates server compatibility and returns typed server\nexport function isCompatibleServerType(\n  server: any,\n): MCPServerLike | HighLevelMCPServerLike {\n  const detection = detectServer(server);\n  if (!detection) {\n    // Shape-fingerprint beacon: the signals detection computed, preserved in\n    // the diagnostics sink so fleet change-detection can spot a new SDK shape.\n    writeToLog(\n      `AgentCat SDK Compatibility: unrecognized server shape | signals ${fingerprintServerShape(server) || \"(none)\"}. ${SUPPORT_MATRIX_SUFFIX}`,\n    );\n    throw new Error(\n      `AgentCat SDK compatibility error: server object does not match any supported MCP SDK shape. ${SUPPORT_MATRIX_SUFFIX}`,\n    );\n  }\n  validateLowLevelServer(detection.lowLevel);\n  return detection.highLevel ?? detection.lowLevel;\n}\n\n// Helper function to validate low-level server requirements\nfunction validateLowLevelServer(server: any): void {\n  if (typeof server.setRequestHandler !== \"function\") {\n    logCompatibilityWarning();\n    throw new Error(\n      \"AgentCat SDK compatibility error: Server must have a setRequestHandler method. \" +\n        SUPPORT_MATRIX_SUFFIX,\n    );\n  }\n\n  if (!server._requestHandlers || !(server._requestHandlers instanceof Map)) {\n    logCompatibilityWarning();\n    throw new Error(\n      \"AgentCat SDK compatibility error: Server._requestHandlers is not accessible. \" +\n        SUPPORT_MATRIX_SUFFIX,\n    );\n  }\n\n  // Validate that _requestHandlers contains functions with compatible signatures\n  if (typeof server._requestHandlers.get !== \"function\") {\n    logCompatibilityWarning();\n    throw new Error(\n      \"AgentCat SDK compatibility error: Server._requestHandlers must be a Map with a get method. \" +\n        SUPPORT_MATRIX_SUFFIX,\n    );\n  }\n\n  if (typeof server.getClientVersion !== \"function\") {\n    logCompatibilityWarning();\n    throw new Error(\n      \"AgentCat SDK compatibility error: Server.getClientVersion must be a function. \" +\n        SUPPORT_MATRIX_SUFFIX,\n    );\n  }\n\n  if (\n    !server._serverInfo ||\n    typeof server._serverInfo !== \"object\" ||\n    !server._serverInfo.name\n  ) {\n    logCompatibilityWarning();\n    throw new Error(\n      \"AgentCat SDK compatibility error: Server._serverInfo is not accessible or missing name. \" +\n        SUPPORT_MATRIX_SUFFIX,\n    );\n  }\n}\n\nexport function getMCPCompatibleErrorMessage(error: unknown): string {\n  if (error instanceof Error) {\n    try {\n      return JSON.stringify(error, Object.getOwnPropertyNames(error));\n    } catch {\n      return \"Unknown error\";\n    }\n  } else if (typeof error === \"string\") {\n    return error;\n  } else if (typeof error === \"object\" && error !== null) {\n    return JSON.stringify(error);\n  }\n  return \"Unknown error\";\n}\n","// src/modules/diagnostics.ts\nimport { setDiagnosticsSink } from \"./logging.js\";\nimport { loadNodeModule, getRuntimeVersions } from \"./runtime-versions.js\";\nimport {\n  DIAGNOSTICS_SCOPE_NAME,\n  DEFAULT_DIAGNOSTICS_ENDPOINT,\n  DEFAULT_DIAGNOSTICS_TOKEN,\n} from \"./constants.js\";\nimport packageJson from \"../../package.json\" with { type: \"json\" };\n\nlet enabled = false;\nlet initialized = false;\n\ninterface OtlpAttribute {\n  key: string;\n  value: { stringValue: string };\n}\n\nlet staticAttributes: OtlpAttribute[] = [];\n\nconst MAX_BUFFER = 1000;\nconst BATCH_FLUSH_MS = 2000;\nlet buffer: OtlpLogRecord[] = [];\nlet flushTimer: ReturnType<typeof setTimeout> | null = null;\n\nfunction resolveEndpoint(): string {\n  let base = DEFAULT_DIAGNOSTICS_ENDPOINT;\n  try {\n    base = globalThis.process?.env?.DIAGNOSTICS_ENDPOINT || base;\n  } catch {\n    // ignore\n  }\n  const trimmed = base.replace(/\\/+$/, \"\");\n  return trimmed.endsWith(\"/v1/logs\") ? trimmed : `${trimmed}/v1/logs`;\n}\n\nfunction resolveToken(): string {\n  try {\n    return (\n      globalThis.process?.env?.DIAGNOSTICS_TOKEN || DEFAULT_DIAGNOSTICS_TOKEN\n    );\n  } catch {\n    return DEFAULT_DIAGNOSTICS_TOKEN;\n  }\n}\n\nfunction scheduleFlush(): void {\n  if (flushTimer) return;\n  try {\n    flushTimer = setTimeout(() => {\n      flushTimer = null;\n      void flushDiagnostics();\n    }, BATCH_FLUSH_MS);\n    // Do not keep the event loop alive solely for diagnostics.\n    (flushTimer as any)?.unref?.();\n  } catch {\n    flushTimer = null;\n  }\n}\n\nfunction attr(key: string, value: string | undefined | null): OtlpAttribute[] {\n  return value ? [{ key, value: { stringValue: String(value) } }] : [];\n}\n\nfunction computeInstallId(): string | null {\n  try {\n    const os = loadNodeModule<typeof import(\"os\")>(\"os\");\n    const crypto = loadNodeModule<typeof import(\"crypto\")>(\"crypto\");\n    if (!os || !crypto) return null;\n    const seed = `${os.hostname?.() ?? \"\"}|${import.meta.url}`;\n    return crypto.createHash(\"sha256\").update(seed).digest(\"hex\").slice(0, 16);\n  } catch {\n    return null;\n  }\n}\n\nfunction buildStaticAttributes(projectId: string | null): OtlpAttribute[] {\n  const out: OtlpAttribute[] = [];\n  try {\n    // Identity / traceability\n    if (projectId) {\n      out.push(...attr(\"agentcat.project_id\", projectId));\n    } else {\n      out.push(...attr(\"agentcat.install_id\", computeInstallId()));\n    }\n\n    // SDK\n    out.push(...attr(\"agentcat.sdk.language\", \"typescript\"));\n    out.push(...attr(\"agentcat.sdk.version\", packageJson.version));\n\n    // Best-effort: resolved MCP SDK versions (both majors are optional peers).\n    const versions = getRuntimeVersions();\n    out.push(...attr(\"agentcat.mcp_sdk.version\", versions.mcpV1));\n    out.push(...attr(\"agentcat.mcp_sdk_v2.version\", versions.mcpV2));\n\n    // Runtime\n    const proc = globalThis.process;\n    out.push(\n      ...attr(\n        \"process.runtime.name\",\n        proc?.versions?.node ? \"nodejs\" : \"other\",\n      ),\n    );\n    out.push(...attr(\"process.runtime.version\", proc?.version));\n    out.push(\n      ...attr(\"process.pid\", proc?.pid != null ? String(proc.pid) : null),\n    );\n\n    // OS / host\n    const os = loadNodeModule<typeof import(\"os\")>(\"os\");\n    if (os) {\n      out.push(...attr(\"os.type\", os.platform?.()));\n      out.push(...attr(\"os.version\", os.release?.()));\n      out.push(...attr(\"host.arch\", os.arch?.()));\n      out.push(\n        ...attr(\"host.cpu.count\", os.cpus ? String(os.cpus().length) : null),\n      );\n    }\n\n    // Deploy/CI hints\n    out.push(...attr(\"deployment.environment\", proc?.env?.NODE_ENV));\n  } catch {\n    // best-effort; partial attributes are fine\n  }\n  return out;\n}\n\nexport function _getStaticAttributesForTest(): OtlpAttribute[] {\n  return staticAttributes;\n}\n\ninterface OtlpLogRecord {\n  timeUnixNano: string;\n  severityNumber: number;\n  severityText: string;\n  body: { stringValue: string };\n  attributes: OtlpAttribute[];\n}\n\nfunction inferSeverity(entry: string): { number: number; text: string } {\n  if (/fail|error/i.test(entry)) return { number: 17, text: \"ERROR\" };\n  if (entry.includes(\"Warning:\")) return { number: 13, text: \"WARN\" };\n  return { number: 9, text: \"INFO\" };\n}\n\n// Version attributes ride on every record (not just the resource) so records\n// stay attributable after pipelines flatten them away from the resource\n// envelope. Built once: the versions cannot change within a process.\nlet versionRecordAttributes: OtlpAttribute[] | null = null;\n\nfunction getVersionRecordAttributes(): OtlpAttribute[] {\n  if (!versionRecordAttributes) {\n    const versions = getRuntimeVersions();\n    versionRecordAttributes = [\n      ...attr(\"agentcat.sdk.version\", versions.sdk),\n      ...attr(\"process.runtime.version\", versions.node),\n      ...attr(\"agentcat.mcp_sdk.version\", versions.mcpV1),\n      ...attr(\"agentcat.mcp_sdk_v2.version\", versions.mcpV2),\n    ];\n  }\n  return versionRecordAttributes;\n}\n\nfunction buildRecord(entry: string): OtlpLogRecord {\n  const sev = inferSeverity(entry);\n  return {\n    timeUnixNano: (BigInt(Date.now()) * BigInt(1_000_000)).toString(),\n    severityNumber: sev.number,\n    severityText: sev.text,\n    body: { stringValue: entry },\n    attributes: getVersionRecordAttributes(),\n  };\n}\n\nexport function _buildRecordForTest(entry: string): OtlpLogRecord {\n  return buildRecord(entry);\n}\n\nfunction isTestEnvironment(): boolean {\n  try {\n    const env = globalThis.process?.env;\n    return Boolean(\n      env?.VITEST || env?.JEST_WORKER_ID || env?.NODE_ENV === \"test\",\n    );\n  } catch {\n    return false;\n  }\n}\n\nfunction envDiagnosticsFlag(): \"disabled\" | \"force-enabled\" | \"unset\" {\n  try {\n    const raw = globalThis.process?.env?.DISABLE_DIAGNOSTICS;\n    if (raw == null || raw.trim() === \"\") return \"unset\";\n    // Interpret the value rather than treating mere presence as truthy. An\n    // explicitly falsy value (DISABLE_DIAGNOSTICS=false / 0 / no / off) is a\n    // deliberate opt-in that also overrides test-environment detection.\n    const normalized = raw.trim().toLowerCase();\n    return [\"false\", \"0\", \"no\", \"off\"].includes(normalized)\n      ? \"force-enabled\"\n      : \"disabled\";\n  } catch {\n    return \"unset\";\n  }\n}\n\nexport function initDiagnostics(opts: {\n  projectId: string | null;\n  disabled?: boolean;\n}): void {\n  try {\n    if (initialized) return;\n    initialized = true;\n    const flag = envDiagnosticsFlag();\n    enabled =\n      !opts.disabled &&\n      flag !== \"disabled\" &&\n      (flag === \"force-enabled\" || !isTestEnvironment());\n    if (!enabled) return;\n    staticAttributes = buildStaticAttributes(opts.projectId);\n    setDiagnosticsSink(capture);\n  } catch {\n    // diagnostics init must never throw\n  }\n}\n\nfunction capture(entry: string): void {\n  try {\n    if (!enabled) return;\n    if (buffer.length >= MAX_BUFFER) buffer.shift();\n    buffer.push(buildRecord(entry));\n    scheduleFlush();\n  } catch {\n    // diagnostics capture must never throw\n  }\n}\n\nexport async function flushDiagnostics(): Promise<void> {\n  try {\n    if (!enabled || buffer.length === 0) return;\n    const records = buffer;\n    buffer = [];\n\n    const payload = {\n      resourceLogs: [\n        {\n          resource: { attributes: staticAttributes },\n          scopeLogs: [\n            {\n              scope: {\n                name: DIAGNOSTICS_SCOPE_NAME,\n                version: packageJson.version,\n              },\n              logRecords: records,\n            },\n          ],\n        },\n      ],\n    };\n\n    const token = resolveToken();\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n    };\n    if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n\n    await fetch(resolveEndpoint(), {\n      method: \"POST\",\n      headers,\n      body: JSON.stringify(payload),\n    });\n  } catch {\n    // fire-and-forget: never propagate diagnostics network errors\n  }\n}\n\nexport function isDiagnosticsEnabled(): boolean {\n  return enabled;\n}\n\nexport function _resetDiagnosticsForTest(): void {\n  enabled = false;\n  initialized = false;\n  staticAttributes = [];\n  versionRecordAttributes = null;\n  buffer = [];\n  if (flushTimer) {\n    clearTimeout(flushTimer);\n    flushTimer = null;\n  }\n  setDiagnosticsSink(null);\n}\n","import { getMCPCompatibleErrorMessage } from \"./compatibility.js\";\nimport { writeToLog } from \"./logging.js\";\n\nexport type BackgroundTaskRegistrar = (task: Promise<void>) => void;\n\nlet backgroundTaskRegistrar: BackgroundTaskRegistrar | undefined;\n\n/**\n * Installs the runtime-specific background task registrar.\n *\n * This is intentionally internal. Runtime entrypoints configure it so public\n * AgentCat APIs stay environment-agnostic.\n */\nexport function setBackgroundTaskRegistrar(\n  registrar: BackgroundTaskRegistrar | undefined,\n): void {\n  backgroundTaskRegistrar = registrar;\n}\n\n/**\n * Extends the current runtime invocation for a task when the active runtime\n * supports it. Registration failures are fail-open so analytics can never\n * break the customer's request.\n */\nexport function registerBackgroundTask(task: Promise<void>): void {\n  if (!backgroundTaskRegistrar) return;\n\n  try {\n    backgroundTaskRegistrar(task);\n  } catch (error) {\n    writeToLog(\n      `Failed to register AgentCat event delivery as a background task: ${getMCPCompatibleErrorMessage(error)}`,\n    );\n  }\n}\n","import { createRequire } from \"module\";\nimport { ErrorData, StackFrame, ChainedErrorData } from \"../types.js\";\n\n// Lazy-loaded fs module for context_line extraction (Node.js only)\n// Edge environments don't have filesystem access\nlet fsModule: typeof import(\"fs\") | null = null;\nlet fsInitAttempted = false;\n\nfunction getFsSync(): typeof import(\"fs\") | null {\n  if (!fsInitAttempted) {\n    fsInitAttempted = true;\n    try {\n      // Use createRequire for ESM compatibility\n      // Works in Node.js ESM/CJS, fails gracefully in Workers/edge environments\n      const require = createRequire(import.meta.url);\n      fsModule = require(\"fs\");\n    } catch {\n      fsModule = null;\n    }\n  }\n  return fsModule;\n}\n\n// Maximum number of exceptions to capture in a cause chain\nconst MAX_EXCEPTION_CHAIN_DEPTH = 10;\n\n// Maximum number of stack frames to capture per exception\nconst MAX_STACK_FRAMES = 50;\n\n/**\n * Captures detailed exception information including stack traces and cause chains.\n *\n * This function extracts error metadata (type, message, stack trace) and recursively\n * unwraps Error.cause chains. It parses V8 stack traces into structured frames and\n * detects whether each frame is user code (in_app: true) or library code (in_app: false).\n *\n * @param error - The error to capture (can be Error, string, object, or any value)\n * @param contextStack - Optional Error object to use for stack context (for validation errors)\n * @returns ErrorData object with structured error information\n */\nexport function captureException(\n  error: unknown,\n  contextStack?: Error,\n): ErrorData {\n  // Handle CallToolResult objects (SDK 1.21.0+ converts errors to these)\n  if (isCallToolResult(error)) {\n    return captureCallToolResultError(error, contextStack);\n  }\n\n  // Handle non-Error objects\n  if (!(error instanceof Error)) {\n    return {\n      message: stringifyNonError(error),\n      type: undefined,\n      platform: \"javascript\",\n    };\n  }\n\n  const errorData: ErrorData = {\n    message: error.message || \"\",\n    type: error.name || error.constructor?.name || undefined,\n    platform: \"javascript\",\n  };\n\n  // Capture stack trace if available\n  if (error.stack) {\n    errorData.stack = error.stack;\n    errorData.frames = parseV8StackTrace(error.stack);\n  }\n\n  // Unwrap Error.cause chain\n  const chainedErrors = unwrapErrorCauses(error);\n  if (chainedErrors.length > 0) {\n    errorData.chained_errors = chainedErrors;\n  }\n\n  return errorData;\n}\n\n/**\n * Parses V8 stack trace string into structured StackFrame array.\n *\n * V8 stack traces have the format:\n *   Error: message\n *   at functionName (filename:line:col)\n *   at Object.method (filename:line:col)\n *   ...\n *\n * This function handles various V8 format variations including:\n * - Regular functions: \"at functionName (file:10:5)\"\n * - Anonymous functions: \"at file:10:5\"\n * - Async functions: \"at async functionName (file:10:5)\"\n * - Object methods: \"at Object.method (file:10:5)\"\n * - Native code: \"at Array.map (native)\"\n *\n * @param stackTrace - Raw V8 stack trace string from Error.stack\n * @returns Array of parsed StackFrame objects (limited to MAX_STACK_FRAMES)\n */\nfunction parseV8StackTrace(stackTrace: string): StackFrame[] {\n  const frames: StackFrame[] = [];\n  const lines = stackTrace.split(\"\\n\");\n\n  for (const line of lines) {\n    // Skip the first line (error message) and empty lines\n    if (!line.trim().startsWith(\"at \")) {\n      continue;\n    }\n\n    const frame = parseV8StackFrame(line.trim());\n    if (frame) {\n      addContextToFrame(frame);\n      frames.push(frame);\n    }\n\n    // Limit number of frames\n    if (frames.length >= MAX_STACK_FRAMES) {\n      break;\n    }\n  }\n\n  return frames;\n}\n\n/**\n * Adds context_line to a stack frame by reading the source file.\n *\n * This function extracts the line of code where the error occurred by:\n * 1. Reading the source file using abs_path\n * 2. Extracting the line at the specified line number\n * 3. Setting the context_line field on the frame\n *\n * Only extracts context for user code (in_app: true)\n * If the file cannot be read or the line number is invalid, context_line remains undefined.\n *\n * @param frame - The StackFrame to add context to (modified in place)\n * @returns The modified StackFrame\n */\nfunction addContextToFrame(frame: StackFrame): StackFrame {\n  if (!frame.in_app || !frame.abs_path || !frame.lineno) {\n    return frame;\n  }\n\n  // Get fs module lazily - returns null in edge environments\n  const fs = getFsSync();\n  if (!fs) {\n    return frame; // File reading not available in this environment\n  }\n\n  try {\n    const source = fs.readFileSync(frame.abs_path, \"utf8\");\n    const lines = source.split(\"\\n\");\n    const lineIndex = frame.lineno - 1; // Convert to 0-based index\n\n    if (lineIndex >= 0 && lineIndex < lines.length) {\n      frame.context_line = lines[lineIndex];\n    }\n  } catch {\n    // File not found or not readable - silently skip\n  }\n\n  return frame;\n}\n\n/**\n * Parses a location string from a V8 stack frame.\n *\n * Handles different location formats:\n * - \"fileName:lineNumber:columnNumber\" - normal file location\n * - \"eval at functionName (location)\" - eval'd code (recursively unwraps)\n * - \"native\" - V8 internal code\n * - \"unknown location\" - location unavailable\n *\n * @param location - Location string from stack frame\n * @returns Object with filename, abs_path, and optional lineno/colno, or null if unparseable\n */\nfunction parseLocation(location: string): {\n  filename: string;\n  abs_path: string;\n  lineno?: number;\n  colno?: number;\n} | null {\n  // Handle special cases first\n  if (location === \"native\") {\n    return { filename: \"native\", abs_path: \"native\" };\n  }\n\n  if (location === \"unknown location\") {\n    return { filename: \"<unknown>\", abs_path: \"<unknown>\" };\n  }\n\n  // Handle eval locations\n  if (location.startsWith(\"eval at \")) {\n    return parseEvalOrigin(location);\n  }\n\n  // Handle normal location format: fileName:lineNumber:columnNumber\n  const match = location.match(/^(.+):(\\d+):(\\d+)$/);\n  if (match) {\n    const [, filename, lineStr, colStr] = match;\n    return {\n      filename: makeRelativePath(filename),\n      abs_path: filename,\n      lineno: parseInt(lineStr, 10),\n      colno: parseInt(colStr, 10),\n    };\n  }\n\n  return null;\n}\n\n/**\n * Recursively unwraps eval location chains to extract the underlying file location.\n *\n * Eval locations have the format: \"eval at functionName (location), <anonymous>:line:col\"\n * where location can be another eval or a file location.\n *\n * V8 formats:\n * - \"eval at Bar.z (myscript.js:10:3)\" → extract myscript.js:10:3\n * - \"eval at Foo (eval at Bar (file.js:10:3)), <anonymous>:5:2\" → extract file.js:10:3\n *\n * @param evalLocation - Eval location string starting with \"eval at \"\n * @returns Object with extracted file location, or null if unparseable\n */\nfunction parseEvalOrigin(evalLocation: string): {\n  filename: string;\n  abs_path: string;\n  lineno?: number;\n  colno?: number;\n} | null {\n  // V8 format: \"eval at functionName (parentLocation), <anonymous>:line:col\"\n  // or simpler: \"eval at functionName (parentLocation)\"\n  //\n  // Strategy: Find balanced parentheses to extract the parent location,\n  // then recursively parse it to find the actual file.\n\n  // First, check if there's a comma separating eval chain from eval code location\n  // Format: \"eval at FUNC (...), <anonymous>:line:col\"\n  // We want to extract just the \"eval at FUNC (...)\" part\n  let evalChainPart = evalLocation;\n  const commaIndex = findCommaAfterBalancedParens(evalLocation);\n  if (commaIndex !== -1) {\n    evalChainPart = evalLocation.substring(0, commaIndex);\n  }\n\n  // Match \"eval at <anything> (<innerLocation>)\"\n  const match = evalChainPart.match(/^eval at (.+?) \\((.+)\\)$/);\n  if (!match) {\n    return null;\n  }\n\n  const innerLocation = match[2];\n\n  // Recursively parse the inner location\n  if (innerLocation.startsWith(\"eval at \")) {\n    return parseEvalOrigin(innerLocation);\n  }\n\n  // Base case: parse as normal location\n  const locationMatch = innerLocation.match(/^(.+):(\\d+):(\\d+)$/);\n  if (locationMatch) {\n    const [, filename, lineStr, colStr] = locationMatch;\n    return {\n      filename: makeRelativePath(filename),\n      abs_path: filename,\n      lineno: parseInt(lineStr, 10),\n      colno: parseInt(colStr, 10),\n    };\n  }\n\n  return null;\n}\n\n/**\n * Finds the index of the comma that appears after balanced parentheses.\n *\n * For \"eval at f (eval at g (x)), <anonymous>:1:2\", returns the index of the comma\n * after the closing \")\" and before \"<anonymous>\".\n *\n * @param str - String to search\n * @returns Index of comma, or -1 if not found\n */\nfunction findCommaAfterBalancedParens(str: string): number {\n  let depth = 0;\n  let foundOpenParen = false;\n\n  for (let i = 0; i < str.length; i++) {\n    if (str[i] === \"(\") {\n      depth++;\n      foundOpenParen = true;\n    } else if (str[i] === \")\") {\n      depth--;\n      if (depth === 0 && foundOpenParen) {\n        // Found the closing paren of the eval at (...) part\n        for (let j = i + 1; j < str.length; j++) {\n          if (str[j] === \",\") {\n            return j;\n          } else if (str[j] !== \" \") {\n            // Non-comma, non-space character found, no comma separator\n            return -1;\n          }\n        }\n        return -1;\n      }\n    }\n  }\n\n  return -1;\n}\n\n/**\n * Parses a single V8 stack frame line into a StackFrame object.\n *\n * Handles multiple V8 stack frame formats:\n * - \"at functionName (filename:line:col)\"\n * - \"at filename:line:col\" (top-level code)\n * - \"at async functionName (filename:line:col)\"\n * - \"at Object.method (filename:line:col)\"\n * - \"at Module._compile (node:internal/...)\" (internal modules)\n * - \"at functionName (eval at ...)\" (eval'd code)\n * - \"at functionName (native)\" (native code)\n *\n * @param line - Single line from V8 stack trace (trimmed, starts with \"at \")\n * @returns Parsed StackFrame or null if line cannot be parsed\n */\nfunction parseV8StackFrame(line: string): StackFrame | null {\n  // Remove \"at \" prefix\n  const withoutAt = line.substring(3);\n\n  // Try to extract function name and location\n  // Format 1: \"functionName (location)\"\n  // Location can be: filename:line:col, eval at ..., native, unknown location\n  const matchWithFunction = withoutAt.match(/^(.+?)\\s+\\((.+)\\)$/);\n  if (matchWithFunction) {\n    const [, functionName, location] = matchWithFunction;\n    const parsedLocation = parseLocation(location);\n\n    if (parsedLocation) {\n      return {\n        function: functionName.trim(),\n        filename: parsedLocation.filename,\n        abs_path: parsedLocation.abs_path,\n        lineno: parsedLocation.lineno,\n        colno: parsedLocation.colno,\n        in_app: isInApp(parsedLocation.abs_path),\n      };\n    }\n  }\n\n  // Format 2: \"location\" (no function name, top-level code)\n  // Try to parse as location directly\n  const parsedLocation = parseLocation(withoutAt);\n  if (parsedLocation) {\n    return {\n      function: \"<anonymous>\",\n      filename: parsedLocation.filename,\n      abs_path: parsedLocation.abs_path,\n      lineno: parsedLocation.lineno,\n      colno: parsedLocation.colno,\n      in_app: isInApp(parsedLocation.abs_path),\n    };\n  }\n\n  // Format 3: Unparseable\n  // Fallback for formats we don't recognize\n  return {\n    function: withoutAt,\n    filename: \"<unknown>\",\n    in_app: false,\n  };\n}\n\n/**\n * Determines if a file path represents user code (in_app: true) or library code (in_app: false).\n *\n * Library code is identified by:\n * - Paths containing \"/node_modules/\"\n * - Node.js internal modules (e.g., \"node:internal/...\")\n * - Native code\n *\n * @param filename - File path from stack frame\n * @returns true if user code, false if library code\n */\nfunction isInApp(filename: string): boolean {\n  // Exclude node_modules\n  if (\n    filename.includes(\"/node_modules/\") ||\n    filename.includes(\"\\\\node_modules\\\\\")\n  ) {\n    return false;\n  }\n\n  // Exclude Node.js internal modules (node:internal/...)\n  if (filename.startsWith(\"node:\")) {\n    return false;\n  }\n\n  // Exclude native code\n  if (filename === \"native\" || filename === \"<unknown>\") {\n    return false;\n  }\n\n  return true;\n}\n\n/**\n * Normalizes URL schemes to regular file paths.\n *\n * Handles file:// URLs commonly seen in ESM modules and local testing:\n * - \"file:///Users/john/project/src/index.ts\" → \"/Users/john/project/src/index.ts\"\n * - \"file:///C:/projects/app/src/index.ts\" → \"C:/projects/app/src/index.ts\"\n *\n * @param filename - File path that may be a file:// URL\n * @returns Clean file path without URL scheme\n */\nfunction normalizeUrl(filename: string): string {\n  // Handle file:// URLs (common in ESM modules and local testing)\n  if (filename.startsWith(\"file://\")) {\n    let result = filename.substring(7); // Remove \"file://\"\n\n    // Ensure Unix paths start with /\n    if (!result.startsWith(\"/\") && !result.match(/^[A-Za-z]:/)) {\n      result = \"/\" + result;\n    }\n\n    return result;\n  }\n\n  return filename;\n}\n\n/**\n * Normalizes Node.js internal module paths for consistent error grouping.\n *\n * Examples:\n * - \"node:internal/modules/cjs/loader\" → \"node:internal\"\n * - \"node:fs/promises\" → \"node:fs\"\n * - \"node:fs\" → \"node:fs\" (unchanged)\n *\n * @param filename - File path that may be a Node.js internal module\n * @returns Simplified module path or original filename\n */\nfunction normalizeNodeInternals(filename: string): string {\n  if (filename.startsWith(\"node:internal\")) {\n    return \"node:internal\";\n  }\n\n  if (filename.startsWith(\"node:\")) {\n    // Extract just the module name: node:fs/promises → node:fs\n    const parts = filename.split(\"/\");\n    return parts[0];\n  }\n\n  return filename;\n}\n\n/**\n * Strips user-specific and system path prefixes.\n *\n * Removes prefixes like:\n * - /Users/username/ → ~/\n * - /home/username/ → ~/\n * - C:\\Users\\username\\ → ~\\\n * - C:/Users/username/ → ~/ (mixed separators)\n *\n * @param path - File path to normalize\n * @returns Path with system prefixes removed\n */\nfunction stripSystemPrefixes(path: string): string {\n  // Unix/macOS: /Users/username/\n  path = path.replace(/^\\/Users\\/[^/]+\\//, \"~/\");\n\n  // Linux: /home/username/\n  path = path.replace(/^\\/home\\/[^/]+\\//, \"~/\");\n\n  // Windows: C:\\Users\\username\\ or C:/Users/username/ (with any separator)\n  path = path.replace(/^[A-Za-z]:[\\\\\\/]Users[\\\\\\/][^\\\\\\/]+[\\\\\\/]/, \"~/\");\n\n  return path;\n}\n\n/**\n * Normalizes node_modules paths to be consistent across deployments.\n *\n * Extracts only the package-relative portion of the path:\n * - /Users/john/project/node_modules/express/lib/router.js → node_modules/express/lib/router.js\n * - /app/node_modules/@scope/pkg/index.js → node_modules/@scope/pkg/index.js\n *\n * @param path - File path that may contain node_modules\n * @returns Normalized node_modules path or original path\n */\nfunction normalizeNodeModules(path: string): string {\n  // Find the last occurrence of /node_modules/ or \\node_modules\\\n  const unixIndex = path.lastIndexOf(\"/node_modules/\");\n  const winIndex = path.lastIndexOf(\"\\\\node_modules\\\\\");\n\n  if (unixIndex !== -1) {\n    return path.substring(unixIndex + 1); // +1 to exclude leading slash\n  }\n\n  if (winIndex !== -1) {\n    return path.substring(winIndex + 1).replace(/\\\\/g, \"/\");\n  }\n\n  return path;\n}\n\n/**\n * Strips common deployment-specific path prefixes.\n *\n * Removes prefixes like:\n * - /var/www/app/ → \"\"\n * - /app/ → \"\"\n * - /opt/project/ → \"\"\n * - /var/task/ → \"\" (AWS Lambda)\n * - /usr/src/app/ → \"\" (Docker)\n *\n * @param path - File path to normalize\n * @returns Path with deployment prefixes removed\n */\nfunction stripDeploymentPaths(path: string): string {\n  // Common deployment paths\n  const deploymentPrefixes = [\n    /^\\/var\\/www\\/[^/]+\\//, // Apache/nginx: /var/www/myapp/\n    /^\\/var\\/task\\//, // AWS Lambda: /var/task/\n    /^\\/usr\\/src\\/app\\//, // Docker: /usr/src/app/\n    /^\\/app\\//, // Heroku, Docker, generic: /app/\n    /^\\/opt\\/[^/]+\\//, // Optional software: /opt/myapp/\n    /^\\/srv\\/[^/]+\\//, // Service data: /srv/myapp/\n  ];\n\n  for (const prefix of deploymentPrefixes) {\n    path = path.replace(prefix, \"\");\n  }\n\n  return path;\n}\n\n/**\n * Finds project-relative path using common project boundary markers.\n *\n * Looks for markers like /src/, /lib/, /dist/, /build/ and extracts the path\n * from that marker onwards:\n * - /Users/john/project/src/components/Button.tsx → src/components/Button.tsx\n * - /app/dist/index.js → dist/index.js\n *\n * Priority order: looks for primary markers first (src, lib, dist, build),\n * then secondary markers. Uses the highest-priority marker found.\n *\n * @param path - File path to search for project boundaries\n * @returns Project-relative path or original path if no marker found\n */\nfunction findProjectPath(path: string): string {\n  // Project boundary markers in priority order\n  // Primary markers (most likely to be project root)\n  const primaryMarkers = [\"/src/\", \"/lib/\", \"/dist/\", \"/build/\"];\n\n  // Secondary markers (could be subdirectories)\n  const secondaryMarkers = [\n    \"/app/\",\n    \"/components/\",\n    \"/pages/\",\n    \"/api/\",\n    \"/utils/\",\n    \"/services/\",\n    \"/modules/\",\n  ];\n\n  // Check primary markers first\n  for (const marker of primaryMarkers) {\n    const index = path.lastIndexOf(marker);\n    if (index !== -1) {\n      return path.substring(index + 1); // +1 to remove leading slash\n    }\n  }\n\n  // If no primary marker, check secondary markers\n  for (const marker of secondaryMarkers) {\n    const index = path.lastIndexOf(marker);\n    if (index !== -1) {\n      return path.substring(index + 1);\n    }\n  }\n\n  return path;\n}\n\n/**\n * Converts absolute file paths to normalized relative paths for consistent error grouping.\n *\n * This function performs comprehensive path normalization to ensure errors from the same\n * code location group together regardless of deployment environment, user directories,\n * or system-specific paths. The original absolute path is always preserved in abs_path.\n *\n * Normalization steps:\n * 1. Normalize URL schemes (file://, etc.) - must be first to strip URL prefixes\n * 2. Preserve special paths (already relative, Node internals, etc.)\n * 3. Normalize path separators to forward slashes (for consistent processing)\n * 4. Normalize Node.js internal modules (node:internal/*, node:fs/*)\n * 5. Normalize node_modules paths to package-relative format\n * 6. Strip user home directories (/Users/*, /home/*, C:\\Users\\*)\n * 7. Strip deployment-specific paths (/var/www/*, /app/, AWS Lambda, Docker)\n * 8. Strip current working directory\n * 9. Find project boundaries (/src/, /lib/, /dist/, etc.)\n * 10. Remove leading slashes for clean relative paths\n *\n * @param filename - Absolute or relative file path from stack trace\n * @returns Normalized relative path for error grouping\n *\n * @example\n * makeRelativePath('/Users/john/project/src/index.ts')\n * // Returns: 'src/index.ts'\n *\n * @example\n * makeRelativePath('/home/ubuntu/app/node_modules/express/lib/router.js')\n * // Returns: 'node_modules/express/lib/router.js'\n *\n * @example\n * makeRelativePath('/var/www/myapp/dist/server.js')\n * // Returns: 'dist/server.js'\n *\n * @example\n * makeRelativePath('node:internal/modules/cjs/loader')\n * // Returns: 'node:internal'\n *\n * @example\n * makeRelativePath('C:\\\\Users\\\\John\\\\projects\\\\myapp\\\\src\\\\index.ts')\n * // Returns: 'src/index.ts'\n */\nfunction makeRelativePath(filename: string): string {\n  let result = filename;\n\n  // Step 1: Normalize URL schemes (file://, etc.)\n  result = normalizeUrl(result);\n\n  // Step 2: Handle already-relative paths and special cases\n  if (!result.startsWith(\"/\") && !result.match(/^[A-Za-z]:\\\\/)) {\n    // Already relative or special path (native, <unknown>, etc.)\n    // Still normalize Node internals\n    if (result.startsWith(\"node:\")) {\n      return normalizeNodeInternals(result);\n    }\n    return result;\n  }\n\n  // Step 3: Normalize path separators early for consistent processing\n  result = result.replace(/\\\\/g, \"/\");\n\n  // Step 4: Normalize Node.js internal modules (should be rare at this point)\n  if (result.startsWith(\"node:\")) {\n    return normalizeNodeInternals(result);\n  }\n\n  // Step 5: Handle node_modules specially - preserve package structure\n  if (result.includes(\"/node_modules/\")) {\n    return normalizeNodeModules(result);\n  }\n\n  // Step 6: Strip user home directories\n  result = stripSystemPrefixes(result);\n\n  // Step 7: Strip deployment-specific paths\n  result = stripDeploymentPaths(result);\n\n  // Step 8: Strip current working directory (if available)\n  // process.cwd() may not be available in edge environments\n  let cwd: string | null = null;\n  try {\n    if (typeof process !== \"undefined\" && typeof process.cwd === \"function\") {\n      cwd = process.cwd();\n    }\n  } catch {\n    // process.cwd() not available in this environment\n  }\n\n  if (cwd && result.startsWith(cwd)) {\n    result = result.substring(cwd.length + 1); // +1 to remove leading /\n  }\n\n  // Step 9: Find project boundaries if still absolute-looking\n  // Also apply to tilde paths that might have project markers after the tilde\n  if (result.startsWith(\"/\") || result.match(/^[A-Za-z]:[/]/)) {\n    result = findProjectPath(result);\n  } else if (result.startsWith(\"~\")) {\n    // For tilde paths, strip the tilde and find markers in the remaining path\n    const withoutTilde = result.substring(2); // Remove ~/\n    const projectPath = findProjectPath(\"/\" + withoutTilde);\n    // If a marker was found (path changed), use it; otherwise keep the tilde version\n    if (projectPath !== \"/\" + withoutTilde) {\n      result = projectPath;\n    }\n  }\n\n  // Step 10: Remove leading slash if present (prefer relative paths)\n  if (result.startsWith(\"/\")) {\n    result = result.substring(1);\n  }\n\n  return result;\n}\n\n/**\n * Recursively unwraps Error.cause chain and returns array of chained errors.\n *\n * Error.cause is a standard JavaScript feature that allows chaining errors:\n *   const cause = new Error(\"Root cause\");\n *   const error = new Error(\"Wrapper error\", { cause });\n *\n * This function extracts all errors in the cause chain up to MAX_EXCEPTION_CHAIN_DEPTH.\n *\n * @param error - Error object to unwrap\n * @returns Array of ChainedErrorData objects representing the error chain\n */\nfunction unwrapErrorCauses(error: Error): ChainedErrorData[] {\n  const chainedErrors: ChainedErrorData[] = [];\n  const seenErrors = new Set<Error>();\n  let currentError: unknown = (error as any).cause;\n  let depth = 0;\n\n  while (currentError && depth < MAX_EXCEPTION_CHAIN_DEPTH) {\n    // If cause is not an Error, stringify it and stop\n    if (!(currentError instanceof Error)) {\n      chainedErrors.push({\n        message: stringifyNonError(currentError),\n        type: undefined,\n      });\n      break;\n    }\n\n    // Check for circular reference\n    if (seenErrors.has(currentError)) {\n      break;\n    }\n    seenErrors.add(currentError);\n\n    const chainedErrorData: ChainedErrorData = {\n      message: currentError.message || \"\",\n      type: currentError.name || currentError.constructor?.name || \"Error\",\n    };\n\n    if (currentError.stack) {\n      chainedErrorData.stack = currentError.stack;\n      chainedErrorData.frames = parseV8StackTrace(currentError.stack);\n    }\n\n    chainedErrors.push(chainedErrorData);\n\n    // Move to next cause in chain\n    currentError = (currentError as any).cause;\n    depth++;\n  }\n\n  return chainedErrors;\n}\n\n/**\n * Detects if a value is a CallToolResult object (SDK 1.21.0+ error format).\n *\n * SDK 1.21.0+ converts errors to CallToolResult format:\n * { content: [{ type: \"text\", text: \"error message\" }], isError: true }\n *\n * @param value - Value to check\n * @returns True if value is a CallToolResult object\n */\nfunction isCallToolResult(value: unknown): boolean {\n  return (\n    value !== null &&\n    typeof value === \"object\" &&\n    \"isError\" in value &&\n    \"content\" in value &&\n    Array.isArray((value as any).content)\n  );\n}\n\n/**\n * Extracts error information from CallToolResult objects.\n *\n * SDK 1.21.0+ converts errors to CallToolResult, losing original stack traces.\n * This extracts the error message from the content array.\n *\n * @param result - CallToolResult object with error\n * @param _contextStack - Optional Error object for stack context (unused, kept for compatibility)\n * @returns ErrorData with extracted message (no stack trace)\n */\nfunction captureCallToolResultError(\n  result: any,\n  _contextStack?: Error,\n): ErrorData {\n  // Extract message from content array. Entries are untrusted handler output:\n  // a low-level server can return null/primitive holes, so shape-check first.\n  const message =\n    result.content\n      ?.filter((c: any) => c && typeof c === \"object\" && c.type === \"text\")\n      .map((c: any) => c.text)\n      .join(\" \")\n      .trim() || \"Unknown error\";\n\n  const errorData: ErrorData = {\n    message,\n    type: undefined, // Can't determine actual type from CallToolResult\n    platform: \"javascript\",\n    // No stack or frames - SDK stripped the original error information\n  };\n\n  return errorData;\n}\n\n/**\n * Converts non-Error objects to string representation for error messages.\n *\n * In JavaScript, anything can be thrown (not just Error objects):\n *   throw \"string error\";\n *   throw { code: 404 };\n *   throw null;\n *\n * This function handles these cases by converting them to meaningful strings.\n *\n * @param value - Non-Error value that was thrown\n * @returns String representation of the value\n */\nfunction stringifyNonError(value: unknown): string {\n  if (value === null) {\n    return \"null\";\n  }\n\n  if (value === undefined) {\n    return \"undefined\";\n  }\n\n  if (typeof value === \"string\") {\n    return value;\n  }\n\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return String(value);\n  }\n\n  // Try to stringify objects with fallback\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n","import { writeToLog } from \"./logging.js\";\n\n/**\n * Projects the request-handler `extra` into a JSON-publishable value for the\n * event's `parameters.extra`. The pipeline's walkers (redaction,\n * sanitization, truncation) traverse own enumerable keys only, so host\n * objects whose data lives behind prototype getters flatten to `{}`:\n *\n * - v2 (`@modelcontextprotocol/server`): `http.req` is a WHATWG Request —\n *   replaced with a plain `{ method, url, headers }` (headers verbatim).\n * - v1 (`@modelcontextprotocol/sdk`): `requestInfo.url` is a URL instance —\n *   replaced with its `.href` string. `requestInfo.headers` is already a\n *   plain object and passes through untouched.\n *\n * Duck-typed, never instanceof: workerd's Request is a different realm than\n * undici's. Shallow-copies only the levels it rewrites (extra, http,\n * requestInfo); everything else passes by reference, and when nothing needs\n * rewriting the original `extra` is returned unchanged. Never throws — a\n * projection failure must not cost the event.\n */\nexport function projectExtraForEvent(extra: unknown): unknown {\n  if (extra === null || typeof extra !== \"object\") return extra;\n\n  try {\n    let out: Record<string, any> | null = null;\n\n    // v2: http.req is a web Request. `headers.entries` doubles as the\n    // duck-type probe and the iteration source; an already-projected plain\n    // req has no such function, so re-projection is a no-op.\n    const req = (extra as any).http?.req;\n    if (\n      req !== null &&\n      typeof req === \"object\" &&\n      req.headers !== null &&\n      typeof req.headers === \"object\" &&\n      typeof req.headers.entries === \"function\"\n    ) {\n      out = {\n        ...(extra as any),\n        http: {\n          ...(extra as any).http,\n          req: {\n            ...(typeof req.method === \"string\" ? { method: req.method } : {}),\n            ...(typeof req.url === \"string\" ? { url: req.url } : {}),\n            headers: Object.fromEntries(req.headers.entries()),\n          },\n        },\n      };\n    }\n\n    // v1: requestInfo.url is a URL instance (an already-string url passes\n    // through untouched).\n    const url = (extra as any).requestInfo?.url;\n    if (\n      url !== null &&\n      typeof url === \"object\" &&\n      typeof url.href === \"string\"\n    ) {\n      if (out === null) out = { ...(extra as Record<string, any>) };\n      out.requestInfo = { ...(extra as any).requestInfo, url: url.href };\n    }\n\n    return out ?? extra;\n  } catch (error) {\n    writeToLog(\n      `Warning: Failed to project request context into event parameters, publishing extra as-is - ${error}`,\n    );\n    return extra;\n  }\n}\n","/**\n * MCP SDK Compatibility Helpers\n *\n * Internal utilities for handling differences between MCP SDK versions.\n * These helpers abstract away SDK-internal details like:\n * - Tool callback/handler property names (changed in SDK 1.24)\n * - Zod schema internal structures (v3 vs v4)\n */\n\nimport { RegisteredTool, ToolCallback } from \"../types.js\";\n\n// --- Tool function property utilities for MCP SDK version compatibility ---\n// MCP SDK 1.23 and earlier use \"callback\", 1.24+ uses \"handler\"\n\nexport type ToolFunctionKey = \"callback\" | \"handler\";\n\n/**\n * Returns the tool function (callback/handler) from a RegisteredTool.\n * Supports both MCP SDK 1.23- (callback) and 1.24+ (handler).\n */\nexport function getToolFunction(tool: RegisteredTool): ToolCallback {\n  if (\"handler\" in tool && typeof tool.handler === \"function\") {\n    return tool.handler;\n  }\n  if (\"callback\" in tool && typeof tool.callback === \"function\") {\n    return tool.callback;\n  }\n  throw new Error(\"Tool has neither callback nor handler property\");\n}\n\n/**\n * Returns the property key name used for the tool function (\"callback\" or \"handler\").\n * This preserves the original property name when wrapping tools.\n */\nexport function getToolFunctionKey(tool: RegisteredTool): ToolFunctionKey {\n  if (\"handler\" in tool && typeof tool.handler === \"function\") {\n    return \"handler\";\n  }\n  return \"callback\";\n}\n\n/**\n * Returns true if the tool has a callback or handler property.\n */\nexport function hasToolFunction(tool: unknown): tool is RegisteredTool {\n  if (!tool || typeof tool !== \"object\") return false;\n  const t = tool as Record<string, unknown>;\n  return (\n    (\"handler\" in t && typeof t.handler === \"function\") ||\n    (\"callback\" in t && typeof t.callback === \"function\")\n  );\n}\n\n/**\n * Creates a new tool object with the wrapped function, preserving the original property name.\n * This ensures MCP SDK 1.24+ gets back a tool with \"handler\" and 1.23- gets \"callback\".\n */\nexport function createWrappedTool(\n  originalTool: RegisteredTool,\n  wrappedFunction: ToolCallback,\n): RegisteredTool {\n  const key = getToolFunctionKey(originalTool);\n  return {\n    ...originalTool,\n    [key]: wrappedFunction,\n  } as RegisteredTool;\n}\n\n// --- Zod schema internal property helpers ---\n// These access internal properties to extract method names from MCP SDK schemas\n// No Zod import needed - we introspect the internal structure directly\n\ninterface ZodV3Internal {\n  _def?: {\n    value?: unknown;\n    values?: unknown[]; // For enums - some Zod versions store literal values here\n    shape?: Record<string, unknown> | (() => Record<string, unknown>);\n  };\n  shape?: Record<string, unknown> | (() => Record<string, unknown>);\n}\n\ninterface ZodV4Internal {\n  _zod?: {\n    def?: {\n      value?: unknown;\n      values?: unknown[]; // For enums - some Zod versions store literal values here\n      shape?: Record<string, unknown> | (() => Record<string, unknown>);\n    };\n  };\n}\n\nexport function isZ4Schema(schema: unknown): boolean {\n  if (!schema || typeof schema !== \"object\") return false;\n  return !!(schema as ZodV4Internal)._zod;\n}\n\nexport function getObjectShape(\n  schema: unknown,\n): Record<string, unknown> | undefined {\n  if (!schema || typeof schema !== \"object\") return undefined;\n\n  let rawShape:\n    | Record<string, unknown>\n    | (() => Record<string, unknown>)\n    | undefined;\n\n  if (isZ4Schema(schema)) {\n    const v4Schema = schema as ZodV4Internal;\n    rawShape = v4Schema._zod?.def?.shape;\n  } else {\n    const v3Schema = schema as ZodV3Internal;\n    // Try .shape first, then fall back to _def.shape (some v3 schema types store it there)\n    rawShape = v3Schema.shape ?? v3Schema._def?.shape;\n  }\n\n  if (!rawShape) return undefined;\n\n  if (typeof rawShape === \"function\") {\n    try {\n      return rawShape();\n    } catch {\n      return undefined;\n    }\n  }\n\n  return rawShape;\n}\n\nexport function getLiteralValue(schema: unknown): unknown {\n  if (!schema || typeof schema !== \"object\") return undefined;\n\n  if (isZ4Schema(schema)) {\n    const v4Schema = schema as ZodV4Internal;\n    const def = v4Schema._zod?.def;\n    if (def?.value !== undefined) return def.value;\n    // Fallback: values array (for enums)\n    if (Array.isArray(def?.values) && def.values.length > 0) {\n      return def.values[0];\n    }\n  } else {\n    const v3Schema = schema as ZodV3Internal;\n    const def = v3Schema._def;\n    if (def?.value !== undefined) return def.value;\n    // Fallback: values array (for enums)\n    if (Array.isArray(def?.values) && def.values.length > 0) {\n      return def.values[0];\n    }\n  }\n\n  // Final fallback: direct .value property (some Zod versions)\n  const directValue = (schema as { value?: unknown }).value;\n  if (directValue !== undefined) return directValue;\n\n  return undefined;\n}\n","import { MCPServerLike } from \"../types.js\";\nimport { writeToLog } from \"../modules/logging.js\";\nimport { getLiteralValue, getObjectShape } from \"../modules/mcp-sdk-compat.js\";\n\n/**\n * Patches setRequestHandler to re-arm the engine when tools/list or\n * tools/call get (re)registered after track().\n *\n * Arity- and type-safe by construction:\n * - v2 passes a method STRING first (2-arg spec form or 3-arg custom form);\n * - v1 passes a Zod request schema first (introspected for its method literal);\n * - ALL arguments are forwarded verbatim — a v2 3-arg custom registration\n *   must reach the SDK intact (dropping the third argument breaks the\n *   customer's server with \"handler is required\").\n */\nexport function patchSetRequestHandler(\n  server: MCPServerLike,\n  onToolHandlerRegistered: () => void,\n): void {\n  const original = server.setRequestHandler.bind(server);\n  server.setRequestHandler = function (...args: any[]) {\n    const first = args[0];\n    let method: unknown;\n    if (typeof first === \"string\") {\n      method = first;\n    } else {\n      const shape = getObjectShape(first);\n      method = shape?.method ? getLiteralValue(shape.method) : undefined;\n    }\n    const result = (original as any)(...args);\n    if (method === \"tools/call\" || method === \"tools/list\") {\n      try {\n        onToolHandlerRegistered();\n      } catch (error) {\n        writeToLog(`Warning: engine re-arm failed - ${error}`);\n      }\n    }\n    return result;\n  } as any;\n}\n","import { Detection } from \"../detect.js\";\nimport { v1Adapter } from \"../adapters/v1.js\";\nimport { v2Adapter } from \"../adapters/v2.js\";\nimport { initEngineState } from \"./registry.js\";\nimport { installListWrap } from \"./listWrap.js\";\nimport { installCallWrap } from \"./callWrap.js\";\nimport { patchSetRequestHandler } from \"./registrationPatch.js\";\nimport { installRegistryProxy, rewrapAllTools } from \"./innerTap.js\";\n\n/**\n * Installs the full interception engine on a detected server:\n * map-seam wraps for tools/list + tools/call, the registration re-arm\n * patch, and (high-level flavor) the registry proxy + initial inner-tap\n * sweep.\n */\nexport function installEngine(detection: Detection): void {\n  const server = detection.lowLevel;\n  const adapter = detection.major === 2 ? v2Adapter : v1Adapter;\n  initEngineState(server, { adapter, highLevel: detection.highLevel });\n\n  const rearm = () => {\n    installListWrap(server);\n    installCallWrap(server);\n  };\n\n  patchSetRequestHandler(server, rearm);\n  if (detection.highLevel) {\n    installRegistryProxy(server, detection.highLevel, adapter, rearm);\n  }\n  rearm();\n  if (detection.highLevel) {\n    rewrapAllTools(server, detection.highLevel, adapter);\n  }\n}\n","import { createHash, randomBytes } from \"crypto\";\n\nclass TraceContext {\n  getTraceId(sessionId?: string): string {\n    if (!sessionId) {\n      return randomBytes(16).toString(\"hex\");\n    }\n\n    return createHash(\"sha256\")\n      .update(sessionId)\n      .digest(\"hex\")\n      .substring(0, 32);\n  }\n\n  getSpanId(eventId?: string): string {\n    if (!eventId) {\n      return randomBytes(8).toString(\"hex\");\n    }\n\n    return createHash(\"sha256\").update(eventId).digest(\"hex\").substring(0, 16);\n  }\n\n  getDatadogTraceId(sessionId?: string): string {\n    const hex = this.getTraceId(sessionId);\n    return BigInt(\"0x\" + hex.substring(16, 32)).toString();\n  }\n\n  getDatadogSpanId(eventId?: string): string {\n    const hex = this.getSpanId(eventId);\n    return BigInt(\"0x\" + hex).toString();\n  }\n}\n\nexport const traceContext = new TraceContext();\n","import { Event, Exporter } from \"../../types.js\";\nimport { writeToLog } from \"../logging.js\";\nimport { traceContext } from \"./trace-context.js\";\nimport { AGENTCAT_SOURCE } from \"../constants.js\";\n\nexport interface OTLPExporterConfig {\n  type: \"otlp\";\n  endpoint: string;\n  headers?: Record<string, string>;\n}\n\nexport class OTLPExporter implements Exporter {\n  private endpoint: string;\n  private headers: Record<string, string>;\n\n  constructor(config: OTLPExporterConfig) {\n    // Auto-append /v1/traces per OTLP spec if not already present\n    const url = config.endpoint.replace(/\\/+$/, \"\");\n    this.endpoint = url.endsWith(\"/v1/traces\") ? url : `${url}/v1/traces`;\n\n    this.headers = {\n      \"Content-Type\": \"application/json\", // Using JSON for now for easier debugging\n      ...config.headers,\n    };\n  }\n\n  async export(event: Event): Promise<void> {\n    try {\n      // Convert AgentCat event to OTLP trace format\n      const span = this.convertToOTLPSpan(event);\n\n      // Create OTLP JSON format\n      const otlpRequest = {\n        resourceSpans: [\n          {\n            resource: {\n              attributes: [\n                {\n                  key: \"service.name\",\n                  value: { stringValue: event.serverName || \"mcp-server\" },\n                },\n                {\n                  key: \"service.version\",\n                  value: { stringValue: event.serverVersion || \"unknown\" },\n                },\n              ],\n            },\n            scopeSpans: [\n              {\n                scope: {\n                  name: \"agentcat\",\n                  version: event.agentcatVersion || \"unknown\",\n                },\n                spans: [span],\n              },\n            ],\n          },\n        ],\n      };\n\n      // Use JSON format for now\n      const body = JSON.stringify(otlpRequest);\n\n      // Use fetch to send the data\n      const response = await fetch(this.endpoint, {\n        method: \"POST\",\n        headers: this.headers,\n        body,\n      });\n\n      if (!response.ok) {\n        throw new Error(\n          `OTLP export failed: ${response.status} ${response.statusText}`,\n        );\n      }\n\n      writeToLog(`Successfully exported event to OTLP: ${event.id}`);\n    } catch (error) {\n      throw new Error(`OTLP export error: ${error}`);\n    }\n  }\n\n  private convertToOTLPSpan(event: Event): any {\n    const startTimeNanos = event.timestamp\n      ? BigInt(event.timestamp.getTime()) * BigInt(1_000_000)\n      : BigInt(Date.now()) * BigInt(1_000_000);\n\n    const endTimeNanos = event.duration\n      ? startTimeNanos + BigInt(event.duration) * BigInt(1_000_000)\n      : startTimeNanos;\n\n    return {\n      traceId: traceContext.getTraceId(event.sessionId),\n      spanId: traceContext.getSpanId(event.id),\n      name: event.eventType || \"mcp.event\",\n      kind: 2, // SPAN_KIND_SERVER\n      startTimeUnixNano: startTimeNanos.toString(),\n      endTimeUnixNano: endTimeNanos.toString(),\n      attributes: [\n        {\n          key: \"source\",\n          value: { stringValue: AGENTCAT_SOURCE },\n        },\n        {\n          key: \"mcp.event_type\",\n          value: { stringValue: event.eventType || \"\" },\n        },\n        {\n          key: \"mcp.session_id\",\n          value: { stringValue: event.sessionId || \"\" },\n        },\n        {\n          key: \"mcp.project_id\",\n          value: { stringValue: event.projectId || \"\" },\n        },\n        {\n          key: \"mcp.resource_name\",\n          value: { stringValue: event.resourceName || \"\" },\n        },\n        {\n          key: \"mcp.user_intent\",\n          value: { stringValue: event.userIntent || \"\" },\n        },\n        {\n          key: \"mcp.actor_id\",\n          value: { stringValue: event.identifyActorGivenId || \"\" },\n        },\n        {\n          key: \"mcp.actor_name\",\n          value: { stringValue: event.identifyActorName || \"\" },\n        },\n        {\n          key: \"mcp.client_name\",\n          value: { stringValue: event.clientName || \"\" },\n        },\n        {\n          key: \"mcp.client_version\",\n          value: { stringValue: event.clientVersion || \"\" },\n        },\n        // Add customer-defined tags as individual attributes\n        ...Object.entries(event.tags || {}).map(([key, value]) => ({\n          key: `agentcat.tag.${key}`,\n          value: { stringValue: value },\n        })),\n        // Add customer-defined properties as JSON\n        ...(event.properties\n          ? [\n              {\n                key: \"agentcat.properties\",\n                value: { stringValue: JSON.stringify(event.properties) },\n              },\n            ]\n          : []),\n      ].filter((attr) => attr.value.stringValue), // Remove empty attributes\n      status: {\n        code: event.isError ? 2 : 1, // ERROR : OK\n      },\n    };\n  }\n}\n","import { Event, Exporter } from \"../../types.js\";\nimport { writeToLog } from \"../logging.js\";\nimport { traceContext } from \"./trace-context.js\";\nimport { AGENTCAT_SOURCE } from \"../constants.js\";\n\nexport interface DatadogExporterConfig {\n  type: \"datadog\";\n  apiKey: string; // Required - Datadog API key\n  site: string; // Required - 'datadoghq.com', 'datadoghq.eu', etc.\n  service: string; // Required - MCP server name\n  env?: string; // Optional - environment\n}\n\ninterface DatadogLog {\n  message: string;\n  service: string;\n  ddsource: string;\n  ddtags: string;\n  timestamp: number;\n  status?: string;\n  dd?: {\n    trace_id: string;\n    span_id: string;\n  };\n  error?: {\n    message: string;\n  };\n  mcp: {\n    session_id?: string;\n    event_id?: string;\n    event_type?: string;\n    resource?: string;\n    duration_ms?: number;\n    user_intent?: string;\n    actor_id?: string;\n    actor_name?: string;\n    client_name?: string;\n    client_version?: string;\n    server_name?: string;\n    server_version?: string;\n    is_error?: boolean;\n    error?: any;\n    tags?: Record<string, string> | null;\n    properties?: Record<string, any> | null;\n  };\n}\n\ninterface DatadogMetric {\n  metric: string;\n  type: \"count\" | \"gauge\" | \"rate\";\n  points: Array<[number, number]>;\n  tags?: string[];\n}\n\nexport class DatadogExporter implements Exporter {\n  private logsUrl: string;\n  private metricsUrl: string;\n  private config: DatadogExporterConfig;\n\n  constructor(config: DatadogExporterConfig) {\n    this.config = config;\n\n    // Build API endpoints based on site\n    const site = config.site.replace(/^https?:\\/\\//, \"\").replace(/\\/$/, \"\");\n    this.logsUrl = `https://http-intake.logs.${site}/api/v2/logs`;\n    this.metricsUrl = `https://api.${site}/api/v1/series`;\n  }\n\n  async export(event: Event): Promise<void> {\n    writeToLog(\"DatadogExporter: Sending event immediately to Datadog\");\n\n    // Convert event to log and metrics\n    const log = this.eventToLog(event);\n    const metrics = this.eventToMetrics(event);\n\n    // Debug: Log the metrics URL and count (never the serialized payload)\n    writeToLog(`DatadogExporter: Metrics URL: ${this.metricsUrl}`);\n    writeToLog(`DatadogExporter: Sending ${metrics.length} metric series`);\n\n    // Send logs with response checking\n    const logsPromise = fetch(this.logsUrl, {\n      method: \"POST\",\n      headers: {\n        \"DD-API-KEY\": this.config.apiKey,\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify([log]),\n    })\n      .then(async (response) => {\n        if (!response.ok) {\n          writeToLog(`Datadog logs failed - Status: ${response.status}`);\n        } else {\n          writeToLog(`Datadog logs success - Status: ${response.status}`);\n        }\n        return response;\n      })\n      .catch((err) => {\n        writeToLog(`Datadog logs network error: ${err}`);\n      });\n\n    // Send metrics with response checking\n    const metricsPromise = fetch(this.metricsUrl, {\n      method: \"POST\",\n      headers: {\n        \"DD-API-KEY\": this.config.apiKey,\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify({ series: metrics }),\n    })\n      .then(async (response) => {\n        if (!response.ok) {\n          writeToLog(`Datadog metrics failed - Status: ${response.status}`);\n        } else {\n          writeToLog(`Datadog metrics success - Status: ${response.status}`);\n        }\n        return response;\n      })\n      .catch((err) => {\n        writeToLog(`Datadog metrics network error: ${err}`);\n      });\n\n    // Wait for both to complete\n    await Promise.all([logsPromise, metricsPromise]);\n  }\n\n  private eventToLog(event: Event): DatadogLog {\n    const tags: string[] = [];\n\n    // Add basic tags\n    if (this.config.env) tags.push(`env:${this.config.env}`);\n    if (event.eventType)\n      tags.push(`event_type:${event.eventType.replace(/\\//g, \".\")}`);\n    if (event.resourceName) tags.push(`resource:${event.resourceName}`);\n    if (event.isError) tags.push(\"error:true\");\n\n    tags.push(`source:${AGENTCAT_SOURCE}`);\n\n    // Add customer-defined tags to ddtags (namespaced to avoid collisions with reserved Datadog tags)\n    if (event.tags) {\n      for (const [key, value] of Object.entries(event.tags)) {\n        const sanitizedKey = key.toLowerCase().replace(/[\\s:,]+/g, \"_\");\n        const sanitizedValue = value.replace(/,/g, \"_\");\n        tags.push(`agentcat.${sanitizedKey}:${sanitizedValue}`);\n      }\n    }\n\n    const log: DatadogLog = {\n      message: `${event.eventType || \"unknown\"} - ${event.resourceName || \"unknown\"}`,\n      service: this.config.service,\n      ddsource: AGENTCAT_SOURCE,\n      ddtags: tags.join(\",\"),\n      timestamp: event.timestamp ? event.timestamp.getTime() : Date.now(),\n      status: event.isError ? \"error\" : \"info\",\n      dd: {\n        trace_id: traceContext.getDatadogTraceId(event.sessionId),\n        span_id: traceContext.getDatadogSpanId(event.id),\n      },\n      mcp: {\n        session_id: event.sessionId,\n        event_id: event.id,\n        event_type: event.eventType,\n        resource: event.resourceName,\n        duration_ms: event.duration,\n        user_intent: event.userIntent,\n        actor_id: event.identifyActorGivenId,\n        actor_name: event.identifyActorName,\n        client_name: event.clientName,\n        client_version: event.clientVersion,\n        server_name: event.serverName,\n        server_version: event.serverVersion,\n        is_error: event.isError,\n        error: event.error,\n        tags: event.tags,\n        properties: event.properties,\n      },\n    };\n\n    // Add error at root level if it exists\n    if (event.isError && event.error) {\n      log.error = {\n        message:\n          typeof event.error === \"string\"\n            ? event.error\n            : JSON.stringify(event.error),\n      };\n    }\n\n    return log;\n  }\n\n  private eventToMetrics(event: Event): DatadogMetric[] {\n    const metrics: DatadogMetric[] = [];\n    const timestamp = Math.floor(\n      (event.timestamp?.getTime() || Date.now()) / 1000,\n    );\n    const tags: string[] = [`service:${this.config.service}`];\n\n    // Add optional tags\n    if (this.config.env) tags.push(`env:${this.config.env}`);\n    if (event.eventType)\n      tags.push(`event_type:${event.eventType.replace(/\\//g, \".\")}`);\n    if (event.resourceName) tags.push(`resource:${event.resourceName}`);\n\n    // Event count metric\n    metrics.push({\n      metric: \"mcp.events.count\",\n      type: \"count\",\n      points: [[timestamp, 1]],\n      tags,\n    });\n\n    // Duration metric (only if duration exists)\n    if (event.duration) {\n      metrics.push({\n        metric: \"mcp.event.duration\",\n        type: \"gauge\",\n        points: [[timestamp, event.duration]],\n        tags,\n      });\n    }\n\n    // Error count metric\n    if (event.isError) {\n      metrics.push({\n        metric: \"mcp.errors.count\",\n        type: \"count\",\n        points: [[timestamp, 1]],\n        tags,\n      });\n    }\n\n    return metrics;\n  }\n}\n","import { Event, Exporter } from \"../../types.js\";\nimport { writeToLog } from \"../logging.js\";\nimport { traceContext } from \"./trace-context.js\";\nimport { AGENTCAT_SOURCE } from \"../constants.js\";\n\nexport interface SentryExporterConfig {\n  type: \"sentry\";\n  dsn: string;\n  environment?: string;\n  release?: string;\n  enableTracing?: boolean; // Default: false (logs/errors only)\n}\n\ninterface ParsedDSN {\n  protocol: string;\n  publicKey: string;\n  host: string;\n  port?: string;\n  path: string;\n  projectId: string;\n}\n\ninterface SentryTransaction {\n  type: \"transaction\";\n  event_id: string;\n  timestamp: number;\n  start_timestamp: number;\n  transaction: string;\n  contexts: {\n    trace: {\n      trace_id: string;\n      span_id: string;\n      op: string;\n      status?: \"ok\" | \"internal_error\";\n    };\n    [key: string]: any;\n  };\n  spans?: Array<{\n    span_id: string;\n    trace_id: string;\n    parent_span_id?: string;\n    op: string;\n    description?: string;\n    start_timestamp: number;\n    timestamp: number;\n    status?: \"ok\" | \"internal_error\";\n  }>;\n  tags?: Record<string, string>;\n  extra?: Record<string, any>;\n}\n\ninterface SentryErrorEvent {\n  type: \"event\";\n  event_id: string;\n  timestamp: number;\n  level: \"error\" | \"fatal\" | \"warning\";\n  exception: {\n    values: Array<{\n      type: string;\n      value: string;\n      mechanism?: {\n        type: string;\n        handled: boolean;\n      };\n    }>;\n  };\n  contexts?: {\n    trace?: {\n      trace_id: string;\n      span_id: string;\n      parent_span_id?: string;\n      op?: string;\n    };\n    [key: string]: any;\n  };\n  tags?: Record<string, string>;\n  extra?: Record<string, any>;\n  transaction?: string;\n}\n\ninterface SentryLog {\n  timestamp: number;\n  trace_id: string;\n  event_id: string;\n  level: \"info\" | \"error\";\n  body: string;\n  attributes?: Record<\n    string,\n    { value: any; type: \"string\" | \"boolean\" | \"integer\" | \"double\" }\n  >;\n}\n\nexport class SentryExporter implements Exporter {\n  private endpoint: string;\n  private authHeader: string;\n  private config: SentryExporterConfig;\n  private parsedDSN: ParsedDSN;\n\n  constructor(config: SentryExporterConfig) {\n    this.config = config;\n    this.parsedDSN = this.parseDSN(config.dsn);\n\n    // Build envelope endpoint\n    this.endpoint = `${this.parsedDSN.protocol}://${this.parsedDSN.host}${\n      this.parsedDSN.port ? `:${this.parsedDSN.port}` : \"\"\n    }${this.parsedDSN.path}/api/${this.parsedDSN.projectId}/envelope/`;\n\n    // Build auth header\n    this.authHeader = `Sentry sentry_version=7, sentry_client=agentcat/1.0.0, sentry_key=${this.parsedDSN.publicKey}`;\n\n    writeToLog(`SentryExporter: Initialized with endpoint ${this.endpoint}`);\n  }\n\n  private parseDSN(dsn: string): ParsedDSN {\n    // DSN format: protocol://publicKey@host[:port]/path/projectId\n    const regex = /^(https?):\\/\\/([a-f0-9]+)@([\\w.-]+)(:\\d+)?(\\/.*)?\\/(\\d+)$/;\n    const match = dsn.match(regex);\n\n    if (!match) {\n      throw new Error(`Invalid Sentry DSN: ${dsn}`);\n    }\n\n    return {\n      protocol: match[1],\n      publicKey: match[2],\n      host: match[3],\n      port: match[4]?.substring(1), // Remove leading ':'\n      path: match[5] || \"\",\n      projectId: match[6],\n    };\n  }\n\n  async export(event: Event): Promise<void> {\n    try {\n      // ALWAYS send log\n      const log = this.eventToLog(event);\n      const logEnvelope = this.createLogEnvelope(log);\n\n      writeToLog(`SentryExporter: Sending log for event ${event.id} to Sentry`);\n\n      const logResponse = await fetch(this.endpoint, {\n        method: \"POST\",\n        headers: {\n          \"X-Sentry-Auth\": this.authHeader,\n          \"Content-Type\": \"application/x-sentry-envelope\",\n        },\n        body: logEnvelope,\n      });\n\n      if (!logResponse.ok) {\n        const errorBody = await logResponse.text();\n        writeToLog(\n          `Sentry log export failed - Status: ${logResponse.status}, Body: ${errorBody}`,\n        );\n      } else {\n        writeToLog(`Sentry log export success - Event: ${event.id}`);\n      }\n\n      // OPTIONALLY send transaction for performance monitoring\n      if (this.config.enableTracing) {\n        const transaction = this.eventToTransaction(event);\n        const transactionEnvelope = this.createTransactionEnvelope(transaction);\n\n        writeToLog(\n          `SentryExporter: Sending transaction ${transaction.event_id} to Sentry`,\n        );\n\n        const transactionResponse = await fetch(this.endpoint, {\n          method: \"POST\",\n          headers: {\n            \"X-Sentry-Auth\": this.authHeader,\n            \"Content-Type\": \"application/x-sentry-envelope\",\n          },\n          body: transactionEnvelope,\n        });\n\n        if (!transactionResponse.ok) {\n          const errorBody = await transactionResponse.text();\n          writeToLog(\n            `Sentry transaction export failed - Status: ${transactionResponse.status}, Body: ${errorBody}`,\n          );\n        } else {\n          writeToLog(`Sentry transaction export success - Event: ${event.id}`);\n        }\n      }\n\n      // ALWAYS send error event for Issue creation if this is an error\n      if (event.isError) {\n        // Use transaction if available for better context, otherwise create minimal error event\n        const errorEvent = this.config.enableTracing\n          ? this.eventToErrorEvent(event, this.eventToTransaction(event))\n          : this.eventToErrorEvent(event);\n        const errorEnvelope = this.createErrorEnvelope(errorEvent);\n\n        writeToLog(\n          `SentryExporter: Sending error event ${errorEvent.event_id} to Sentry for Issue creation`,\n        );\n\n        const errorResponse = await fetch(this.endpoint, {\n          method: \"POST\",\n          headers: {\n            \"X-Sentry-Auth\": this.authHeader,\n            \"Content-Type\": \"application/x-sentry-envelope\",\n          },\n          body: errorEnvelope,\n        });\n\n        if (!errorResponse.ok) {\n          const errorBody = await errorResponse.text();\n          writeToLog(\n            `Sentry error export failed - Status: ${errorResponse.status}, Body: ${errorBody}`,\n          );\n        } else {\n          writeToLog(`Sentry error export success - Event: ${event.id}`);\n        }\n      }\n    } catch (error) {\n      writeToLog(`Sentry export error: ${error}`);\n    }\n  }\n\n  private eventToLog(event: Event): SentryLog {\n    const timestamp = event.timestamp\n      ? new Date(event.timestamp).getTime() / 1000\n      : Date.now() / 1000;\n\n    const traceId = traceContext.getTraceId(event.sessionId);\n\n    // Generate deterministic event_id for Sentry\n    const eventId =\n      traceContext.getSpanId(event.id) + traceContext.getSpanId(event.id);\n\n    // Build message\n    const message = event.resourceName\n      ? `MCP ${event.eventType || \"event\"}: ${event.resourceName}`\n      : `MCP ${event.eventType || \"event\"}`;\n\n    return {\n      timestamp,\n      trace_id: traceId,\n      event_id: eventId,\n      level: event.isError ? \"error\" : \"info\",\n      body: message,\n      attributes: this.buildLogAttributes(event),\n    };\n  }\n\n  private buildLogAttributes(\n    event: Event,\n  ): Record<\n    string,\n    { value: any; type: \"string\" | \"boolean\" | \"integer\" | \"double\" }\n  > {\n    const attributes: Record<\n      string,\n      { value: any; type: \"string\" | \"boolean\" | \"integer\" | \"double\" }\n    > = {};\n\n    if (event.eventType) {\n      attributes.eventType = { value: event.eventType, type: \"string\" };\n    }\n    if (event.resourceName) {\n      attributes.resourceName = { value: event.resourceName, type: \"string\" };\n    }\n    if (event.serverName) {\n      attributes.serverName = { value: event.serverName, type: \"string\" };\n    }\n    if (event.clientName) {\n      attributes.clientName = { value: event.clientName, type: \"string\" };\n    }\n    if (event.sessionId) {\n      attributes.sessionId = { value: event.sessionId, type: \"string\" };\n    }\n    if (event.projectId) {\n      attributes.projectId = { value: event.projectId, type: \"string\" };\n    }\n    if (event.duration !== undefined) {\n      attributes.duration_ms = { value: event.duration, type: \"double\" };\n    }\n    if (event.identifyActorGivenId) {\n      attributes.actorId = {\n        value: event.identifyActorGivenId,\n        type: \"string\",\n      };\n    }\n    if (event.identifyActorName) {\n      attributes.actorName = { value: event.identifyActorName, type: \"string\" };\n    }\n    if (event.userIntent) {\n      attributes.userIntent = { value: event.userIntent, type: \"string\" };\n    }\n    if (event.serverVersion) {\n      attributes.serverVersion = { value: event.serverVersion, type: \"string\" };\n    }\n    if (event.clientVersion) {\n      attributes.clientVersion = { value: event.clientVersion, type: \"string\" };\n    }\n    if (event.isError !== undefined) {\n      attributes.isError = { value: event.isError, type: \"boolean\" };\n    }\n\n    return attributes;\n  }\n\n  private createLogEnvelope(log: SentryLog): string {\n    // Envelope header\n    const envelopeHeader = {\n      event_id: log.event_id,\n      sent_at: new Date().toISOString(),\n    };\n\n    // Item header with ALL MANDATORY fields\n    const itemHeader = {\n      type: \"log\",\n      item_count: 1, // MANDATORY - must match number of logs\n      content_type: \"application/vnd.sentry.items.log+json\", // MANDATORY - exact string\n    };\n\n    // Payload with CORRECT key\n    const payload = {\n      items: [log], // Changed from 'logs' to 'items'\n    };\n\n    // Build envelope with TRAILING NEWLINE\n    return (\n      [\n        JSON.stringify(envelopeHeader),\n        JSON.stringify(itemHeader),\n        JSON.stringify(payload),\n      ].join(\"\\n\") + \"\\n\"\n    ); // Added required trailing newline\n  }\n\n  private eventToTransaction(event: Event): SentryTransaction {\n    // Calculate timestamps\n    const endTimestamp = event.timestamp\n      ? new Date(event.timestamp).getTime() / 1000\n      : Date.now() / 1000;\n\n    const startTimestamp = event.duration\n      ? endTimestamp - event.duration / 1000\n      : endTimestamp;\n\n    const traceId = traceContext.getTraceId(event.sessionId);\n    const spanId = traceContext.getSpanId(event.id);\n\n    // Build transaction name\n    const transactionName = event.resourceName\n      ? `${event.eventType || \"mcp\"} - ${event.resourceName}`\n      : event.eventType || \"mcp.event\";\n\n    const transaction: SentryTransaction = {\n      type: \"transaction\",\n      event_id: traceContext.getSpanId(event.id) + traceContext.getSpanId(),\n      timestamp: endTimestamp,\n      start_timestamp: startTimestamp,\n      transaction: transactionName,\n      contexts: this.buildContexts(event, {\n        trace_id: traceId,\n        span_id: spanId,\n        op: event.eventType || \"mcp.event\",\n        status: event.isError ? \"internal_error\" : \"ok\",\n      }) as SentryTransaction[\"contexts\"],\n      tags: this.buildTags(event),\n      extra: this.buildExtra(event),\n    };\n\n    return transaction;\n  }\n\n  private buildTags(event: Event): Record<string, string> {\n    const tags: Record<string, string> = {\n      source: AGENTCAT_SOURCE,\n    };\n\n    if (this.config.environment) tags.environment = this.config.environment;\n    if (this.config.release) tags.release = this.config.release;\n    if (event.eventType) tags.event_type = event.eventType;\n    if (event.resourceName) tags.resource = event.resourceName;\n    if (event.serverName) tags.server_name = event.serverName;\n    if (event.clientName) tags.client_name = event.clientName;\n    if (event.identifyActorGivenId) tags.actor_id = event.identifyActorGivenId;\n\n    // Add customer-defined tags (namespaced to avoid collisions with Sentry reserved fields)\n    if (event.tags) {\n      for (const [key, value] of Object.entries(event.tags)) {\n        tags[`agentcat.${key}`] = value;\n      }\n    }\n\n    return tags;\n  }\n\n  private buildExtra(event: Event): Record<string, any> {\n    const extra: Record<string, any> = {};\n\n    if (event.sessionId) extra.session_id = event.sessionId;\n    if (event.projectId) extra.project_id = event.projectId;\n    if (event.userIntent) extra.user_intent = event.userIntent;\n    if (event.identifyActorName) extra.actor_name = event.identifyActorName;\n    if (event.serverVersion) extra.server_version = event.serverVersion;\n    if (event.clientVersion) extra.client_version = event.clientVersion;\n    if (event.duration !== undefined) extra.duration_ms = event.duration;\n    if (event.error) extra.error = event.error;\n\n    return extra;\n  }\n\n  private buildContexts(\n    event: Event,\n    traceCtx: Record<string, any>,\n  ): Record<string, any> {\n    const contexts: Record<string, any> = {\n      trace: traceCtx,\n    };\n\n    // Add customer-defined properties as a custom context\n    if (event.properties) {\n      contexts.agentcat = event.properties;\n    }\n\n    return contexts;\n  }\n\n  private eventToErrorEvent(\n    event: Event,\n    transaction?: SentryTransaction,\n  ): SentryErrorEvent {\n    // Extract error message\n    let errorMessage = \"Unknown error\";\n    let errorType = \"ToolCallError\";\n\n    if (event.error) {\n      if (typeof event.error === \"string\") {\n        errorMessage = event.error;\n      } else if (typeof event.error === \"object\" && event.error !== null) {\n        if (\"message\" in event.error) {\n          errorMessage = String(event.error.message);\n        } else {\n          errorMessage = JSON.stringify(event.error);\n        }\n        if (\"type\" in event.error) {\n          errorType = String(event.error.type);\n        }\n      }\n    }\n\n    // Use same trace context as the transaction for correlation (if available)\n    const traceId = transaction\n      ? transaction.contexts.trace.trace_id\n      : traceContext.getTraceId(event.sessionId);\n    const spanId = traceContext.getSpanId(event.id);\n\n    const timestamp = transaction\n      ? transaction.timestamp\n      : event.timestamp\n        ? new Date(event.timestamp).getTime() / 1000\n        : Date.now() / 1000;\n\n    const errorEvent: SentryErrorEvent = {\n      type: \"event\",\n      event_id: traceContext.getSpanId(event.id) + traceContext.getSpanId(),\n      timestamp,\n      level: \"error\",\n      exception: {\n        values: [\n          {\n            type: errorType,\n            value: errorMessage,\n            mechanism: {\n              type: \"mcp_tool_call\",\n              handled: false,\n            },\n          },\n        ],\n      },\n      contexts: {\n        ...this.buildContexts(event, {\n          trace_id: traceId,\n          span_id: spanId,\n          parent_span_id: transaction?.contexts.trace.span_id,\n          op: transaction?.contexts.trace.op || event.eventType || \"mcp.event\",\n        }),\n        mcp: {\n          resource_name: event.resourceName,\n          session_id: event.sessionId,\n          event_type: event.eventType,\n          user_intent: event.userIntent,\n        },\n      },\n      tags: this.buildTags(event),\n      extra: this.buildExtra(event),\n      transaction:\n        transaction?.transaction ||\n        (event.resourceName\n          ? `${event.eventType || \"mcp\"} - ${event.resourceName}`\n          : event.eventType || \"mcp.event\"), // Generate transaction name if not available\n    };\n\n    return errorEvent;\n  }\n\n  private createTransactionEnvelope(transaction: SentryTransaction): string {\n    // Envelope header\n    const envelopeHeader = {\n      event_id: transaction.event_id,\n      sent_at: new Date().toISOString(),\n    };\n\n    // Item header for transaction\n    const itemHeader = {\n      type: \"transaction\",\n    };\n\n    // Build envelope (newline-separated JSON)\n    return [\n      JSON.stringify(envelopeHeader),\n      JSON.stringify(itemHeader),\n      JSON.stringify(transaction),\n    ].join(\"\\n\");\n  }\n\n  private createErrorEnvelope(errorEvent: SentryErrorEvent): string {\n    // Envelope header\n    const envelopeHeader = {\n      event_id: errorEvent.event_id,\n      sent_at: new Date().toISOString(),\n    };\n\n    // Item header for error event\n    const itemHeader = {\n      type: \"event\",\n      content_type: \"application/json\",\n    };\n\n    // Build envelope (newline-separated JSON)\n    return [\n      JSON.stringify(envelopeHeader),\n      JSON.stringify(itemHeader),\n      JSON.stringify(errorEvent),\n    ].join(\"\\n\");\n  }\n}\n","import { createHash } from \"crypto\";\nimport { Event, Exporter } from \"../../types.js\";\nimport { writeToLog } from \"../logging.js\";\nimport { PublishEventRequestEventTypeEnum } from \"agentcat-api\";\nimport { AGENTCAT_SOURCE } from \"../constants.js\";\nimport KSUID from \"../../thirdparty/ksuid/index.js\";\n\n/**\n * Generates a deterministic UUIDv7 from a prefixed KSUID (e.g. ses_xxx).\n * Uses the KSUID's embedded timestamp for the UUIDv7 timestamp portion\n * and a SHA-256 hash of the full ID for the random bits.\n */\nexport function toUUIDv7(prefixedId: string): string {\n  // Hash the full ID for deterministic random bits (and fallback timestamp)\n  const hash = createHash(\"sha256\").update(prefixedId).digest();\n\n  // Strip prefix (ses_, evt_, etc.) and parse KSUID\n  const ksuidStr = prefixedId.replace(/^[a-z]+_/, \"\");\n  let timestampMs: number;\n  try {\n    const ksuid = KSUID.parse(ksuidStr);\n    timestampMs = ksuid.date.getTime();\n  } catch {\n    // Fallback: non-KSUID input (e.g. verbatim customer session IDs). Derive the\n    // 48-bit timestamp from the hash so the same input always yields the same\n    // UUIDv7 — Date.now() here would fragment one task across sessions.\n    timestampMs = hash.readUIntBE(10, 6);\n  }\n\n  const buf = Buffer.alloc(16);\n\n  // Bytes 0-5: 48-bit Unix timestamp in milliseconds\n  buf.writeUIntBE(timestampMs, 0, 6);\n\n  // Byte 6: version 7 (0111) + high 4 bits of rand_a from hash\n  buf[6] = 0x70 | (hash[0] & 0x0f);\n  // Byte 7: low 8 bits of rand_a from hash\n  buf[7] = hash[1];\n\n  // Byte 8: variant 10 + high 6 bits of rand_b from hash\n  buf[8] = 0x80 | (hash[2] & 0x3f);\n  // Bytes 9-15: remaining rand_b from hash\n  buf[9] = hash[3];\n  buf[10] = hash[4];\n  buf[11] = hash[5];\n  buf[12] = hash[6];\n  buf[13] = hash[7];\n  buf[14] = hash[8];\n  buf[15] = hash[9];\n\n  const hex = buf.toString(\"hex\");\n  return [\n    hex.substring(0, 8),\n    hex.substring(8, 12),\n    hex.substring(12, 16),\n    hex.substring(16, 20),\n    hex.substring(20, 32),\n  ].join(\"-\");\n}\n\nfunction getDistinctId(event: Event): string {\n  return event.identifyActorGivenId || event.sessionId || \"anonymous\";\n}\n\nfunction getTimestamp(event: Event): string {\n  return event.timestamp\n    ? event.timestamp.toISOString()\n    : new Date().toISOString();\n}\n\nexport interface PostHogExporterConfig {\n  type: \"posthog\";\n  apiKey: string; // PostHog project API key (e.g. phc_...)\n  host?: string; // Default: \"https://us.i.posthog.com\" (supports self-hosted & EU region)\n  /**\n   * Emits `$ai_span` events for tool calls alongside regular capture events,\n   * integrating with PostHog's AI observability views. Each tool call is its own\n   * trace (`$ai_trace_id`), grouped into sessions via `$ai_session_id`.\n   * Customer-defined `eventTags` are spread directly onto `$ai_span` properties\n   * and can override any default, including reserved `$ai_*` fields.\n   * @default false\n   */\n  enableAITracing?: boolean;\n}\n\ninterface PostHogCaptureEvent {\n  event: string;\n  distinct_id: string;\n  properties: Record<string, any>;\n  timestamp: string;\n  type: \"capture\";\n}\n\nexport class PostHogExporter implements Exporter {\n  private batchUrl: string;\n  private apiKey: string;\n  private config: PostHogExporterConfig;\n\n  constructor(config: PostHogExporterConfig) {\n    this.config = config;\n    const host = (config.host || \"https://us.i.posthog.com\").replace(/\\/$/, \"\");\n    this.batchUrl = `${host}/batch`;\n    this.apiKey = config.apiKey;\n\n    writeToLog(`PostHogExporter: Initialized with endpoint ${this.batchUrl}`);\n  }\n\n  async export(event: Event): Promise<void> {\n    try {\n      const batch: PostHogCaptureEvent[] = [];\n\n      // Always send the regular event\n      batch.push(this.buildCaptureEvent(event));\n\n      // Send $exception event alongside if this is an error\n      if (event.isError && event.error) {\n        batch.push(this.buildExceptionEvent(event));\n      }\n\n      // Send $ai_span for tool calls when AI tracing is enabled\n      if (\n        this.config.enableAITracing &&\n        event.eventType === PublishEventRequestEventTypeEnum.mcpToolsCall\n      ) {\n        batch.push(this.buildAISpanEvent(event));\n      }\n\n      writeToLog(\n        `PostHogExporter: Sending ${batch.length} event(s) for ${event.id}`,\n      );\n\n      const response = await fetch(this.batchUrl, {\n        method: \"POST\",\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n        body: JSON.stringify({\n          api_key: this.apiKey,\n          batch,\n        }),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.text();\n        writeToLog(\n          `PostHog export failed - Status: ${response.status}, Body: ${errorBody}`,\n        );\n      } else {\n        writeToLog(`PostHog export success - Event: ${event.id}`);\n      }\n    } catch (error) {\n      writeToLog(`PostHog export error: ${error}`);\n    }\n  }\n\n  private buildCaptureEvent(event: Event): PostHogCaptureEvent {\n    const distinctId = getDistinctId(event);\n    const eventName = this.mapEventType(event.eventType);\n    const timestamp = getTimestamp(event);\n\n    const properties: Record<string, any> = {\n      source: AGENTCAT_SOURCE,\n    };\n    // Sessionless events (empty sessionId) get no $session_id at all —\n    // synthesizing one would group unrelated events into a fake session.\n    if (event.sessionId) {\n      properties.$session_id = toUUIDv7(event.sessionId);\n    }\n\n    if (event.resourceName) {\n      properties.resource_name = event.resourceName;\n      if (event.eventType === PublishEventRequestEventTypeEnum.mcpToolsCall) {\n        properties.tool_name = event.resourceName;\n      }\n    }\n    if (event.duration !== undefined) {\n      properties.duration_ms = event.duration;\n    }\n    if (event.serverName) properties.server_name = event.serverName;\n    if (event.serverVersion) properties.server_version = event.serverVersion;\n    if (event.clientName) properties.client_name = event.clientName;\n    if (event.clientVersion) properties.client_version = event.clientVersion;\n    if (event.projectId) properties.project_id = event.projectId;\n    if (event.userIntent) properties.user_intent = event.userIntent;\n    if (event.isError !== undefined) properties.is_error = event.isError;\n\n    if (event.parameters !== undefined) {\n      properties.parameters = event.parameters;\n    }\n    if (event.response !== undefined) {\n      properties.response = event.response;\n    }\n\n    // Set person properties from identity data\n    const $set: Record<string, any> = {};\n    if (event.identifyActorName) $set.name = event.identifyActorName;\n    if (event.identifyActorData) {\n      Object.assign($set, event.identifyActorData);\n    }\n    if (Object.keys($set).length > 0) {\n      properties.$set = $set;\n    }\n\n    // Spread customer-defined tags directly (can override AgentCat defaults)\n    if (event.tags) {\n      for (const [key, value] of Object.entries(event.tags)) {\n        properties[key] = value;\n      }\n    }\n\n    // Spread customer-defined properties directly (can override AgentCat defaults)\n    if (event.properties) {\n      for (const [key, value] of Object.entries(event.properties)) {\n        properties[key] = value;\n      }\n    }\n\n    return {\n      event: eventName,\n      distinct_id: distinctId,\n      properties,\n      timestamp,\n      type: \"capture\",\n    };\n  }\n\n  private buildExceptionEvent(event: Event): PostHogCaptureEvent {\n    const distinctId = getDistinctId(event);\n    const timestamp = getTimestamp(event);\n\n    const properties: Record<string, any> = {\n      $exception_source: \"backend\",\n    };\n    if (event.sessionId) {\n      properties.$session_id = toUUIDv7(event.sessionId);\n    }\n\n    if (event.error) {\n      if (event.error.message) {\n        properties.$exception_message = event.error.message;\n      }\n      if (event.error.type) {\n        properties.$exception_type = event.error.type;\n      }\n      if (event.error.stack) {\n        properties.$exception_stacktrace = event.error.stack;\n      }\n    }\n\n    // Add tool/resource context\n    if (event.resourceName) {\n      properties.resource_name = event.resourceName;\n      if (event.eventType === PublishEventRequestEventTypeEnum.mcpToolsCall) {\n        properties.tool_name = event.resourceName;\n      }\n    }\n    if (event.serverName) properties.server_name = event.serverName;\n    if (event.serverVersion) properties.server_version = event.serverVersion;\n    if (event.clientName) properties.client_name = event.clientName;\n    if (event.clientVersion) properties.client_version = event.clientVersion;\n\n    return {\n      event: \"$exception\",\n      distinct_id: distinctId,\n      properties,\n      timestamp,\n      type: \"capture\",\n    };\n  }\n\n  private buildAISpanEvent(event: Event): PostHogCaptureEvent {\n    const distinctId = getDistinctId(event);\n    const timestamp = getTimestamp(event);\n\n    const properties: Record<string, any> = {\n      // Sessionless events fall back to a per-event trace; $ai_session_id and\n      // $session_id are omitted rather than synthesized from \"\".\n      $ai_trace_id: toUUIDv7(event.sessionId || event.id),\n      $ai_span_id: toUUIDv7(event.id),\n      $ai_span_name: event.resourceName || \"unknown_tool\",\n      $ai_is_error: event.isError || false,\n      source: AGENTCAT_SOURCE,\n    };\n    if (event.sessionId) {\n      properties.$ai_session_id = `agentcat_${event.sessionId}`;\n      properties.$session_id = toUUIDv7(event.sessionId);\n    }\n\n    if (event.duration !== undefined) {\n      properties.$ai_latency = event.duration / 1000;\n    }\n    if (event.isError && event.error) {\n      properties.$ai_error = event.error;\n    }\n    if (event.parameters !== undefined) {\n      properties.$ai_input_state = event.parameters;\n    }\n    if (event.response !== undefined) {\n      properties.$ai_output_state = event.response;\n    }\n    if (event.serverName) properties.server_name = event.serverName;\n    if (event.clientName) properties.client_name = event.clientName;\n\n    // Spread customer tags directly (can override AgentCat defaults)\n    if (event.tags) {\n      for (const [key, value] of Object.entries(event.tags)) {\n        properties[key] = value;\n      }\n    }\n\n    // Spread customer properties directly (can override AgentCat defaults)\n    if (event.properties) {\n      for (const [key, value] of Object.entries(event.properties)) {\n        properties[key] = value;\n      }\n    }\n\n    return {\n      event: \"$ai_span\",\n      distinct_id: distinctId,\n      properties,\n      timestamp,\n      type: \"capture\",\n    };\n  }\n\n  private mapEventType(eventType: string): string {\n    // Map AgentCat event types to PostHog event names\n    const mapping: Record<string, string> = {\n      [PublishEventRequestEventTypeEnum.mcpToolsCall]: \"mcp_tool_call\",\n      [PublishEventRequestEventTypeEnum.mcpToolsList]: \"mcp_tools_list\",\n      [PublishEventRequestEventTypeEnum.mcpInitialize]: \"mcp_initialize\",\n      [PublishEventRequestEventTypeEnum.mcpResourcesRead]: \"mcp_resource_read\",\n      [PublishEventRequestEventTypeEnum.mcpResourcesList]: \"mcp_resources_list\",\n      [PublishEventRequestEventTypeEnum.mcpPromptsGet]: \"mcp_prompt_get\",\n      [PublishEventRequestEventTypeEnum.mcpPromptsList]: \"mcp_prompts_list\",\n    };\n\n    return (\n      mapping[eventType] ||\n      `mcp_${eventType.replace(/^mcp:/, \"\").replace(/\\//g, \"_\")}`\n    );\n  }\n}\n","import { Event, Exporter, ExporterConfig } from \"../types.js\";\nimport { writeToLog } from \"./logging.js\";\nimport { OTLPExporter } from \"./exporters/otlp.js\";\nimport { DatadogExporter } from \"./exporters/datadog.js\";\nimport { SentryExporter } from \"./exporters/sentry.js\";\nimport { PostHogExporter } from \"./exporters/posthog.js\";\n\nexport class TelemetryManager {\n  private exporters: Map<string, Exporter> = new Map();\n\n  constructor(exporterConfigs?: Record<string, ExporterConfig>) {\n    if (!exporterConfigs) return;\n\n    for (const [name, config] of Object.entries(exporterConfigs)) {\n      try {\n        const exporter = this.createExporter(name, config);\n        if (exporter) {\n          this.exporters.set(name, exporter);\n          writeToLog(`Initialized telemetry exporter: ${name}`);\n        }\n      } catch (error) {\n        writeToLog(`Failed to initialize exporter ${name}: ${error}`);\n      }\n    }\n  }\n\n  private createExporter(\n    name: string,\n    config: ExporterConfig,\n  ): Exporter | null {\n    switch (config.type) {\n      case \"otlp\":\n        return new OTLPExporter(config as any);\n      case \"datadog\":\n        return new DatadogExporter(config as any);\n      case \"sentry\":\n        return new SentryExporter(config as any);\n      case \"posthog\":\n        return new PostHogExporter(config as any);\n      default:\n        writeToLog(`Unknown exporter type: ${config.type}`);\n        return null;\n    }\n  }\n\n  async export(event: Event): Promise<void> {\n    if (this.exporters.size === 0) return;\n\n    // Telemetry errors should be logged but not propagated\n    for (const [name, exporter] of this.exporters) {\n      exporter.export(event).catch((error) => {\n        const errorMessage =\n          error instanceof Error ? error.message : String(error);\n        writeToLog(`Telemetry export failed for ${name}: ${errorMessage}`);\n      });\n    }\n  }\n\n  getExporterCount(): number {\n    return this.exporters.size;\n  }\n}\n","export interface AgentCatOptions {\n  enableReportMissing?: boolean;\n  enableTracing?: boolean;\n  enableToolCallContext?: boolean;\n  customContextDescription?: string;\n  /**\n   * Default false. Set true to inject a required agent_id parameter into every\n   * tool. Agents self-generate the value (model|harness|nonce, e.g.\n   * \"opus-4.80-1m|claude-code|k3n9x\"); it is echoed back in mcp_session\n   * and stamped on events as tags. Omission never rejects a call server-side —\n   * the event is simply published without agent identity. The intended\n   * enforcement is client-side: a strict schema-validating MCP client will\n   * refuse to send a call that omits a required agent_id in the first place.\n   */\n  enableAgentTracking?: boolean;\n  /**\n   * Hook mode: you manage task state. When configured, AgentCat injects no\n   * session_id parameter and prepends no issuance text; the returned value is\n   * combined with the project ID into a deterministic ses_ KSUID. Nullish\n   * returns and throws mint silently — a configured hook should answer every\n   * request.\n   */\n  resolveSessionId?: (\n    request: any,\n    extra?: CompatibleRequestHandlerExtra,\n  ) => string | null | Promise<string | null>;\n  identify?: (\n    request: any,\n    extra?: CompatibleRequestHandlerExtra,\n  ) => Promise<UserIdentity | null>;\n  redactSensitiveInformation?: RedactFunction;\n  redactEvent?: RedactEventFunction;\n  exporters?: Record<string, ExporterConfig>;\n  apiBaseUrl?: string;\n  disableDiagnostics?: boolean;\n  eventTags?: (\n    request: any,\n    extra?: CompatibleRequestHandlerExtra,\n  ) => Record<string, string> | null | Promise<Record<string, string> | null>;\n  eventProperties?: (\n    request: any,\n    extra?: CompatibleRequestHandlerExtra,\n  ) => Record<string, any> | null | Promise<Record<string, any> | null>;\n}\n\nexport interface CompatibleToolResult {\n  content?: Array<Record<string, unknown>>;\n  structuredContent?: unknown;\n  isError?: boolean;\n  [key: string]: unknown;\n}\n\nexport type ToolCallback =\n  | ((\n      args: any,\n      extra: CompatibleRequestHandlerExtra,\n    ) => CompatibleToolResult | Promise<CompatibleToolResult>)\n  | ((\n      extra: CompatibleRequestHandlerExtra,\n    ) => CompatibleToolResult | Promise<CompatibleToolResult>);\n\n// RegisteredTool type that supports both MCP SDK 1.23- (callback) and 1.24+ (handler)\nexport type RegisteredTool = {\n  description?: string;\n  inputSchema?: any;\n  update?: (...args: any[]) => any;\n} & (\n  | { callback: ToolCallback; handler?: never }\n  | { handler: ToolCallback; callback?: never }\n);\n\nexport type RedactFunction = (text: string) => Promise<string>;\n\nexport type RedactEventFunction = (\n  event: Event,\n) => Event | null | Promise<Event | null>;\n\nexport interface ExporterConfig {\n  type: string;\n  [key: string]: any;\n}\n\nexport interface Exporter {\n  export(event: Event): Promise<void>;\n}\n\nexport enum AgentCatIDPrefixes {\n  Session = \"ses\", // Session IDs deliberately keep this prefix\n  Event = \"evt\",\n  Agent = \"agt\",\n}\n\nexport interface Event {\n  // Core identification\n  id: string;\n  sessionId: string;\n  projectId?: string; // Optional for telemetry-only mode\n\n  // Event metadata\n  eventType: string; // Changed from enum to string for flexibility\n  timestamp: Date;\n  duration?: number;\n\n  // Session context (from SessionInfo)\n  ipAddress?: string;\n  sdkLanguage?: string;\n  agentcatVersion?: string;\n  serverName?: string;\n  serverVersion?: string;\n  clientName?: string;\n  clientVersion?: string;\n\n  // Actor/identity information\n  identifyActorGivenId?: string;\n  identifyActorName?: string;\n  identifyActorData?: object;\n\n  // Event-specific data\n  resourceName?: string; // Tool/resource name\n  parameters?: any;\n  response?: any;\n  userIntent?: string;\n\n  // Error tracking\n  isError?: boolean;\n  error?: ErrorData;\n\n  // Customer-defined metadata\n  tags?: Record<string, string> | null;\n  properties?: Record<string, any> | null;\n\n  // Legacy fields for AgentCat API compatibility\n  actorId?: string; // Maps to identifyActorGivenId in some contexts\n  eventId?: string; // Custom event ID\n  identifyData?: object; // Legacy name for identifyActorData\n}\n\n/**\n * Promises for customer-hook results, fired at request start and resolved in\n * the background event pipeline — customer hooks never hold up the tool call.\n * Every promise here is constructed non-rejecting (hook failures resolve to\n * null). Never serialized: detached at the top of processEvent before any\n * pipeline stage or the wire payload can see it.\n */\nexport interface PendingEventFields {\n  /** Raw resolveSessionId hook value (pre-derivation). */\n  sessionHookValue?: Promise<string | null>;\n  identity?: Promise<UserIdentity | null>;\n  tags?: Promise<Record<string, string> | null>;\n  properties?: Promise<Record<string, any> | null>;\n}\n\nexport interface UnredactedEvent extends Partial<Event> {\n  redactionFn?: RedactFunction; // Optional redaction function for sensitive data\n  eventRedactionFn?: RedactEventFunction; // Optional whole-event redaction hook\n  pending?: PendingEventFields; // Deferred hook results, applied in the queue\n}\n\n/**\n * Duck type over the second argument the MCP SDK passes to request handlers,\n * covering both supported majors:\n * - v1 (`@modelcontextprotocol/sdk`): the SDK's `RequestHandlerExtra` —\n *   e.g. `sessionId`, `authInfo`, `requestId`.\n * - v2 (`@modelcontextprotocol/server`): the SDK's `ServerContext` —\n *   `{ sessionId, mcpReq, http }`; note `http?.req?.headers` is a Web\n *   `Headers` object (use `.get(\"x-header\")`, not bracket access).\n *\n * Only `sessionId` is common to both; everything else is reached through the\n * index signature and is SDK-version-specific.\n */\nexport interface CompatibleRequestHandlerExtra {\n  /**\n   * The MCP transport session, assigned by the SDK and reset on reconnect.\n   * NOT AgentCat's `session_id` handle, which outlives the transport — that\n   * one is the agent-echoed tool parameter stored in `Event.sessionId`.\n   */\n  sessionId?: string;\n  [key: string]: any;\n}\n\nexport interface ServerClientInfoLike {\n  name?: string;\n  version?: string;\n}\n\nexport interface HighLevelMCPServerLike {\n  _registeredTools: { [name: string]: RegisteredTool };\n  server: MCPServerLike;\n  // Tool registration methods - simplified signatures without Zod dependency\n  tool?(name: string, cb: ToolCallback): void;\n  tool?(name: string, description: string, cb: ToolCallback): void;\n  tool?(name: string, paramsSchema: any, cb: ToolCallback): void;\n  tool?(\n    name: string,\n    description: string,\n    paramsSchema: any,\n    cb: ToolCallback,\n  ): void;\n  registerTool?(\n    name: string,\n    config: {\n      description?: string;\n      inputSchema?: any;\n    },\n    handler: ToolCallback,\n  ): void;\n}\n\nexport interface MCPServerLike {\n  setRequestHandler(\n    schema: any,\n    handler: (\n      request: any,\n      extra?: CompatibleRequestHandlerExtra,\n    ) => Promise<any>,\n  ): void;\n  _requestHandlers: Map<\n    string,\n    (request: any, extra?: CompatibleRequestHandlerExtra) => Promise<any>\n  >;\n  _serverInfo?: ServerClientInfoLike;\n  getClientVersion(): ServerClientInfoLike | undefined;\n}\n\nexport interface UserIdentity {\n  userId: string; // Unique identifier for the user\n  userName?: string; // Optional user name\n  userData?: Record<string, any>; // Additional user data\n}\n\nexport interface SessionInfo {\n  ipAddress?: string;\n  sdkLanguage?: string;\n  agentcatVersion?: string;\n  serverName?: string;\n  serverVersion?: string;\n  clientName?: string;\n  clientVersion?: string;\n  identifyActorGivenId?: string; // Actor identity stamped on every event\n  identifyActorName?: string; // Actor identity stamped on every event\n  identifyActorData?: object;\n}\n\nexport interface AgentCatData {\n  projectId: string; // Project ID for AgentCat (\"\" in telemetry-only mode)\n  options: AgentCatOptions;\n}\n\n// Error tracking types\nexport interface StackFrame {\n  filename: string;\n  function: string; // Function name or \"<anonymous>\"\n  lineno?: number;\n  colno?: number;\n  in_app: boolean;\n  abs_path?: string;\n  context_line?: string; // The line of code where the error occurred\n}\n\nexport interface ChainedErrorData {\n  message: string;\n  type?: string;\n  stack?: string;\n  frames?: StackFrame[];\n}\n\nexport interface ErrorData {\n  message: string;\n  type?: string; // Error class name (e.g., \"TypeError\", \"Error\")\n  stack?: string; // Full stack trace string\n  frames?: StackFrame[]; // Parsed stack frames\n  chained_errors?: ChainedErrorData[];\n  platform?: string; // Platform identifier (e.g., \"javascript\", \"node\")\n}\n\n// Custom event types for publishCustomEvent function\nexport interface CustomEventData {\n  /** Session ID to attribute this event to. Takes precedence over a session-id string argument. */\n  sessionId?: string;\n  resourceName?: string;\n  parameters?: any;\n  response?: any;\n  message?: string;\n  duration?: number;\n  isError?: boolean;\n  error?: any;\n  tags?: Record<string, string>;\n  properties?: Record<string, any>;\n}\n","// Import our minimal interface from types\nimport {\n  AgentCatOptions,\n  AgentCatData,\n  MCPServerLike,\n  CustomEventData,\n  UnredactedEvent,\n} from \"./types.js\";\n\n// Import from modules\nimport { detectServer, describeSignals } from \"./detect.js\";\nimport { installEngine } from \"./engine/index.js\";\nimport { isCompatibleServerType } from \"./modules/compatibility.js\";\nimport { writeToLog } from \"./modules/logging.js\";\nimport {\n  setServerTrackingData,\n  getServerTrackingData,\n} from \"./modules/internal.js\";\nimport { TelemetryManager } from \"./modules/telemetry.js\";\nimport {\n  setTelemetryManager,\n  getTelemetryManager,\n  publishEvent as publishEventToQueue,\n  eventQueue,\n} from \"./modules/eventQueue.js\";\nimport { AGENTCAT_CUSTOM_EVENT_TYPE } from \"./modules/constants.js\";\nimport { validateTags } from \"./modules/validation.js\";\nimport { initDiagnostics } from \"./modules/diagnostics.js\";\n\n/**\n * Integrates AgentCat analytics into an MCP server to track tool usage patterns and user interactions.\n *\n * @param server - The MCP server instance to track. Must be a compatible MCP server implementation.\n *   Both TypeScript SDK majors are supported with the same call — `@modelcontextprotocol/sdk` >=1.11 <2\n *   (v1 `Server`/`McpServer`) and `@modelcontextprotocol/server` >=2 <3 (v2 `McpServer`, including\n *   instances built inside `createMcpHandler`/`serveStdio` factories). The SDK major is auto-detected\n *   per server object.\n * @param projectId - Your AgentCat project ID obtained from agentcat.com when creating an account. Pass null for telemetry-only mode.\n * @param options - Optional configuration to customize tracking behavior.\n * @param options.enableReportMissing - Adds a \"get_more_tools\" tool that allows LLMs to automatically report missing functionality.\n * @param options.enableTracing - Enables tracking of tool calls and usage patterns.\n * @param options.enableToolCallContext - Injects a \"context\" parameter to existing tools to capture user intent. The context parameter is appended after the injected `session_id`/`agent_id` parameters.\n * @param options.customContextDescription - Custom description for the injected context parameter. Only applies when enableToolCallContext is true. Use this to provide domain-specific guidance to LLMs about what context they should provide.\n * @param options.enableAgentTracking - Injects an optional `agent_id` parameter so each agent (including every spawned subagent) is individually identifiable. Agent IDs are minted by the server on an agent's first call and echoed back on subsequent calls. Defaults to false (opt-in). The agent ID rides on events as the `agentcat_agent_id` tag.\n * @param options.resolveSessionId - Hook mode: supply your own session identifier per request (e.g. from your auth or workflow state) and AgentCat steps back — no `session_id` parameter is injected and no issuance text is prepended to results. The returned string is combined with your project ID into a deterministic KSUID, so the same identifier always maps to the same task. Return null to mint silently (avoid: the agent can never learn a silently minted ID). Receives the same `(request, extra)` arguments as `identify`.\n * @param options.identify - Async function to identify the actor behind a tool call. Runs on every tool call; the result is stamped directly onto that call's event.\n * @param options.redactSensitiveInformation - Function to redact sensitive data before sending to AgentCat.\n * @param options.redactEvent - Event-level redaction hook invoked with the full event (inspect `resourceName`, `eventType`, `parameters`, `response`, etc.) before it is published. Return a modified event, or null to drop the event entirely. May be sync or async. Runs before `redactSensitiveInformation`, so it sees raw, unredacted values; the string-level hook, sanitization, and truncation still run on its output. The system-managed fields `id`, `sessionId`, `projectId`, `eventType`, and `timestamp` cannot be changed (`id` is assigned after redaction and is empty at hook time). If the hook throws, the event is dropped and the error is logged to `~/agentcat.log`.\n * @param options.eventTags - Callback invoked on every auto-captured tool call to attach string key-value tags. Tags are intended to be indexed and queryable in the AgentCat dashboard — use them for structured metadata you'll want to filter or group by (e.g., trace IDs, environments, regions). Tags are validated client-side: keys must be ≤32 chars matching `[a-zA-Z0-9$_.:\\- ]`, values must be strings ≤200 chars with no newlines, max 50 entries per event. Invalid entries are silently dropped with a warning logged to `~/agentcat.log`. If the callback throws or returns null, tags are omitted. Receives the same `(request, extra)` arguments as `identify`.\n * @param options.eventProperties - Callback invoked on every auto-captured tool call to attach flexible JSON metadata (device info, feature flags, nested context). No constraints beyond standard JSON types. If the callback throws or returns null, properties are omitted. Receives the same `(request, extra)` arguments as `identify`.\n * @param options.apiBaseUrl - Custom API base URL for sending events. Falls back to the `AGENTCAT_API_URL` environment variable if not set (then legacy `MCPCAT_API_URL`), then to the default `https://api.agentcat.com`.\n * @param options.disableDiagnostics - Disables AgentCat's internal SDK diagnostics (anonymous error/telemetry reporting used to monitor SDK setup failures). Diagnostics are on by default, automatically disabled in test environments (`VITEST`, `JEST_WORKER_ID`, or `NODE_ENV=test`), and can also be disabled with the `DISABLE_DIAGNOSTICS` environment variable. Local `~/agentcat.log` logging is unaffected.\n * @param options.exporters - Configure telemetry exporters to send events to external systems. Available exporters:\n *   - `otlp`: OpenTelemetry Protocol exporter (see {@link ../modules/exporters/otlp.OTLPExporter})\n *   - `datadog`: Datadog APM exporter (see {@link ../modules/exporters/datadog.DatadogExporter})\n *   - `sentry`: Sentry Monitoring exporter (see {@link ../modules/exporters/sentry.SentryExporter})\n *   - `posthog`: PostHog analytics exporter (see {@link ../modules/exporters/posthog.PostHogExporter})\n *\n * @returns The tracked server instance.\n *\n * @remarks\n * Analytics data and debug information are logged to `~/agentcat.log` since console logs interfere\n * with STDIO-based MCP servers.\n *\n * Do not call `track()` multiple times on the same server instance as this will cause unexpected behavior.\n *\n * @example\n * ```typescript\n * import * as agentcat from \"agentcat\";\n *\n * const mcpServer = new Server({ name: \"my-mcp-server\", version: \"1.0.0\" });\n *\n * // Track the server with AgentCat\n * agentcat.track(mcpServer, \"proj_abc123xyz\");\n *\n * // Register your tools\n * mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({\n *   tools: [{ name: \"my_tool\", description: \"Does something useful\" }]\n * }));\n * ```\n *\n * @example\n * ```typescript\n * // MCP SDK v2 (@modelcontextprotocol/server) — same call, auto-detected\n * import { McpServer } from \"@modelcontextprotocol/server\";\n * import { z } from \"zod\";\n * import * as agentcat from \"agentcat\";\n *\n * const server = new McpServer(\n *   { name: \"my-mcp-server\", version: \"1.0.0\" },\n *   { capabilities: { tools: {} } },\n * );\n *\n * server.registerTool(\n *   \"my_tool\",\n *   { description: \"Does something useful\", inputSchema: z.object({ msg: z.string() }) },\n *   async (args) => ({ content: [{ type: \"text\", text: args.msg }] }),\n * );\n *\n * agentcat.track(server, \"proj_abc123xyz\");\n * ```\n *\n * @example\n * ```typescript\n * // MCP 2026-07-28 era (createMcpHandler / serveStdio): call track() inside\n * // the factory so every per-request instance is tracked.\n * import { createMcpHandler, McpServer } from \"@modelcontextprotocol/server\";\n * import * as agentcat from \"agentcat\";\n *\n * const handler = createMcpHandler(() => {\n *   const server = new McpServer({ name: \"my-server\", version: \"1.0.0\" }, { capabilities: { tools: {} } });\n *   // register tools...\n *   return agentcat.track(server, \"proj_abc123xyz\"); // track every per-request instance\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With user identification\n * agentcat.track(mcpServer, \"proj_abc123xyz\", {\n *   identify: async (request, extra) => {\n *     const user = await getUserFromToken(request.params.arguments.token);\n *     return {\n *       userId: user.id,\n *       userData: { plan: user.plan, company: user.company }\n *     };\n *   }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With custom context description\n * agentcat.track(mcpServer, \"proj_abc123xyz\", {\n *   enableToolCallContext: true,\n *   customContextDescription: \"Explain why you're calling this tool and what business objective it helps achieve\"\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With sensitive data redaction\n * agentcat.track(mcpServer, \"proj_abc123xyz\", {\n *   redactSensitiveInformation: async (text) => {\n *     return text.replace(/api_key_\\w+/g, \"[REDACTED]\");\n *   }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With event-level redaction\n * agentcat.track(mcpServer, \"proj_abc123xyz\", {\n *   redactEvent: (event) => {\n *     // Drop events from tools that handle secrets entirely\n *     if (event.resourceName === \"get_credentials\") {\n *       return null;\n *     }\n *     // Strip response payloads from a specific tool\n *     if (event.resourceName === \"export_report\") {\n *       return { ...event, response: undefined };\n *     }\n *     return event;\n *   }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // With event tags and properties. The `extra` shape is SDK-version-specific:\n * // on v2 it is the SDK's ServerContext ({ sessionId, mcpReq, http }) as shown\n * // here; on v1 it is the SDK's RequestHandlerExtra.\n * agentcat.track(mcpServer, \"proj_abc123xyz\", {\n *   eventTags: async (request, extra) => ({\n *     request_id: String(extra?.mcpReq?.id ?? \"\"),\n *     env: process.env.NODE_ENV,\n *     region: \"us-east-1\",\n *   }),\n *   eventProperties: async (request, extra) => ({\n *     device: \"desktop\",\n *     app_version: \"2.1.0\",\n *     feature_flags: [\"dark_mode\", \"beta_ui\"],\n *   }),\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Telemetry-only mode (no AgentCat account required)\n * agentcat.track(mcpServer, null, {\n *   exporters: {\n *     otlp: {\n *       type: \"otlp\",\n *       endpoint: \"http://localhost:4318/v1/traces\"\n *     }\n *   }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Dual mode - send to both AgentCat and telemetry exporters\n * agentcat.track(mcpServer, \"proj_abc123xyz\", {\n *   exporters: {\n *     datadog: {\n *       type: \"datadog\",\n *       apiKey: process.env.DD_API_KEY,\n *       site: \"datadoghq.com\"\n *     }\n *   }\n * });\n * ```\n */\nfunction track(\n  server: any,\n  projectId: string | null,\n  options: AgentCatOptions = {},\n): any {\n  try {\n    initDiagnostics({ projectId, disabled: options.disableDiagnostics });\n\n    // Throws the support-matrix message on unknown shapes (caught below →\n    // accurate warn + untracked return; never tells a too-new SDK to\n    // \"upgrade to v1.11+\"). On success detection is non-null by construction.\n    const validated = isCompatibleServerType(server);\n    const detection = detectServer(server)!;\n    const lowLevelServer = detection.lowLevel;\n\n    // Resolve API base URL: option > AGENTCAT_API_URL > MCPCAT_API_URL (legacy) > default\n    const apiBaseUrl =\n      options.apiBaseUrl ||\n      process.env.AGENTCAT_API_URL ||\n      process.env.MCPCAT_API_URL;\n    if (apiBaseUrl) eventQueue.configure(apiBaseUrl);\n\n    // Setup-started beacon — now carries the detection fingerprint. This\n    // line IS the fleet-level change-detection channel: writeToLog feeds the\n    // diagnostics sink (setDiagnosticsSink), so signal drift across SDK\n    // releases surfaces in the diagnostics pipeline without a separate API.\n    writeToLog(\n      `AgentCat setup started | project ${projectId || \"(telemetry-only)\"} | sdk v${detection.major}/${detection.flavor} | signals ${describeSignals(detection.signals)}`,\n    );\n\n    const existingData = getServerTrackingData(lowLevelServer);\n    if (existingData) {\n      writeToLog(\n        \"[SESSION DEBUG] track() - Server already being tracked, skipping initialization\",\n      );\n      return validated;\n    }\n\n    // First-wins: per-request factories call track() on every request;\n    // rebuilding exporters each time is waste.\n    if (options.exporters && !getTelemetryManager()) {\n      const telemetryManager = new TelemetryManager(options.exporters);\n      setTelemetryManager(telemetryManager);\n      writeToLog(\n        `Initialized telemetry with ${Object.keys(options.exporters).length} exporters`,\n      );\n    }\n\n    // If projectId is null and no exporters, warn the user\n    if (!projectId && !options.exporters) {\n      writeToLog(\n        \"Warning: No projectId provided and no exporters configured. Events will not be sent anywhere.\",\n      );\n    }\n\n    const agentcatData: AgentCatData = {\n      projectId: projectId || \"\", // Use empty string for null projectId\n      options: {\n        enableReportMissing: options.enableReportMissing ?? true,\n        enableTracing: options.enableTracing ?? true,\n        enableToolCallContext: options.enableToolCallContext ?? true,\n        customContextDescription: options.customContextDescription,\n        enableAgentTracking: options.enableAgentTracking ?? false,\n        resolveSessionId: options.resolveSessionId,\n        identify: options.identify,\n        redactSensitiveInformation: options.redactSensitiveInformation,\n        redactEvent: options.redactEvent,\n        eventTags: options.eventTags,\n        eventProperties: options.eventProperties,\n      },\n    };\n\n    setServerTrackingData(lowLevelServer, agentcatData);\n    installEngine(detection);\n\n    // Setup-completed beacon. Pairs with the start beacon: start + complete\n    // means setup succeeded; start without complete (plus an error) localizes\n    // the failure.\n    const exporterCount = options.exporters\n      ? Object.keys(options.exporters).length\n      : 0;\n    writeToLog(\n      `AgentCat setup complete | project ${projectId || \"(telemetry-only)\"} | tracing=${agentcatData.options.enableTracing} context=${agentcatData.options.enableToolCallContext} reportMissing=${agentcatData.options.enableReportMissing} exporters=${exporterCount}`,\n    );\n\n    return validated;\n  } catch (error) {\n    writeToLog(`Warning: Failed to track server - ${error}`);\n    return server;\n  }\n}\n\n/**\n * Publishes a custom event to AgentCat with flexible session management.\n *\n * @param serverOrSessionId - Either a tracked MCP server instance or a session ID string.\n *   A session ID string is used verbatim as the event's session — it is never derived or hashed.\n * @param projectId - Your AgentCat project ID (required)\n * @param eventData - Optional event data to include with the custom event. Set `eventData.sessionId`\n *   to attribute the event to a task; it takes precedence over a session ID string passed as the\n *   first argument. When a tracked server is passed without `eventData.sessionId`, the event is\n *   published without a session (the server assigns one).\n *\n * @returns Promise that resolves when the event is queued for publishing\n *\n * @remarks\n * When a tracked server is passed, the `redactEvent` hook configured via `track()`\n * is applied to the custom event before it is published. Events published with a\n * bare session ID string bypass redaction, since no tracked configuration exists.\n *\n * @example\n * ```typescript\n * // With a tracked server, attributed to a task\n * await agentcat.publishCustomEvent(\n *   server,\n *   \"proj_abc123xyz\",\n *   {\n *     sessionId: \"ses_2cOHEO0LYGADMzRvWTXXVbbgxgm\",\n *     resourceName: \"custom-action\",\n *     parameters: { action: \"user-feedback\", rating: 5 },\n *     message: \"User provided feedback\"\n *   }\n * );\n * ```\n *\n * @example\n * ```typescript\n * // With a session ID string\n * await agentcat.publishCustomEvent(\n *   \"ses_2cOHEO0LYGADMzRvWTXXVbbgxgm\",\n *   \"proj_abc123xyz\",\n *   {\n *     isError: true,\n *     error: { message: \"Custom error occurred\", code: \"ERR_001\" }\n *   }\n * );\n * ```\n *\n * @example\n * ```typescript\n * // With a tracked server and no session ID: published without a session\n * await agentcat.publishCustomEvent(\n *   server,\n *   \"proj_abc123xyz\",\n *   {\n *     resourceName: \"feature-usage\",\n *   }\n * );\n * ```\n */\nexport async function publishCustomEvent(\n  serverOrSessionId: any | string,\n  projectId: string,\n  eventData?: CustomEventData,\n): Promise<void> {\n  // Validate required parameters\n  if (!projectId) {\n    throw new Error(\"projectId is required for publishCustomEvent\");\n  }\n\n  let sessionId: string;\n\n  // Determine if the first parameter is a tracked server or a session ID string\n  const isServer =\n    typeof serverOrSessionId === \"object\" && serverOrSessionId !== null;\n  let lowLevelServer: MCPServerLike | null = null;\n\n  if (isServer) {\n    lowLevelServer = serverOrSessionId.server\n      ? serverOrSessionId.server\n      : serverOrSessionId;\n    const trackingData = getServerTrackingData(lowLevelServer as MCPServerLike);\n    if (!trackingData) {\n      throw new Error(\n        \"Server is not tracked. Please call agentcat.track() first or provide a session ID string.\",\n      );\n    }\n    if (eventData?.sessionId) {\n      sessionId = eventData.sessionId;\n    } else {\n      // Handles are per-request now; a tracked server has no ambient session ID.\n      sessionId = \"\"; // wire: null (\"stateless mode - server assigns session\")\n      writeToLog(\n        \"publishCustomEvent: no sessionId provided; event will be published without a session. Pass eventData.sessionId to attribute it to a task.\",\n      );\n    }\n  } else if (typeof serverOrSessionId === \"string\") {\n    // The string IS the session id — verbatim, no derivation.\n    sessionId = eventData?.sessionId || serverOrSessionId;\n  } else {\n    throw new Error(\n      \"First parameter must be either an MCP server object or a session ID string\",\n    );\n  }\n\n  // Build the event object\n  const event: UnredactedEvent = {\n    // Core fields\n    sessionId,\n    projectId,\n\n    // Fixed event type for custom events\n    eventType: AGENTCAT_CUSTOM_EVENT_TYPE,\n\n    // Timestamp\n    timestamp: new Date(),\n\n    // Event data from parameters\n    resourceName: eventData?.resourceName,\n    parameters: eventData?.parameters,\n    response: eventData?.response,\n    userIntent: eventData?.message,\n    duration: eventData?.duration,\n    isError: eventData?.isError,\n    error: eventData?.error,\n  };\n\n  // Wire up customer-defined metadata\n  if (eventData?.tags) {\n    event.tags = validateTags(eventData.tags);\n  }\n  if (eventData?.properties && Object.keys(eventData.properties).length > 0) {\n    event.properties = eventData.properties;\n  }\n\n  // If we have a tracked server, use the publishEvent function\n  // Otherwise, add directly to the event queue\n  if (lowLevelServer && getServerTrackingData(lowLevelServer)) {\n    publishEventToQueue(lowLevelServer, event);\n  } else {\n    // For custom sessions, we need to import and use the event queue directly\n    eventQueue.add(event);\n  }\n\n  writeToLog(\n    `Published custom event ${sessionId ? `for session ${sessionId}` : \"without a session\"} with type 'agentcat:custom'`,\n  );\n}\n\nexport type {\n  AgentCatOptions,\n  AgentCatData,\n  UserIdentity,\n  RedactFunction,\n  RedactEventFunction,\n  ExporterConfig,\n  Exporter,\n  CustomEventData,\n} from \"./types.js\";\n\nexport { AgentCatIDPrefixes } from \"./types.js\";\n\nexport type IdentifyFunction = AgentCatOptions[\"identify\"];\n\nexport { track };\n"],"mappings":";AA2BA,SAAS,eAAe,GAGtB;AACA,QAAM,UAAmC;AAAA,IACvC,eAAe,CAAC,EAAE,EAAE,UAAU,OAAO,EAAE,WAAW;AAAA,IAClD,SAAS,OAAO,EAAE,SAAS;AAAA,IAC3B,iBAAiB,OAAO,EAAE,iBAAiB;AAAA,EAC7C;AACA,QAAM,MAAM,QAAQ,gBAAgB,EAAE,SAAS;AAC/C,UAAQ,uBAAuB,OAAO,KAAK,sBAAsB;AACjE,UAAQ,wBAAwB,KAAK,4BAA4B;AACjE,UAAQ,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AACJ,UAAM,eAAe,sBAAsB,cAA+B;AAC1E,QAAI,CAAC,cAAc;AACjB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,WAAW,WAAW;AACxB,kBAAY,UAAU;AAAA,IACxB,OAAO;AAEL,kBAAY;AACZ;AAAA,QACE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,sBAAsB,UAAU;AAEhD,gBAAY,WAAW,aAAa;AAAA,EACtC,OAAO;AACL,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAGA,QAAM,QAAyB;AAAA;AAAA,IAE7B;AAAA,IACA;AAAA;AAAA,IAGA,WAAW;AAAA;AAAA,IAGX,WAAW,oBAAI,KAAK;AAAA;AAAA,IAGpB,cAAc,WAAW;AAAA,IACzB,YAAY,WAAW;AAAA,IACvB,UAAU,WAAW;AAAA,IACrB,YAAY,WAAW;AAAA,IACvB,UAAU,WAAW;AAAA,IACrB,SAAS,WAAW;AAAA,IACpB,OAAO,WAAW;AAAA,EACpB;AAGA,MAAI,WAAW,MAAM;AACnB,UAAM,OAAO,aAAa,UAAU,IAAI;AAAA,EAC1C;AACA,MAAI,WAAW,cAAc,OAAO,KAAK,UAAU,UAAU,EAAE,SAAS,GAAG;AACzE,UAAM,aAAa,UAAU;AAAA,EAC/B;AAIA,MAAI,kBAAkB,sBAAsB,cAAc,GAAG;AAC3D,iBAAoB,gBAAgB,KAAK;AAAA,EAC3C,OAAO;AAEL,eAAW,IAAI,KAAK;AAAA,EACtB;AAEA;AAAA,IACE,0BAA0B,YAAY,eAAe,SAAS,KAAK,mBAAmB;AAAA,EACxF;AACF;","names":["createRequire","require","createRequire","buffer","buffer","PublishEventRequestEventTypeEnum","maxLength","createRequire","fsModule","require","MAX_STACK_FRAMES","parsedLocation","resolution","clientInfo","event","PublishEventRequestEventTypeEnum","createHash","randomBytes","attr","createHash","PublishEventRequestEventTypeEnum","createHash","PublishEventRequestEventTypeEnum","AgentCatIDPrefixes"]}