@copilotkit/runtime 1.64.2-canary.1785346263 → 1.64.2-canary.1785375021
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/package.cjs +1 -1
- package/dist/runtime/package.mjs +1 -1
- package/dist/v2/runtime/core/channel-activation-config.cjs +3 -1
- package/dist/v2/runtime/core/channel-activation-config.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.cts +6 -0
- package/dist/v2/runtime/core/channel-activation-config.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.mts +6 -0
- package/dist/v2/runtime/core/channel-activation-config.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-activation-config.mjs +3 -1
- package/dist/v2/runtime/core/channel-activation-config.mjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.cjs +209 -6
- package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.cts +6 -1
- package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.mts +6 -1
- package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.mjs +209 -6
- package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.cjs +15 -0
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +16 -1
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.cjs +1 -0
- package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.mjs +1 -0
- package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
- package/dist/v2/runtime/core/hooks.cjs.map +1 -1
- package/dist/v2/runtime/core/hooks.d.cts +2 -0
- package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
- package/dist/v2/runtime/core/hooks.d.mts +2 -0
- package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
- package/dist/v2/runtime/core/hooks.mjs.map +1 -1
- package/dist/v2/runtime/core/runtime.cjs +4 -0
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +24 -0
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +24 -0
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +4 -0
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.cjs +63 -1
- package/dist/v2/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/memories.mjs +63 -2
- package/dist/v2/runtime/handlers/intelligence/memories.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +17 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +31 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +31 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +17 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.cts +2 -0
- package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.mts +2 -0
- package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.cjs +2 -5
- package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.mjs +2 -5
- package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.cjs +36 -31
- package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.mjs +36 -31
- package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-manager.mjs","names":[],"sources":["../../../../src/v2/runtime/core/channel-manager.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n ChannelConfigError,\n deriveChannelActivationConfig,\n} from \"./channel-activation-config\";\nimport type { ChannelActivationConfig } from \"./channel-activation-config\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\n// Type-only: @copilotkit/channels is pure-ESM, so a value import would break this\n// package's CJS output (see `core/runtime.ts` and `channel-activation-config.ts`\n// for the same constraint).\nimport type { Channel } from \"@copilotkit/channels\";\n\n/**\n * Lifecycle status of a single Channel activation, or of the manager overall.\n *\n * - `connecting`: activation in flight, not yet settled.\n * - `online`: activation resolved AND the managed session can currently send.\n * A drop moves the Channel to `reconnecting` (not `online`); a successful\n * rejoin restores `online`.\n * - `setup_required`: the Channel is declared but has no managed provider yet —\n * a valid degraded state, not a failure.\n * - `reconnecting`: the managed session dropped and Phoenix is retrying — not\n * currently sendable. The manager does NOT re-activate (reconnection is\n * delegated to the Phoenix connection layer); it only reflects the health the\n * session reports via its `onStateChange` observer.\n * - `stopped`: {@link ChannelManager.stop} has torn the Channel down.\n * - `error`: activation rejected with a non-setup error, OR a previously-online\n * session gave up reconnecting after its bounded reconnect window or was\n * generation-fenced by a replacement.\n *\n * Both MANAGED (Intelligence-gateway) and DIRECT (developer-supplied adapter)\n * Channels move through these states. A direct Channel is driven by the manager\n * too — it is started via {@link Channel.ɵruntime}`.start()` and reaches `online`\n * once its own transport is up — but it is NOT wired into the Intelligence\n * gateway/canonical/reliability layer: it simply runs its own adapter transport,\n * started and stopped by the manager. A direct Channel has no managed-session\n * drop signal, so it never reports `reconnecting`.\n *\n * That gap is BY DESIGN, not a deferral. Run-correctness (canonical\n * cross-surface history, fenced outer-run/single-terminal, durable\n * HITL-resume-across-restart, selection pinning) and the reliability layer are\n * Intelligence-side only — see OSS-599's boundary discipline. A direct Channel's\n * ceiling is the SDK's in-process run loop. Do not \"finish\" this by pulling the\n * canonical/reliability layer down into the SDK: that is explicitly the thing\n * OSS-599 forbids.\n */\nexport type ChannelStatus =\n | \"connecting\"\n | \"online\"\n | \"setup_required\"\n | \"reconnecting\"\n | \"stopped\"\n | \"error\";\n\n/**\n * The lifecycle control surface a Channel host uses to drive and observe\n * managed Channel activation.\n */\nexport interface ChannelsControl {\n /**\n * Resolve once every declared Channel has settled to a terminal, non-connecting\n * state (`online` or `setup_required`). Rejects if any Channel is in `error`,\n * or — when `timeoutMs` is given — if the whole set has not settled in time.\n */\n ready(opts?: { timeoutMs?: number }): Promise<void>;\n /** Snapshot the overall status and the per-Channel status map. */\n status(): { overall: ChannelStatus; channels: Record<string, ChannelStatus> };\n /** Tear down every activated Channel. Idempotent. */\n stop(): Promise<void>;\n}\n\n/**\n * Signals that a declared Channel cannot be activated because no managed\n * provider exists for it yet. The engine throws this (or any error whose\n * `code === \"SETUP_REQUIRED\"`) to move a Channel to `setup_required` rather\n * than `error` — a declared-but-unprovisioned Channel is a valid degraded\n * state, not a failure.\n */\nexport class ChannelSetupRequiredError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ChannelSetupRequiredError\";\n }\n}\n\n/**\n * The activation engine: given a resolved {@link ChannelActivationConfig} and\n * the declared {@link Channel}, bring the Channel online and return its handle.\n * Injected in tests (a fake engine); defaults to the Realtime Gateway launcher.\n */\nexport type ActivateChannelEngine = (\n config: ChannelActivationConfig,\n channel: Channel,\n) => Promise<ChannelsHandle>;\n\n/**\n * Minimal structural view of the `@copilotkit/channels-intelligence`\n * `ChannelsHandle`. Declared locally (not imported) because the runtime is a\n * CJS package that must not take a static dependency on the pure-ESM\n * channels-intelligence package — the default engine reaches its launcher\n * through a dynamic `import()` instead. The manager only ever needs `stop()`.\n */\nexport interface ChannelsHandle {\n /** Activation metadata declared to Intelligence. Unused by the manager. */\n metadata: unknown;\n /** Stop the underlying Channel(s) and release transports. */\n stop(): Promise<void>;\n /**\n * Optional seam: register a callback the handle fires when its managed\n * session drops. Retained as a per-episode drop breadcrumb; the manager drives\n * status from {@link ChannelsHandle.onStateChange} instead. Present on the\n * Realtime Gateway launcher handle; optional for non-gateway/test handles.\n */\n onClose?(cb: () => void): void;\n /**\n * Optional seam: register a connection-health observer the handle fires as its\n * managed session moves between `online` (sendable), `reconnecting` (dropped,\n * Phoenix retrying), and `gave_up` (dead after the bounded reconnect window).\n * The manager uses this to keep {@link ChannelManager.status} honest — it does\n * NOT re-activate on a drop (reconnection is delegated to the Phoenix\n * connection layer; see {@link ChannelManager}). Optional so non-gateway or\n * test handles that do not implement it are always invoked as\n * `handle.onStateChange?.(cb)`.\n */\n onStateChange?(\n cb: (state: \"online\" | \"reconnecting\" | \"gave_up\" | \"fenced\") => void,\n ): void;\n}\n\n/** Constructor arguments for {@link ChannelManager}. */\nexport interface ChannelManagerArgs {\n /** The Intelligence runtime client the activation config is derived from. */\n intelligence: CopilotKitIntelligence;\n /** The declared framework Channels to activate. */\n channels: Channel[];\n /**\n * Activation engine. Defaults to a wrapper over the channels-intelligence\n * Realtime Gateway launcher (`startChannelsOverRealtimeGateway`), reached via\n * dynamic import so this CJS package keeps no static ESM dependency.\n */\n activateChannel?: ActivateChannelEngine;\n /** Mint a runtime instance id per Channel. Defaults to `rti_{uuid-no-dashes}`. */\n mintRuntimeInstanceId?: () => string;\n /** Diagnostic sink. Forwarded to the launcher/transport when the default\n * activation engine is used, so transport-level drops surface in the managed\n * path (not just activation-level events). */\n log?: (msg: string, meta?: unknown) => void;\n /** Per-handle deadline (ms) for `handle.stop()` during {@link ChannelManager.stop}\n * so a wedged stop can't hang SIGTERM shutdown. Default 5000. */\n stopHandleTimeoutMs?: number;\n}\n\n/** Per-Channel mutable activation entry tracked by the manager. */\ninterface ChannelEntry {\n status: ChannelStatus;\n /** Resolves on `online`/`setup_required`; rejects on `error`. Awaited by `ready`. */\n readonly settled: Promise<void>;\n handle?: ChannelsHandle;\n /**\n * Whether {@link ChannelManager.stopEntry} has already stopped `handle`. Gates\n * the single-stop guarantee: the success settle handler and `stop()` can both\n * reach the same entry in the same tick, but the handle is torn down at most\n * once.\n */\n handleStopped: boolean;\n}\n\n/**\n * Runtime installs this pure-ESM package as a direct dependency, but the\n * specifier must stay non-literal so it never becomes a static dependency of\n * the runtime's CJS build. The packed-consumer contract is enforced by\n * `scripts/release/verify-runtime-package.ts`.\n */\nconst CHANNELS_INTELLIGENCE_SPECIFIER = \"@copilotkit/channels-intelligence\";\n\n/**\n * Structural view of the `@copilotkit/channels-intelligence` module surface the\n * default engine consumes. Declared locally (not imported) for the same\n * CJS/ESM-boundary reason the {@link ChannelsHandle} view is.\n */\nexport interface ChannelsIntelligenceModule {\n startChannelsOverRealtimeGateway: (\n channels: Channel[],\n opts: {\n wsUrl: string;\n apiKey: string;\n scope: { projectId: number; channelName: string };\n runtimeInstanceId: string;\n adapter?: string;\n /** Intelligence app-api HTTP base URL, forwarded to the transport so the\n * managed realtime path enables file/history parity (HTTP-only) — OSS-476. */\n appApiBaseUrl?: string;\n /** Diagnostic sink forwarded to the launcher/transport so transport-level\n * drop diagnostics (e.g. a version-skew missing-leaseToken outage) are not\n * silent in the managed path. */\n log?: (msg: string, meta?: unknown) => void;\n },\n ) => Promise<ChannelsHandle>;\n}\n\n/**\n * Default engine: wrap the channels-intelligence Realtime Gateway launcher.\n *\n * The module is reached through an injectable importer that defaults to a\n * dynamic `import()` of a non-literal specifier, so the pure-ESM\n * `@copilotkit/channels-intelligence` never becomes a static dependency of this\n * CJS package (mirrors the runtime's other channels seams). The `import`\n * seam is a parameter purely so this function's config→opts mapping and its\n * module-not-found / generic-error branches are unit-testable WITHOUT the real\n * package installed; production always uses the default importer.\n *\n * Passes NO `org`/`channelId` — the launcher's realtime scope treats them as\n * optional.\n *\n * @param config - Resolved activation config for the Channel.\n * @param channel - The Channel to activate.\n * @param importChannelsIntelligence - Test seam; loads the channels-intelligence\n * module. Defaults to a dynamic import of the real package.\n * @param log - Optional diagnostic sink forwarded to the launcher/transport so\n * transport-level drop diagnostics are not silent in the managed path.\n * @returns The launcher's {@link ChannelsHandle}.\n */\nexport async function defaultActivateChannel(\n config: ChannelActivationConfig,\n channel: Channel,\n importChannelsIntelligence: () => Promise<ChannelsIntelligenceModule> = () =>\n import(\n CHANNELS_INTELLIGENCE_SPECIFIER\n ) as Promise<ChannelsIntelligenceModule>,\n log?: (msg: string, meta?: unknown) => void,\n): Promise<ChannelsHandle> {\n let mod: ChannelsIntelligenceModule;\n try {\n mod = await importChannelsIntelligence();\n } catch (err) {\n if (isModuleNotFound(err)) {\n throw new Error(\n \"Managed Channels require '@copilotkit/channels-intelligence' to be installed. Add it to your app's dependencies.\",\n { cause: err },\n );\n }\n throw err;\n }\n return mod.startChannelsOverRealtimeGateway([channel], {\n wsUrl: config.wsUrl,\n apiKey: config.apiKey,\n scope: { projectId: config.projectId, channelName: config.channelName },\n runtimeInstanceId: config.runtimeInstanceId,\n adapter: config.adapter,\n // Forward the app-api HTTP base URL so the transport wires file/history\n // (HTTP-only) on the NORMAL managed path — without this, Channels started by\n // the CopilotRuntime handler run with no history/file support (OSS-476).\n appApiBaseUrl: config.apiUrl,\n // Forward the manager's diagnostic sink down to the launcher/transport so a\n // transport-level drop (e.g. a version-skew missing-leaseToken outage) is\n // observable in the managed path, not just activation-level events.\n ...(log ? { log } : {}),\n });\n}\n\n/** Whether `err` signals a missing managed provider rather than a hard failure. */\nfunction isSetupRequired(err: unknown): boolean {\n return (\n err instanceof ChannelSetupRequiredError ||\n (typeof err === \"object\" &&\n err !== null &&\n (err as { code?: unknown }).code === \"SETUP_REQUIRED\")\n );\n}\n\n/**\n * Whether `err` is a Node/runtime module-resolution failure — i.e. the error\n * a dynamic `import()` throws when the target package is not installed.\n * Exported so the friendly-error path in {@link defaultActivateChannel} can be\n * unit-tested without forcing a real failing import.\n */\nexport function isModuleNotFound(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) {\n return false;\n }\n const code = (err as { code?: unknown }).code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\n/** Default deadline (ms) for a single `handle.stop()` during teardown. */\nconst DEFAULT_STOP_HANDLE_TIMEOUT_MS = 5_000;\n\n/**\n * Reject with `timeoutMessage` after `timeoutMs` if `inner` has not settled,\n * otherwise pass `inner` through. When `timeoutMs` is undefined, `inner` is\n * returned unchanged. The timer is `unref`'d so a pending deadline never keeps\n * the process alive, and `inner` always has a settle handler attached, so a\n * timed-out promise that later settles never surfaces as unhandled.\n */\nfunction withTimeout<T>(\n inner: Promise<T>,\n timeoutMs: number | undefined,\n timeoutMessage: string,\n): Promise<T> {\n if (timeoutMs === undefined) {\n return inner;\n }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(timeoutMessage)),\n timeoutMs,\n );\n (timer as unknown as { unref?: () => void }).unref?.();\n inner.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\n/**\n * Drives Channel activation for an Intelligence runtime: lazily activates each\n * declared Channel, tracks per-Channel lifecycle status, exposes readiness, and\n * tears everything down. A MANAGED Channel (empty `adapters`) is activated\n * through the injected engine over the Intelligence gateway; a DIRECT Channel\n * (developer-supplied adapter) is started through its own transport seam\n * (`channel.ɵruntime.start()`) — driven by the manager, but running only its own\n * adapter transport, not the gateway path (direct Channels stay below the\n * canonical/reliability layer by design — see {@link ChannelStatus} and OSS-599).\n * Its very existence means Intelligence is configured, so there is no\n * standalone/self-started path.\n *\n * Activation is lazy and idempotent — constructing the manager does nothing;\n * {@link activate} starts it and a second call is a no-op. Activation throws\n * SYNCHRONOUSLY (a {@link ChannelConfigError}) only for a misconfiguration it\n * can detect up front — a duplicate or missing Channel name. Every OTHER\n * activation failure is recorded as the Channel's status (`error`, or\n * `setup_required` for a missing provider) and surfaced through {@link status}\n * and {@link ready} rather than thrown.\n *\n * Reconnection is NOT handled here — it is delegated to the Phoenix connection\n * layer that backs the launcher. When a managed socket drops, Phoenix's `Socket`\n * auto-reconnects and auto-rejoins, re-sending the channel's join declaration;\n * the Intelligence gateway's `join/3` re-runs `record_heartbeat` (re-registering\n * the runtime's listener) and its `terminate/2` releases the dead socket's\n * leases (verified against Intelligence #511 `sdk_channel.ex`). So the transport\n * self-heals under the persistent adapter and a re-activation here would be both\n * redundant AND broken: re-invoking the engine on an already-started `Channel`\n * throws in `channel.addAdapter` (started=true). The manager therefore never\n * re-activates on a drop.\n *\n * It DOES, however, reflect real connection health through the session's\n * `onStateChange` observer so {@link ChannelManager.status} stays honest rather\n * than reporting `online` forever after a drop: a drop moves the Channel to\n * `reconnecting`, a successful rejoin restores `online`, and a bounded give-up\n * (Phoenix would otherwise retry forever) moves it to `error`.\n */\nexport class ChannelManager implements ChannelsControl {\n private readonly intelligence: CopilotKitIntelligence;\n private readonly channels: Channel[];\n private readonly activateChannel: ActivateChannelEngine;\n private readonly mintRuntimeInstanceId: () => string;\n private readonly log?: (msg: string, meta?: unknown) => void;\n private readonly stopHandleTimeoutMs: number;\n\n private readonly entries = new Map<string, ChannelEntry>();\n private activated = false;\n private stopped = false;\n\n /** @param args - See {@link ChannelManagerArgs}. */\n constructor(args: ChannelManagerArgs) {\n this.intelligence = args.intelligence;\n this.channels = args.channels;\n this.log = args.log;\n // When using the default engine, forward the manager's log DOWN to the\n // launcher/transport (via defaultActivateChannel's log param) so a\n // transport-level drop is observable in the managed path. `this.log` is read\n // lazily at activation time, so this closure always sees the assigned sink.\n this.activateChannel =\n args.activateChannel ??\n ((config, channel) =>\n defaultActivateChannel(config, channel, undefined, this.log));\n this.mintRuntimeInstanceId =\n args.mintRuntimeInstanceId ??\n (() => `rti_${randomUUID().replace(/-/g, \"\")}`);\n this.stopHandleTimeoutMs =\n args.stopHandleTimeoutMs ?? DEFAULT_STOP_HANDLE_TIMEOUT_MS;\n }\n\n /**\n * Start activation of every declared Channel (lazy + idempotent). Mints a\n * distinct runtime instance id per Channel, derives its activation config,\n * and calls the engine. Records each Channel as `connecting`, transitioning\n * to `online`/`setup_required`/`error` as its activation settles.\n */\n activate(): void {\n // Short-circuit on BOTH latches: `activated` makes activation idempotent,\n // and `stopped` prevents a post-`stop()` activate() from opening transports\n // on a dead manager. (A late activation self-heals via the post-settle guard,\n // but never starting it is cheaper and clearer.)\n if (this.activated || this.stopped) {\n return;\n }\n // Reject duplicate Channel names BEFORE kicking off any engine call. The\n // manager keys `entries` by name, so a duplicate would let the second\n // activation's entry silently overwrite the first — leaking the first\n // Channel's live session out of status()/ready()/stop(). Fail loud here so\n // nothing is ever activated in that state.\n this.assertUniqueChannelNames();\n this.activated = true;\n\n // Partition declared Channels by transport. A Channel carrying ANY adapter\n // that is NOT the Intelligence managed adapter (a developer-supplied\n // slack/discord/... adapter, which lacks `__intelligenceChannel`) is a\n // DIRECT channel. The manager still owns its lifecycle — but a direct Channel\n // runs its OWN adapter transport rather than the Intelligence gateway path:\n // it is started here via `channel.ɵruntime.start()` (not the managed engine)\n // and torn down via `channel.ɵruntime.stop()`. The distinction is EXCLUSIVE\n // PER CHANNEL, not per platform — a Channel served by a direct adapter is not\n // also managed: ANY direct adapter makes the WHOLE Channel direct, regardless\n // of platform. Attaching the managed adapter alongside a direct one would\n // double-deliver every turn (and trip the SDK's `assertExclusive` guard,\n // moving the Channel to `error`). Per the SoT rule, never infer managed intent\n // from a local direct adapter — a managed-eligible Channel has an empty\n // `adapters` at declaration time. Managed+direct coexistence on the same\n // Channel is NOT supported today; it is deferred (OSS-484). Direct Channels\n // run only their own transport here and stay below the Intelligence\n // canonical/reliability layer by design, not pending work (OSS-599).\n for (const channel of this.channels) {\n const isDirect = channel.adapters.some((a) => !a.__intelligenceChannel);\n if (isDirect) {\n this.startDirectChannel(channel);\n continue;\n }\n const name = channel.name!;\n const runtimeInstanceId = this.mintRuntimeInstanceId();\n\n let resolveSettled!: () => void;\n let rejectSettled!: (err: unknown) => void;\n const settled = new Promise<void>((resolve, reject) => {\n resolveSettled = resolve;\n rejectSettled = reject;\n });\n // ready() awaits `settled`; if nothing ever handles a rejection there,\n // Node reports an unhandled rejection. Attach a no-op catch so the\n // promise is always considered handled — ready() still sees the reason.\n settled.catch(() => {});\n\n // Invoke the engine synchronously so activation is observably started the\n // moment activate() returns (callers assert the engine was called and see\n // `connecting` before awaiting ready). A synchronous config/engine throw is\n // turned into a rejected activation so it becomes this channel's status\n // rather than throwing out of activate().\n let activation: Promise<ChannelsHandle>;\n let config: ChannelActivationConfig | undefined;\n try {\n config = deriveChannelActivationConfig({\n intelligence: this.intelligence,\n channel,\n runtimeInstanceId,\n });\n activation = this.activateChannel(config, channel);\n } catch (err) {\n activation = Promise.reject(err);\n }\n\n // The deferred `.then` callbacks capture `entry` and run only after the\n // literal has fully initialized, so referencing it here is safe.\n const entry: ChannelEntry = {\n status: \"connecting\",\n handle: undefined,\n handleStopped: false,\n settled,\n };\n\n // Anchor the settle handlers. Both branches route every teardown through\n // the idempotent `stopEntry`, so a late settle can never resurrect a\n // `stopped` entry and a handle is torn down at most once. The handlers\n // only mutate state (never throw), so the trailing no-op catch just keeps\n // the chain from surfacing as an unhandled rejection.\n activation\n .then(\n async (handle) => {\n entry.handle = handle;\n if (this.stopped) {\n // stop() ran before this activation settled, so it could not tear\n // down a handle that did not exist yet. Release it now (idempotent)\n // and keep the Channel `stopped`.\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n entry.status = \"online\";\n this.registerConnectionObserver(name, entry);\n resolveSettled();\n },\n async (err: unknown) => {\n if (this.stopped) {\n // A rejection that arrives AFTER stop() must NOT resurrect the\n // entry into `error`/`setup_required`: the Channel is already\n // being torn down. Keep it `stopped` and resolve `settled` so a\n // subsequent ready() does not reject on a stopped Channel.\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n if (isSetupRequired(err)) {\n entry.status = \"setup_required\";\n this.log?.(`channel \"${name}\" requires setup`, err);\n resolveSettled();\n } else {\n entry.status = \"error\";\n this.log?.(`channel \"${name}\" failed to activate`, err);\n rejectSettled(err);\n }\n },\n )\n .catch(() => {});\n\n this.entries.set(name, entry);\n }\n }\n\n /**\n * Start a DIRECT-adapter Channel through its own transport seam\n * ({@link Channel.ɵruntime}`.start()`), recording a live entry so\n * {@link ready}/{@link status}/{@link stop} all cover it. A direct Channel is\n * driven by the manager — but only because the Intelligence runtime constructed\n * this manager at all — and runs its OWN adapter transport, NOT the Intelligence\n * gateway path. It is deliberately NOT wired into the gateway/canonical/\n * reliability layer — that boundary is permanent, not a deferral (OSS-599).\n *\n * Mirrors the managed path's settle machinery so teardown resilience is shared:\n * the entry's `handle` is a synthetic {@link ChannelsHandle} whose `stop()`\n * calls `channel.ɵruntime.stop()`, so the SAME idempotent, bounded, resilient\n * {@link stopEntry} that tears down a managed handle tears down a direct Channel\n * too. The handle is assigned only AFTER `start()` resolves (exactly as the\n * managed path assigns its handle only on resolve), so a `stop()` during a\n * still-starting direct Channel returns promptly with nothing to stop and the\n * post-settle guard tears down the late transport. A direct Channel exposes no\n * managed-session drop signal, so no connection observer is wired and it never\n * reaches `reconnecting`.\n *\n * @param channel - The direct-adapter Channel to start.\n */\n private startDirectChannel(channel: Channel): void {\n const name = channel.name!;\n this.log?.(\n `channel \"${name}\" carries a direct adapter — starting its own transport via channel.ɵruntime.start() (the Intelligence runtime drives its lifecycle; it runs its own adapter transport, NOT the managed gateway path — direct Channels stay below the canonical/reliability layer by design (OSS-599); managed+direct coexistence deferred (OSS-484))`,\n );\n\n let resolveSettled!: () => void;\n let rejectSettled!: (err: unknown) => void;\n const settled = new Promise<void>((resolve, reject) => {\n resolveSettled = resolve;\n rejectSettled = reject;\n });\n // ready() awaits `settled`; attach a no-op catch so a rejection is always\n // considered handled (ready() still sees the reason).\n settled.catch(() => {});\n\n // Synthetic handle wrapping the Channel's own stop seam. Assigned to the\n // entry only on successful start (below) so the shared teardown machinery\n // (handleStopped guard, withTimeout bounding, resilient allSettled) stops a\n // direct Channel exactly as it stops a managed handle.\n const directHandle: ChannelsHandle = {\n metadata: {},\n stop: () => channel.ɵruntime.stop(),\n };\n\n // Start the direct transport synchronously so it is observably started the\n // moment activate() returns (callers see `connecting` before awaiting ready).\n // A synchronous throw becomes this Channel's status rather than throwing out\n // of activate().\n let activation: Promise<void>;\n try {\n activation = channel.ɵruntime.start();\n } catch (err) {\n activation = Promise.reject(err);\n }\n\n const entry: ChannelEntry = {\n status: \"connecting\",\n handle: undefined,\n handleStopped: false,\n settled,\n };\n\n activation\n .then(\n async () => {\n entry.handle = directHandle;\n if (this.stopped) {\n // stop() ran before start() settled, so it could not tear down a\n // transport that was not up yet. Release it now (idempotent) and keep\n // the Channel `stopped`.\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n entry.status = \"online\";\n resolveSettled();\n },\n async (err: unknown) => {\n if (this.stopped) {\n // A start rejection that arrives AFTER stop() must NOT resurrect the\n // entry into `error`: the Channel is already being torn down. Keep it\n // `stopped` and resolve `settled` so a later ready() does not reject.\n entry.handle = directHandle;\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n entry.status = \"error\";\n this.log?.(\n `channel \"${name}\" failed to start its direct transport`,\n err,\n );\n rejectSettled(err);\n },\n )\n .catch(() => {});\n\n this.entries.set(name, entry);\n }\n\n /**\n * Throw if two declared Channels share a `name`. `entries` is keyed by name,\n * so a duplicate would overwrite the first Channel's entry and leak its live\n * session. Called at the very start of {@link activate}, before any engine\n * call, so a misconfiguration fails loud instead of silently.\n *\n * @throws {ChannelConfigError} If any Channel is missing a name, or if any\n * name appears more than once.\n */\n private assertUniqueChannelNames(): void {\n const seen = new Set<string>();\n for (const channel of this.channels) {\n const name = channel.name;\n // Check for a missing/empty name FIRST: `channel.name!` on a nameless\n // Channel keys as the string \"undefined\", which would otherwise report a\n // spurious duplicate for two nameless Channels before the accurate\n // missing-name error. Fail with the precise error instead.\n if (!name) {\n throw new ChannelConfigError(\n \"A managed Channel is missing a `name` — every declared Channel must \" +\n \"have a unique, non-empty name (pass createChannel({ name })).\",\n );\n }\n if (seen.has(name)) {\n throw new ChannelConfigError(\n `Duplicate managed Channel name \"${name}\" — every declared Channel ` +\n `must have a unique name.`,\n );\n }\n seen.add(name);\n }\n }\n\n /**\n * Resolve when every declared Channel — managed OR direct — has settled to\n * `online`/`setup_required`.\n *\n * A direct-adapter Channel is awaited too: its `settled` resolves once its own\n * transport is up (`channel.ɵruntime.start()` settling) and rejects if that\n * start fails, exactly as a managed Channel's `settled` tracks its activation.\n *\n * Activates lazily if not already started — so a first call rejects with the\n * same {@link ChannelConfigError} as the synchronous throw from\n * {@link activate} for an up-front misconfiguration (duplicate/missing Channel\n * names). Once activation has been kicked off, all OTHER failures are surfaced\n * here instead: this rejects with an `AggregateError` if any Channel settled\n * to `error` OR — when `timeoutMs` is given — did not settle in time. The\n * `timeoutMs` deadline is applied PER CHANNEL, so the aggregate carries each\n * failed Channel's real reason AND a named timeout for each Channel still\n * hanging: a genuine activation error is never masked by a sibling that hangs\n * (a pre-fix set-wide timeout discarded the real reason in that case).\n *\n * A STOPPED manager short-circuits and resolves: a Channel that settled to\n * `error` BEFORE {@link stop} already rejected its `settled` promise, so\n * awaiting it here would throw an `AggregateError` even though\n * {@link status}.overall is `\"stopped\"` — inconsistent with the case where the\n * Channel was still online at stop() (which resolves). A stopped manager has\n * nothing left to be ready for, so resolve uniformly.\n *\n * `ready()` is ONE-SHOT: it settles on the INITIAL activation outcome. Later\n * connection-health transitions (a live Channel dropping to `reconnecting`, or\n * giving up to `error`) are reported through {@link status} — where `online`\n * means currently-sendable — but do NOT re-arm or re-reject an already-settled\n * `ready()`.\n */\n async ready(opts?: { timeoutMs?: number }): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.activate();\n const entries = [...this.entries.entries()];\n // Apply `timeoutMs` PER CHANNEL rather than to the whole set. A single\n // set-wide timeout wrapping `allSettled` would, when one channel settles to\n // `error` while a sibling hangs, reject with only a generic timeout and\n // DISCARD the erroring channel's real reason. Timing out each channel's\n // `settled` independently lets `allSettled` collect BOTH a hung channel's\n // named timeout AND a failed channel's real error into one AggregateError.\n const results = await Promise.allSettled(\n entries.map(([name, e]) =>\n withTimeout(\n e.settled,\n opts?.timeoutMs,\n `channel \"${name}\" did not settle within ${opts?.timeoutMs}ms`,\n ),\n ),\n );\n const errors = results\n .filter((r): r is PromiseRejectedResult => r.status === \"rejected\")\n .map((r) => r.reason);\n if (errors.length > 0) {\n throw new AggregateError(\n errors,\n `ChannelManager.ready: ${errors.length} channel(s) failed to activate or settle in time`,\n );\n }\n }\n\n /**\n * Snapshot status. Every declared Channel — managed OR direct — appears keyed\n * by name in `channels`; a direct-adapter Channel reads `online` once its own\n * transport is up, exactly like a managed one.\n *\n * `overall` is folded over ALL declared Channels (see {@link computeOverall}),\n * by precedence `error` > `reconnecting` > `setup_required` > `connecting` >\n * `online`. `online` means every Channel can currently send. `reconnecting`\n * outranks `setup_required` because a dropped-but-retrying Channel is an active\n * outage, louder than a steadily-degraded unprovisioned one (only managed\n * Channels ever reach `reconnecting`; a direct Channel has no managed-session\n * drop signal). With no declared Channels at all, `overall` is `online` (nothing\n * is degraded); once every Channel has been stopped, `overall` is `stopped`.\n */\n status(): {\n overall: ChannelStatus;\n channels: Record<string, ChannelStatus>;\n } {\n const channels: Record<string, ChannelStatus> = {};\n for (const [name, entry] of this.entries) {\n channels[name] = entry.status;\n }\n // A stopped manager is `stopped` regardless of whether it was ever activated.\n // stop() before activate() (e.g. SIGTERM during startup) leaves `entries`\n // empty, and the empty-set fold below returns `online` — a torn-down manager\n // must never read healthy. Short-circuit before that fold. (After a normal\n // activate→stop, every entry is already `stopped` and the fold agrees, so\n // this is also consistent with the populated case.)\n if (this.stopped) {\n return { overall: \"stopped\", channels };\n }\n // Before activate() has run, `entries` is empty. Folding an empty set gives\n // `online` — correct for a manager that declares NO channels (nothing is\n // degraded), but a LIE for one that declares channels and simply has not\n // opened its socket yet: activation is lazy (deferred to the first\n // `ready()`), so a not-yet-activated manager must never read `online`.\n // Report `connecting` (\"not started\") for that case so `status()` is honest\n // before any `ready()`.\n if (!this.activated && this.channels.length > 0) {\n return { overall: \"connecting\", channels };\n }\n return { overall: this.computeOverall(Object.values(channels)), channels };\n }\n\n /**\n * Fold per-Channel statuses into a single overall status (see {@link status}).\n *\n * Every declared Channel — managed OR direct — participates: a started direct\n * Channel reads `online` and counts toward health exactly like a managed one,\n * and its `error` is a real outage that must dominate. Statuses are ranked\n * `error` > `reconnecting` > `setup_required` > `connecting` > `online`, so a\n * genuine failure still dominates a healthy sibling. (Only managed Channels ever\n * reach `reconnecting`; a direct Channel has no managed-session drop signal.)\n * The empty-input case (no declared Channels at all) stays `online` (nothing is\n * degraded).\n */\n private computeOverall(values: ChannelStatus[]): ChannelStatus {\n if (values.length === 0) {\n return \"online\";\n }\n if (values.every((v) => v === \"stopped\")) {\n return \"stopped\";\n }\n if (values.includes(\"error\")) {\n return \"error\";\n }\n if (values.includes(\"reconnecting\")) {\n return \"reconnecting\";\n }\n if (values.includes(\"setup_required\")) {\n return \"setup_required\";\n }\n if (values.includes(\"connecting\")) {\n return \"connecting\";\n }\n return \"online\";\n }\n\n /**\n * Wire the Channel's connection-health observer (if the handle exposes the\n * optional `onStateChange` seam) so {@link ChannelManager.status} reflects real\n * health instead of reporting `online` forever after a drop:\n *\n * - `reconnecting` → status `reconnecting` (dropped, Phoenix retrying);\n * - `online` → status `online` (rejoined, sendable again);\n * - `gave_up` → status `error` (dead after the bounded reconnect window);\n * - `fenced` → status `error` immediately (another activation superseded it).\n *\n * Makes NO re-activation — reconnection is delegated to the Phoenix connection\n * layer (see {@link ChannelManager}), which auto-rejoins under the persistent\n * adapter. A STOPPED manager (or an already-stopped entry) ignores late\n * connection events, so a drop that fires after {@link ChannelManager.stop}\n * never resurrects the Channel out of `stopped`.\n *\n * @param name - The Channel name (map key).\n * @param entry - The Channel's activation entry.\n */\n private registerConnectionObserver(name: string, entry: ChannelEntry): void {\n entry.handle?.onStateChange?.((state) => {\n // A stopped manager (or a stopped entry) ignores late connection events.\n if (this.stopped || entry.status === \"stopped\") {\n return;\n }\n if (state === \"reconnecting\") {\n entry.status = \"reconnecting\";\n this.log?.(\n `channel \"${name}\" managed session dropped; reconnecting (Phoenix auto-rejoin)`,\n );\n } else if (state === \"online\") {\n entry.status = \"online\";\n this.log?.(`channel \"${name}\" managed session back online`);\n } else if (state === \"gave_up\") {\n entry.status = \"error\";\n this.log?.(\n `channel \"${name}\" managed session gave up reconnecting; marking error`,\n );\n } else {\n entry.status = \"error\";\n this.log?.(\n `channel \"${name}\" managed session was generation-fenced by a replacement; marking error`,\n );\n }\n });\n }\n\n /**\n * Drive a single entry to its terminal `stopped` state, tearing down its\n * handle AT MOST ONCE. Idempotent: it always sets `status = \"stopped\"`, and\n * only calls `handle.stop()` on the first invocation that sees a live,\n * not-yet-stopped handle (gated by {@link ChannelEntry.handleStopped}).\n *\n * This is the ONE guarded teardown path shared by both `stop()` and the\n * post-settle guard in {@link activate}/{@link startDirectChannel}. Because the\n * guard is per-entry and idempotent, a handle assigned in the same tick as\n * `stop()` is stopped exactly once even when both callers reach the entry, and a\n * late settle can never resurrect a `stopped` entry. It is transport-agnostic: a\n * managed entry's `handle.stop()` releases the gateway session, and a direct\n * entry's synthetic handle (assigned in {@link startDirectChannel}) routes the\n * same `handle.stop()` to `channel.ɵruntime.stop()` — so direct and managed\n * Channels share one bounded, resilient teardown.\n *\n * `handle.stop()` failures are logged (via {@link ChannelManager.log}) but NOT\n * rethrown: the real launcher's `stop()` rethrows after `session.disconnect()`,\n * and teardown must still complete for every other entry. The call is wrapped\n * in `Promise.resolve().then(...)` so a foreign/injected handle whose `stop()`\n * throws SYNCHRONOUSLY (before any promise is created) is caught by the same\n * `.catch` — otherwise the sync throw would escape, skip `resolveSettled()` in\n * the fulfilled-then-stopped branch of {@link activate}, and hang `settled`.\n *\n * An entry with no handle yet (a still-`connecting` Channel whose transport has\n * not come up) is only marked `stopped`: there is nothing to tear down, and the\n * post-settle guard releases the transport if it arrives after `stop()`.\n *\n * A WEDGED `handle.stop()` (one that never settles) is bounded by\n * {@link ChannelManagerArgs.stopHandleTimeoutMs}: after the deadline the call\n * is logged and abandoned so it can't hang `stop()` — and thus SIGTERM\n * shutdown — forever.\n *\n * @param entry - The Channel entry to stop.\n */\n private async stopEntry(entry: ChannelEntry): Promise<void> {\n entry.status = \"stopped\";\n if (entry.handle && !entry.handleStopped) {\n entry.handleStopped = true;\n const handle = entry.handle;\n // Bound handle.stop(): a wedged stop() (e.g. a socket.disconnect that\n // never returns) must not hang teardown — and thus SIGTERM shutdown —\n // forever. On timeout, log and abandon it (the call keeps running with a\n // settle handler attached inside withTimeout, so it never surfaces as an\n // unhandled rejection) so every OTHER entry still reaches `stopped`. The\n // `Promise.resolve().then(...)` wrap also routes a SYNCHRONOUS throw from\n // a foreign handle through the same timeout+catch.\n await withTimeout(\n Promise.resolve().then(() => handle.stop()),\n this.stopHandleTimeoutMs,\n `channel handle stop() timed out after ${this.stopHandleTimeoutMs}ms during teardown`,\n ).catch((err: unknown) =>\n this.log?.(\"channel handle stop() failed during teardown\", err),\n );\n }\n }\n\n /**\n * Stop every activated Channel exactly once and mark all statuses `stopped`.\n * Idempotent — a second call is a no-op.\n *\n * Resolves promptly: {@link stopEntry} stops only the handles that already\n * exist and never blocks on activations that have not settled. A hung connect\n * (which `ready({ timeoutMs })` tolerates) has no handle to stop yet, and\n * awaiting it here would hang teardown — and thus SIGTERM shutdown — forever.\n * Any handle that arrives after this point is torn down by the post-settle\n * guard in {@link activate}, which routes through the same idempotent\n * {@link stopEntry}, so nothing leaks and nothing double-stops.\n *\n * Teardown is resilient to a throwing `handle.stop()`: `Promise.allSettled`\n * over the per-entry `stopEntry` calls guarantees one rejection can't abort\n * the rest, so every entry reaches `stopped` and `stop()` always resolves.\n * It is equally resilient to a WEDGED `handle.stop()` that never settles: each\n * is bounded by {@link ChannelManagerArgs.stopHandleTimeoutMs} inside\n * {@link stopEntry}, so a single hung handle can't hang SIGTERM shutdown.\n */\n async stop(): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n\n const entries = [...this.entries.values()];\n await Promise.allSettled(entries.map((entry) => this.stopEntry(entry)));\n }\n}\n"],"mappings":";;;;;;;;;;;;AA8EA,IAAa,4BAAb,cAA+C,MAAM;CACnD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;;AA4FhB,MAAM,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;AAiDxC,eAAsB,uBACpB,QACA,SACA,mCACE,OACE,kCAEJ,KACyB;CACzB,IAAI;AACJ,KAAI;AACF,QAAM,MAAM,4BAA4B;UACjC,KAAK;AACZ,MAAI,iBAAiB,IAAI,CACvB,OAAM,IAAI,MACR,oHACA,EAAE,OAAO,KAAK,CACf;AAEH,QAAM;;AAER,QAAO,IAAI,iCAAiC,CAAC,QAAQ,EAAE;EACrD,OAAO,OAAO;EACd,QAAQ,OAAO;EACf,OAAO;GAAE,WAAW,OAAO;GAAW,aAAa,OAAO;GAAa;EACvE,mBAAmB,OAAO;EAC1B,SAAS,OAAO;EAIhB,eAAe,OAAO;EAItB,GAAI,MAAM,EAAE,KAAK,GAAG,EAAE;EACvB,CAAC;;;AAIJ,SAAS,gBAAgB,KAAuB;AAC9C,QACE,eAAe,6BACd,OAAO,QAAQ,YACd,QAAQ,QACP,IAA2B,SAAS;;;;;;;;AAU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B;GACtB,MAAM,SAAS,MAAM;AAQrB,SAAM,YACJ,QAAQ,SAAS,CAAC,WAAW,OAAO,MAAM,CAAC,EAC3C,KAAK,qBACL,yCAAyC,KAAK,oBAAoB,oBACnE,CAAC,OAAO,QACP,KAAK,MAAM,gDAAgD,IAAI,CAChE;;;;;;;;;;;;;;;;;;;;;;CAuBL,MAAM,OAAsB;AAC1B,MAAI,KAAK,QACP;AAEF,OAAK,UAAU;EAEf,MAAM,UAAU,CAAC,GAAG,KAAK,QAAQ,QAAQ,CAAC;AAC1C,QAAM,QAAQ,WAAW,QAAQ,KAAK,UAAU,KAAK,UAAU,MAAM,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"channel-manager.mjs","names":[],"sources":["../../../../src/v2/runtime/core/channel-manager.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n ChannelConfigError,\n deriveChannelActivationConfig,\n} from \"./channel-activation-config\";\nimport type { ChannelActivationConfig } from \"./channel-activation-config\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type {\n AgentSubscriber,\n BaseEvent,\n Message,\n RunAgentParameters,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport { EMPTY } from \"rxjs\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\n// Type-only: @copilotkit/channels is pure-ESM, so a value import would break this\n// package's CJS output (see `core/runtime.ts` and `channel-activation-config.ts`\n// for the same constraint).\nimport type { Channel } from \"@copilotkit/channels\";\n\n/**\n * Lifecycle status of a single Channel activation, or of the manager overall.\n *\n * - `connecting`: activation in flight, not yet settled.\n * - `online`: activation resolved AND the managed session can currently send.\n * A drop moves the Channel to `reconnecting` (not `online`); a successful\n * rejoin restores `online`.\n * - `setup_required`: the Channel is declared but has no managed provider yet —\n * a valid degraded state, not a failure.\n * - `reconnecting`: the managed session dropped and Phoenix is retrying — not\n * currently sendable. The manager does NOT re-activate (reconnection is\n * delegated to the Phoenix connection layer); it only reflects the health the\n * session reports via its `onStateChange` observer.\n * - `stopped`: {@link ChannelManager.stop} has torn the Channel down.\n * - `error`: activation rejected with a non-setup error, OR a previously-online\n * session gave up reconnecting after its bounded reconnect window or was\n * generation-fenced by a replacement.\n *\n * Both MANAGED (Intelligence-gateway) and DIRECT (developer-supplied adapter)\n * Channels move through these states. A direct Channel is driven by the manager\n * too — it is started via {@link Channel.ɵruntime}`.start()` and reaches `online`\n * once its own transport is up — but it is NOT wired into the Intelligence\n * gateway/canonical/reliability layer: it simply runs its own adapter transport,\n * started and stopped by the manager. A direct Channel has no managed-session\n * drop signal, so it never reports `reconnecting`.\n *\n * That gap is BY DESIGN, not a deferral. Run-correctness (canonical\n * cross-surface history, fenced outer-run/single-terminal, durable\n * HITL-resume-across-restart, selection pinning) and the reliability layer are\n * Intelligence-side only — see OSS-599's boundary discipline. A direct Channel's\n * ceiling is the SDK's in-process run loop. Do not \"finish\" this by pulling the\n * canonical/reliability layer down into the SDK: that is explicitly the thing\n * OSS-599 forbids.\n */\nexport type ChannelStatus =\n | \"connecting\"\n | \"online\"\n | \"setup_required\"\n | \"reconnecting\"\n | \"stopped\"\n | \"error\";\n\n/**\n * The lifecycle control surface a Channel host uses to drive and observe\n * managed Channel activation.\n */\nexport interface ChannelsControl {\n /**\n * Resolve once every declared Channel has settled to a terminal, non-connecting\n * state (`online` or `setup_required`). Rejects if any Channel is in `error`,\n * or — when `timeoutMs` is given — if the whole set has not settled in time.\n */\n ready(opts?: { timeoutMs?: number }): Promise<void>;\n /** Snapshot the overall status and the per-Channel status map. */\n status(): { overall: ChannelStatus; channels: Record<string, ChannelStatus> };\n /** Tear down every activated Channel. Idempotent. */\n stop(): Promise<void>;\n}\n\n/**\n * Signals that a declared Channel cannot be activated because no managed\n * provider exists for it yet. The engine throws this (or any error whose\n * `code === \"SETUP_REQUIRED\"`) to move a Channel to `setup_required` rather\n * than `error` — a declared-but-unprovisioned Channel is a valid degraded\n * state, not a failure.\n */\nexport class ChannelSetupRequiredError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ChannelSetupRequiredError\";\n }\n}\n\n/**\n * The activation engine: given a resolved {@link ChannelActivationConfig} and\n * the declared {@link Channel}, bring the Channel online and return its handle.\n * Injected in tests (a fake engine); defaults to the Realtime Gateway launcher.\n */\nexport type ActivateChannelEngine = (\n config: ChannelActivationConfig,\n channel: Channel,\n) => Promise<ChannelsHandle>;\n\n/**\n * Minimal structural view of the `@copilotkit/channels-intelligence`\n * `ChannelsHandle`. Declared locally (not imported) because the runtime is a\n * CJS package that must not take a static dependency on the pure-ESM\n * channels-intelligence package — the default engine reaches its launcher\n * through a dynamic `import()` instead. The manager only ever needs `stop()`.\n */\nexport interface ChannelsHandle {\n /** Activation metadata declared to Intelligence. Unused by the manager. */\n metadata: unknown;\n /** Stop the underlying Channel(s) and release transports. */\n stop(): Promise<void>;\n /**\n * Optional seam: register a callback the handle fires when its managed\n * session drops. Retained as a per-episode drop breadcrumb; the manager drives\n * status from {@link ChannelsHandle.onStateChange} instead. Present on the\n * Realtime Gateway launcher handle; optional for non-gateway/test handles.\n */\n onClose?(cb: () => void): void;\n /**\n * Optional seam: register a connection-health observer the handle fires as its\n * managed session moves between `online` (sendable), `reconnecting` (dropped,\n * Phoenix retrying), and `gave_up` (dead after the bounded reconnect window).\n * The manager uses this to keep {@link ChannelManager.status} honest — it does\n * NOT re-activate on a drop (reconnection is delegated to the Phoenix\n * connection layer; see {@link ChannelManager}). Optional so non-gateway or\n * test handles that do not implement it are always invoked as\n * `handle.onStateChange?.(cb)`.\n */\n onStateChange?(\n cb: (\n state: \"online\" | \"reconnecting\" | \"gave_up\" | \"fenced\",\n detail?: { reason?: string; code?: string },\n ) => void,\n ): void;\n}\n\n/** Constructor arguments for {@link ChannelManager}. */\nexport interface ChannelManagerArgs {\n /** The Intelligence runtime client the activation config is derived from. */\n intelligence: CopilotKitIntelligence;\n /** The declared framework Channels to activate. */\n channels: Channel[];\n /** Standard runtime AgentRunner used by managed Channel executions. */\n runner?: AgentRunner;\n /** Standard thread-lock TTL forwarded to Channel AgentRunner heartbeats. */\n lockTtlSeconds?: number;\n /** Standard thread-lock heartbeat cadence used by Channel AgentRunner calls. */\n lockHeartbeatIntervalSeconds?: number;\n /**\n * Activation engine. Defaults to a wrapper over the channels-intelligence\n * Realtime Gateway launcher (`startChannelsOverRealtimeGateway`), reached via\n * dynamic import so this CJS package keeps no static ESM dependency.\n */\n activateChannel?: ActivateChannelEngine;\n /** Mint a runtime instance id per Channel. Defaults to `rti_{uuid-no-dashes}`. */\n mintRuntimeInstanceId?: () => string;\n /** Diagnostic sink. Forwarded to the launcher/transport when the default\n * activation engine is used, so transport-level drops surface in the managed\n * path (not just activation-level events). */\n log?: (msg: string, meta?: unknown) => void;\n /**\n * How often (ms) to repeat a \"still down\" log while a managed session is\n * disconnected. A dropped session was previously silent for as long as the\n * outage lasted, which made a dead bot indistinguishable from an idle one\n * (OSS-670). Injectable so tests need no fake timers. Default 30000.\n */\n reconnectLogIntervalMs?: number;\n /** Per-handle deadline (ms) for `handle.stop()` during {@link ChannelManager.stop}\n * so a wedged stop can't hang SIGTERM shutdown. Default 5000. */\n stopHandleTimeoutMs?: number;\n}\n\n/** Per-Channel mutable activation entry tracked by the manager. */\ninterface ChannelEntry {\n status: ChannelStatus;\n /** Resolves on `online`/`setup_required`; rejects on `error`. Awaited by `ready`. */\n readonly settled: Promise<void>;\n handle?: ChannelsHandle;\n /**\n * Whether {@link ChannelManager.stopEntry} has already stopped `handle`. Gates\n * the single-stop guarantee: the success settle handler and `stop()` can both\n * reach the same entry in the same tick, but the handle is torn down at most\n * once.\n */\n handleStopped: boolean;\n /** Epoch ms this outage episode began; unset while the session is healthy. */\n downSince?: number;\n /** Repeating \"still down\" logger for this outage; cleared on recovery/teardown. */\n reconnectLogTimer?: ReturnType<typeof setInterval>;\n}\n\n/**\n * Runtime installs this pure-ESM package as a direct dependency, but the\n * specifier must stay non-literal so it never becomes a static dependency of\n * the runtime's CJS build. The packed-consumer contract is enforced by\n * `scripts/release/verify-runtime-package.ts`.\n */\nconst CHANNELS_INTELLIGENCE_SPECIFIER = \"@copilotkit/channels-intelligence\";\n\n/**\n * Structural view of the `@copilotkit/channels-intelligence` module surface the\n * default engine consumes. Declared locally (not imported) for the same\n * CJS/ESM-boundary reason the {@link ChannelsHandle} view is.\n */\nexport interface ChannelsIntelligenceModule {\n startChannelsOverRealtimeGateway: (\n channels: Channel[],\n opts: {\n wsUrl: string;\n apiKey: string;\n scope: { projectId: number; channelName: string };\n runtimeInstanceId: string;\n adapter?: string;\n /** Optional per-Channel override for managed tool-call visibility. */\n showToolStatus?: boolean;\n /** Intelligence app-api HTTP base URL, forwarded to the transport so the\n * managed realtime path enables file/history parity (HTTP-only) — OSS-476. */\n appApiBaseUrl?: string;\n /** Diagnostic sink forwarded to the launcher/transport so transport-level\n * drop diagnostics (e.g. a version-skew missing-leaseToken outage) are not\n * silent in the managed path. */\n log?: (msg: string, meta?: unknown) => void;\n runCanonical(args: {\n agent: AbstractAgent;\n threadId: string;\n runId: string;\n runnerToken: string;\n abortSignal: AbortSignal;\n tools: readonly {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n }[];\n context: readonly { description: string; value: string }[];\n persistedInputMessages: Message[];\n execute(\n subscriber: AgentSubscriber,\n canonicalRun?: { threadId: string; runId: string },\n ): Promise<{\n iterations: number;\n interrupted: boolean;\n deliveryError?: unknown;\n }>;\n }): Promise<{\n iterations: number;\n interrupted: boolean;\n deliveryError?: unknown;\n }>;\n loadHistory(args: {\n threadId: string;\n appUserId: string;\n }): Promise<Message[]>;\n },\n ) => Promise<ChannelsHandle>;\n}\n\n/**\n * Default engine: wrap the channels-intelligence Realtime Gateway launcher.\n *\n * The module is reached through an injectable importer that defaults to a\n * dynamic `import()` of a non-literal specifier, so the pure-ESM\n * `@copilotkit/channels-intelligence` never becomes a static dependency of this\n * CJS package (mirrors the runtime's other channels seams). The `import`\n * seam is a parameter purely so this function's config→opts mapping and its\n * module-not-found / generic-error branches are unit-testable WITHOUT the real\n * package installed; production always uses the default importer.\n *\n * Passes NO `org`/`channelId` — the launcher's realtime scope treats them as\n * optional.\n *\n * @param config - Resolved activation config for the Channel.\n * @param channel - The Channel to activate.\n * @param importChannelsIntelligence - Test seam; loads the channels-intelligence\n * module. Defaults to a dynamic import of the real package.\n * @param log - Optional diagnostic sink forwarded to the launcher/transport so\n * transport-level drop diagnostics are not silent in the managed path.\n * @returns The launcher's {@link ChannelsHandle}.\n */\nexport async function defaultActivateChannel(\n config: ChannelActivationConfig,\n channel: Channel,\n importChannelsIntelligence: () => Promise<ChannelsIntelligenceModule> = () =>\n import(\n CHANNELS_INTELLIGENCE_SPECIFIER\n ) as Promise<ChannelsIntelligenceModule>,\n log?: (msg: string, meta?: unknown) => void,\n services?: {\n runner: AgentRunner;\n intelligence: CopilotKitIntelligence;\n lockTtlSeconds?: number;\n lockHeartbeatIntervalSeconds?: number;\n },\n): Promise<ChannelsHandle> {\n let mod: ChannelsIntelligenceModule;\n try {\n mod = await importChannelsIntelligence();\n } catch (err) {\n if (isModuleNotFound(err)) {\n throw new Error(\n \"Managed Channels require '@copilotkit/channels-intelligence' to be installed. Add it to your app's dependencies.\",\n { cause: err },\n );\n }\n throw err;\n }\n if (!services) {\n throw new Error(\n \"Managed Channels require the runtime AgentRunner and Intelligence client\",\n );\n }\n return mod.startChannelsOverRealtimeGateway([channel], {\n wsUrl: config.wsUrl,\n apiKey: config.apiKey,\n scope: { projectId: config.projectId, channelName: config.channelName },\n runtimeInstanceId: config.runtimeInstanceId,\n adapter: config.adapter,\n ...(config.showToolStatus !== undefined\n ? { showToolStatus: config.showToolStatus }\n : {}),\n // Forward the app-api HTTP base URL so the transport wires file/history\n // (HTTP-only) on the NORMAL managed path — without this, Channels started by\n // the CopilotRuntime handler run with no history/file support (OSS-476).\n appApiBaseUrl: config.apiUrl,\n // Forward the manager's diagnostic sink down to the launcher/transport so a\n // transport-level drop (e.g. a version-skew missing-leaseToken outage) is\n // observable in the managed path, not just activation-level events.\n ...(log ? { log } : {}),\n runCanonical: (args) =>\n runCanonicalChannelAgent(\n services.runner,\n services.intelligence,\n services.lockTtlSeconds ?? 20,\n services.lockHeartbeatIntervalSeconds ?? 15,\n args,\n ),\n loadHistory: async ({ threadId, appUserId }) => {\n const history = await services.intelligence.getThreadMessages({\n threadId,\n userId: appUserId,\n });\n return history.messages.map(toAgentMessage);\n },\n });\n}\n\ninterface CanonicalRunArgs {\n agent: AbstractAgent;\n threadId: string;\n runId: string;\n runnerToken: string;\n abortSignal: AbortSignal;\n tools: readonly {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n }[];\n context: readonly { description: string; value: string }[];\n persistedInputMessages: Message[];\n execute(\n subscriber: AgentSubscriber,\n canonicalRun?: { threadId: string; runId: string },\n ): Promise<{\n iterations: number;\n interrupted: boolean;\n deliveryError?: unknown;\n }>;\n}\n\n/** One outer agent that lets the standard runner own the whole local tool loop. */\nclass ChannelOuterAgent extends AbstractAgent {\n constructor(\n private readonly inner: AbstractAgent,\n private readonly canonicalThreadId: string,\n private readonly executeLoop: CanonicalRunArgs[\"execute\"],\n ) {\n super({\n threadId: inner.threadId,\n initialMessages: inner.messages,\n initialState: inner.state,\n ...(inner.agentId ? { agentId: inner.agentId } : {}),\n });\n }\n\n run(): ReturnType<AbstractAgent[\"run\"]> {\n return EMPTY;\n }\n\n override async runAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n if (!parameters?.runId) {\n throw new Error(\"Canonical Channel run requires a runId\");\n }\n const result = await this.executeLoop(subscriber ?? {}, {\n threadId: this.canonicalThreadId,\n runId: parameters.runId,\n });\n return { result, newMessages: [] };\n }\n\n override abortRun(): void {\n this.inner.abortRun();\n }\n}\n\n/** Drive one public Channel run through the runtime's existing AgentRunner. */\nasync function runCanonicalChannelAgent(\n runner: AgentRunner,\n intelligence: CopilotKitIntelligence,\n lockTtlSeconds: number,\n lockHeartbeatIntervalSeconds: number,\n args: CanonicalRunArgs,\n): Promise<{\n iterations: number;\n interrupted: boolean;\n deliveryError?: unknown;\n}> {\n if (args.abortSignal.aborted) {\n throw channelRunCancellationError(args.abortSignal);\n }\n\n let result = { iterations: 0, interrupted: false };\n const outer = new ChannelOuterAgent(\n args.agent,\n args.threadId,\n async (subscriber, canonicalRun) => {\n result = await args.execute(subscriber, canonicalRun);\n return result;\n },\n );\n let stopPromise: Promise<boolean | undefined> | undefined;\n let heartbeatError: unknown;\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n const stopCanonicalRun = (): void => {\n stopPromise ??= Promise.resolve()\n .then(() => runner.stop({ threadId: args.threadId }))\n .catch(() => false);\n };\n args.abortSignal.addEventListener(\"abort\", stopCanonicalRun, { once: true });\n heartbeatTimer = setInterval(() => {\n intelligence\n .ɵrenewThreadLock({\n threadId: args.threadId,\n runId: args.runId,\n ttlSeconds: lockTtlSeconds,\n })\n .catch((error: unknown) => {\n if (heartbeatTimer === undefined) return;\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n heartbeatError = error;\n try {\n args.agent.abortRun();\n } catch {\n // The runner stop below remains the authoritative cancellation path.\n }\n stopCanonicalRun();\n });\n }, lockHeartbeatIntervalSeconds * 1_000);\n heartbeatTimer.unref?.();\n\n try {\n if (args.abortSignal.aborted) {\n stopCanonicalRun();\n }\n\n await new Promise<void>((resolve, reject) => {\n let terminalError: (Error & { code?: string }) | undefined;\n runner\n .run({\n threadId: args.threadId,\n agent: outer,\n input: {\n threadId: args.threadId,\n runId: args.runId,\n messages: args.agent.messages,\n state: args.agent.state,\n tools: [...args.tools],\n context: [...args.context],\n forwardedProps: undefined,\n },\n persistedInputMessages: args.persistedInputMessages,\n authToken: args.runnerToken,\n })\n .subscribe({\n next: (event: BaseEvent) => {\n if (event.type !== EventType.RUN_ERROR || terminalError) return;\n const message =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Canonical Channel agent run failed\";\n terminalError = new Error(message);\n terminalError.name = \"ChannelCanonicalRunError\";\n if (\n \"code\" in event &&\n typeof event.code === \"string\" &&\n event.code.length > 0\n ) {\n terminalError.code = event.code;\n }\n },\n error: reject,\n complete: () => {\n if (terminalError) {\n reject(terminalError);\n } else {\n resolve();\n }\n },\n });\n });\n } catch (error) {\n if (args.abortSignal.aborted) {\n await stopPromise;\n throw channelRunCancellationError(args.abortSignal);\n }\n throw error;\n } finally {\n if (heartbeatTimer !== undefined) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n }\n args.abortSignal.removeEventListener(\"abort\", stopCanonicalRun);\n }\n\n if (heartbeatError !== undefined) {\n await stopPromise;\n throw heartbeatError;\n }\n if (args.abortSignal.aborted) {\n await stopPromise;\n throw channelRunCancellationError(args.abortSignal);\n }\n return result;\n}\n\nfunction channelRunCancellationError(signal: AbortSignal): Error {\n const reason =\n typeof signal.reason === \"string\" && signal.reason.length > 0\n ? signal.reason\n : \"channel_run_cancelled\";\n const error = new Error(reason);\n error.name = \"ChannelCanonicalRunCancelledError\";\n return error;\n}\n\n/** Convert canonical Intelligence history into AG-UI messages. */\nfunction toAgentMessage(message: {\n id: string;\n role: string;\n content?: string;\n toolCalls?: Array<{ id: string; name: string; args: string }>;\n toolCallId?: string;\n}): Message {\n return {\n id: message.id,\n role: message.role as Message[\"role\"],\n content: message.content ?? \"\",\n ...(message.toolCalls\n ? {\n toolCalls: message.toolCalls.map((call) => ({\n id: call.id,\n type: \"function\" as const,\n function: { name: call.name, arguments: call.args },\n })),\n }\n : {}),\n ...(message.toolCallId ? { toolCallId: message.toolCallId } : {}),\n } as Message;\n}\n\n/** Whether `err` signals a missing managed provider rather than a hard failure. */\nfunction isSetupRequired(err: unknown): boolean {\n return (\n err instanceof ChannelSetupRequiredError ||\n (typeof err === \"object\" &&\n err !== null &&\n (err as { code?: unknown }).code === \"SETUP_REQUIRED\")\n );\n}\n\n/**\n * Whether `err` is a Node/runtime module-resolution failure — i.e. the error\n * a dynamic `import()` throws when the target package is not installed.\n * Exported so the friendly-error path in {@link defaultActivateChannel} can be\n * unit-tested without forcing a real failing import.\n */\nexport function isModuleNotFound(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) {\n return false;\n }\n const code = (err as { code?: unknown }).code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\n/** Default deadline (ms) for a single `handle.stop()` during teardown. */\nconst DEFAULT_STOP_HANDLE_TIMEOUT_MS = 5_000;\n\n/** Default cadence (ms) for the \"still down\" log while a session is dropped. */\nconst DEFAULT_RECONNECT_LOG_INTERVAL_MS = 30_000;\n\n/**\n * Reject with `timeoutMessage` after `timeoutMs` if `inner` has not settled,\n * otherwise pass `inner` through. When `timeoutMs` is undefined, `inner` is\n * returned unchanged. The timer is `unref`'d so a pending deadline never keeps\n * the process alive, and `inner` always has a settle handler attached, so a\n * timed-out promise that later settles never surfaces as unhandled.\n */\nfunction withTimeout<T>(\n inner: Promise<T>,\n timeoutMs: number | undefined,\n timeoutMessage: string,\n): Promise<T> {\n if (timeoutMs === undefined) {\n return inner;\n }\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(timeoutMessage)),\n timeoutMs,\n );\n (timer as unknown as { unref?: () => void }).unref?.();\n inner.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\n/**\n * Drives Channel activation for an Intelligence runtime: lazily activates each\n * declared Channel, tracks per-Channel lifecycle status, exposes readiness, and\n * tears everything down. A MANAGED Channel (empty `adapters`) is activated\n * through the injected engine over the Intelligence gateway; a DIRECT Channel\n * (developer-supplied adapter) is started through its own transport seam\n * (`channel.ɵruntime.start()`) — driven by the manager, but running only its own\n * adapter transport, not the gateway path (direct Channels stay below the\n * canonical/reliability layer by design — see {@link ChannelStatus} and OSS-599).\n * Its very existence means Intelligence is configured, so there is no\n * standalone/self-started path.\n *\n * Activation is lazy and idempotent — constructing the manager does nothing;\n * {@link activate} starts it and a second call is a no-op. Activation throws\n * SYNCHRONOUSLY (a {@link ChannelConfigError}) only for a misconfiguration it\n * can detect up front — a duplicate or missing Channel name. Every OTHER\n * activation failure is recorded as the Channel's status (`error`, or\n * `setup_required` for a missing provider) and surfaced through {@link status}\n * and {@link ready} rather than thrown.\n *\n * Reconnection is NOT handled here — it is delegated to the Phoenix connection\n * layer that backs the launcher. When a managed socket drops, Phoenix's `Socket`\n * auto-reconnects and auto-rejoins, re-sending the channel's join declaration;\n * the Intelligence gateway's `join/3` re-runs `record_heartbeat` (re-registering\n * the runtime's listener) and its `terminate/2` releases the dead socket's\n * leases (verified against Intelligence #511 `sdk_channel.ex`). So the transport\n * self-heals under the persistent adapter and a re-activation here would be both\n * redundant AND broken: re-invoking the engine on an already-started `Channel`\n * throws in `channel.addAdapter` (started=true). The manager therefore never\n * re-activates on a drop.\n *\n * It DOES, however, reflect real connection health through the session's\n * `onStateChange` observer so {@link ChannelManager.status} stays honest rather\n * than reporting `online` forever after a drop: a drop moves the Channel to\n * `reconnecting`, a successful rejoin restores `online`, and a bounded give-up\n * (Phoenix would otherwise retry forever) moves it to `error`.\n */\nexport class ChannelManager implements ChannelsControl {\n private readonly intelligence: CopilotKitIntelligence;\n private readonly runner?: AgentRunner;\n private readonly lockTtlSeconds: number;\n private readonly lockHeartbeatIntervalSeconds: number;\n private readonly channels: Channel[];\n private readonly activateChannel: ActivateChannelEngine;\n private readonly mintRuntimeInstanceId: () => string;\n private readonly log?: (msg: string, meta?: unknown) => void;\n private readonly stopHandleTimeoutMs: number;\n private readonly reconnectLogIntervalMs: number;\n\n private readonly entries = new Map<string, ChannelEntry>();\n private activated = false;\n private stopped = false;\n\n /** @param args - See {@link ChannelManagerArgs}. */\n constructor(args: ChannelManagerArgs) {\n this.intelligence = args.intelligence;\n this.runner = args.runner;\n this.lockTtlSeconds = args.lockTtlSeconds ?? 20;\n this.lockHeartbeatIntervalSeconds = args.lockHeartbeatIntervalSeconds ?? 15;\n this.channels = args.channels;\n this.log = args.log;\n // When using the default engine, forward the manager's log DOWN to the\n // launcher/transport (via defaultActivateChannel's log param) so a\n // transport-level drop is observable in the managed path. `this.log` is read\n // lazily at activation time, so this closure always sees the assigned sink.\n this.activateChannel =\n args.activateChannel ??\n ((config, channel) =>\n defaultActivateChannel(\n config,\n channel,\n undefined,\n this.log,\n this.runner\n ? {\n runner: this.runner,\n intelligence: this.intelligence,\n lockTtlSeconds: this.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: this.lockHeartbeatIntervalSeconds,\n }\n : undefined,\n ));\n this.mintRuntimeInstanceId =\n args.mintRuntimeInstanceId ??\n (() => `rti_${randomUUID().replace(/-/g, \"\")}`);\n this.stopHandleTimeoutMs =\n args.stopHandleTimeoutMs ?? DEFAULT_STOP_HANDLE_TIMEOUT_MS;\n this.reconnectLogIntervalMs =\n args.reconnectLogIntervalMs ?? DEFAULT_RECONNECT_LOG_INTERVAL_MS;\n }\n\n /**\n * Start activation of every declared Channel (lazy + idempotent). Mints a\n * distinct runtime instance id per Channel, derives its activation config,\n * and calls the engine. Records each Channel as `connecting`, transitioning\n * to `online`/`setup_required`/`error` as its activation settles.\n */\n activate(): void {\n // Short-circuit on BOTH latches: `activated` makes activation idempotent,\n // and `stopped` prevents a post-`stop()` activate() from opening transports\n // on a dead manager. (A late activation self-heals via the post-settle guard,\n // but never starting it is cheaper and clearer.)\n if (this.activated || this.stopped) {\n return;\n }\n // Reject duplicate Channel names BEFORE kicking off any engine call. The\n // manager keys `entries` by name, so a duplicate would let the second\n // activation's entry silently overwrite the first — leaking the first\n // Channel's live session out of status()/ready()/stop(). Fail loud here so\n // nothing is ever activated in that state.\n this.assertUniqueChannelNames();\n this.activated = true;\n\n // Partition declared Channels by transport. A Channel carrying ANY adapter\n // that is NOT the Intelligence managed adapter (a developer-supplied\n // slack/discord/... adapter, which lacks `__intelligenceChannel`) is a\n // DIRECT channel. The manager still owns its lifecycle — but a direct Channel\n // runs its OWN adapter transport rather than the Intelligence gateway path:\n // it is started here via `channel.ɵruntime.start()` (not the managed engine)\n // and torn down via `channel.ɵruntime.stop()`. The distinction is EXCLUSIVE\n // PER CHANNEL, not per platform — a Channel served by a direct adapter is not\n // also managed: ANY direct adapter makes the WHOLE Channel direct, regardless\n // of platform. Attaching the managed adapter alongside a direct one would\n // double-deliver every turn (and trip the SDK's `assertExclusive` guard,\n // moving the Channel to `error`). Per the SoT rule, never infer managed intent\n // from a local direct adapter — a managed-eligible Channel has an empty\n // `adapters` at declaration time. Managed+direct coexistence on the same\n // Channel is NOT supported today; it is deferred (OSS-484). Direct Channels\n // run only their own transport here and stay below the Intelligence\n // canonical/reliability layer by design, not pending work (OSS-599).\n for (const channel of this.channels) {\n const isDirect = channel.adapters.some((a) => !a.__intelligenceChannel);\n if (isDirect) {\n this.startDirectChannel(channel);\n continue;\n }\n const name = channel.name!;\n const runtimeInstanceId = this.mintRuntimeInstanceId();\n\n let resolveSettled!: () => void;\n let rejectSettled!: (err: unknown) => void;\n const settled = new Promise<void>((resolve, reject) => {\n resolveSettled = resolve;\n rejectSettled = reject;\n });\n // ready() awaits `settled`; if nothing ever handles a rejection there,\n // Node reports an unhandled rejection. Attach a no-op catch so the\n // promise is always considered handled — ready() still sees the reason.\n settled.catch(() => {});\n\n // Invoke the engine synchronously so activation is observably started the\n // moment activate() returns (callers assert the engine was called and see\n // `connecting` before awaiting ready). A synchronous config/engine throw is\n // turned into a rejected activation so it becomes this channel's status\n // rather than throwing out of activate().\n let activation: Promise<ChannelsHandle>;\n let config: ChannelActivationConfig | undefined;\n try {\n config = deriveChannelActivationConfig({\n intelligence: this.intelligence,\n channel,\n runtimeInstanceId,\n });\n activation = this.activateChannel(config, channel);\n } catch (err) {\n activation = Promise.reject(err);\n }\n\n // The deferred `.then` callbacks capture `entry` and run only after the\n // literal has fully initialized, so referencing it here is safe.\n const entry: ChannelEntry = {\n status: \"connecting\",\n handle: undefined,\n handleStopped: false,\n settled,\n };\n\n // Anchor the settle handlers. Both branches route every teardown through\n // the idempotent `stopEntry`, so a late settle can never resurrect a\n // `stopped` entry and a handle is torn down at most once. The handlers\n // only mutate state (never throw), so the trailing no-op catch just keeps\n // the chain from surfacing as an unhandled rejection.\n activation\n .then(\n async (handle) => {\n entry.handle = handle;\n if (this.stopped) {\n // stop() ran before this activation settled, so it could not tear\n // down a handle that did not exist yet. Release it now (idempotent)\n // and keep the Channel `stopped`.\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n entry.status = \"online\";\n this.registerConnectionObserver(name, entry);\n resolveSettled();\n },\n async (err: unknown) => {\n if (this.stopped) {\n // A rejection that arrives AFTER stop() must NOT resurrect the\n // entry into `error`/`setup_required`: the Channel is already\n // being torn down. Keep it `stopped` and resolve `settled` so a\n // subsequent ready() does not reject on a stopped Channel.\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n if (isSetupRequired(err)) {\n entry.status = \"setup_required\";\n this.log?.(`channel \"${name}\" requires setup`, err);\n resolveSettled();\n } else {\n entry.status = \"error\";\n this.log?.(`channel \"${name}\" failed to activate`, err);\n rejectSettled(err);\n }\n },\n )\n .catch(() => {});\n\n this.entries.set(name, entry);\n }\n }\n\n /**\n * Start a DIRECT-adapter Channel through its own transport seam\n * ({@link Channel.ɵruntime}`.start()`), recording a live entry so\n * {@link ready}/{@link status}/{@link stop} all cover it. A direct Channel is\n * driven by the manager — but only because the Intelligence runtime constructed\n * this manager at all — and runs its OWN adapter transport, NOT the Intelligence\n * gateway path. It is deliberately NOT wired into the gateway/canonical/\n * reliability layer — that boundary is permanent, not a deferral (OSS-599).\n *\n * Mirrors the managed path's settle machinery so teardown resilience is shared:\n * the entry's `handle` is a synthetic {@link ChannelsHandle} whose `stop()`\n * calls `channel.ɵruntime.stop()`, so the SAME idempotent, bounded, resilient\n * {@link stopEntry} that tears down a managed handle tears down a direct Channel\n * too. The handle is assigned only AFTER `start()` resolves (exactly as the\n * managed path assigns its handle only on resolve), so a `stop()` during a\n * still-starting direct Channel returns promptly with nothing to stop and the\n * post-settle guard tears down the late transport. A direct Channel exposes no\n * managed-session drop signal, so no connection observer is wired and it never\n * reaches `reconnecting`.\n *\n * @param channel - The direct-adapter Channel to start.\n */\n private startDirectChannel(channel: Channel): void {\n const name = channel.name!;\n this.log?.(\n `channel \"${name}\" carries a direct adapter — starting its own transport via channel.ɵruntime.start() (the Intelligence runtime drives its lifecycle; it runs its own adapter transport, NOT the managed gateway path — direct Channels stay below the canonical/reliability layer by design (OSS-599); managed+direct coexistence deferred (OSS-484))`,\n );\n\n let resolveSettled!: () => void;\n let rejectSettled!: (err: unknown) => void;\n const settled = new Promise<void>((resolve, reject) => {\n resolveSettled = resolve;\n rejectSettled = reject;\n });\n // ready() awaits `settled`; attach a no-op catch so a rejection is always\n // considered handled (ready() still sees the reason).\n settled.catch(() => {});\n\n // Synthetic handle wrapping the Channel's own stop seam. Assigned to the\n // entry only on successful start (below) so the shared teardown machinery\n // (handleStopped guard, withTimeout bounding, resilient allSettled) stops a\n // direct Channel exactly as it stops a managed handle.\n const directHandle: ChannelsHandle = {\n metadata: {},\n stop: () => channel.ɵruntime.stop(),\n };\n\n // Start the direct transport synchronously so it is observably started the\n // moment activate() returns (callers see `connecting` before awaiting ready).\n // A synchronous throw becomes this Channel's status rather than throwing out\n // of activate().\n let activation: Promise<void>;\n try {\n activation = channel.ɵruntime.start();\n } catch (err) {\n activation = Promise.reject(err);\n }\n\n const entry: ChannelEntry = {\n status: \"connecting\",\n handle: undefined,\n handleStopped: false,\n settled,\n };\n\n activation\n .then(\n async () => {\n entry.handle = directHandle;\n if (this.stopped) {\n // stop() ran before start() settled, so it could not tear down a\n // transport that was not up yet. Release it now (idempotent) and keep\n // the Channel `stopped`.\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n entry.status = \"online\";\n resolveSettled();\n },\n async (err: unknown) => {\n if (this.stopped) {\n // A start rejection that arrives AFTER stop() must NOT resurrect the\n // entry into `error`: the Channel is already being torn down. Keep it\n // `stopped` and resolve `settled` so a later ready() does not reject.\n entry.handle = directHandle;\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n entry.status = \"error\";\n this.log?.(\n `channel \"${name}\" failed to start its direct transport`,\n err,\n );\n rejectSettled(err);\n },\n )\n .catch(() => {});\n\n this.entries.set(name, entry);\n }\n\n /**\n * Throw if two declared Channels share a `name`. `entries` is keyed by name,\n * so a duplicate would overwrite the first Channel's entry and leak its live\n * session. Called at the very start of {@link activate}, before any engine\n * call, so a misconfiguration fails loud instead of silently.\n *\n * @throws {ChannelConfigError} If any Channel is missing a name, or if any\n * name appears more than once.\n */\n private assertUniqueChannelNames(): void {\n const seen = new Set<string>();\n for (const channel of this.channels) {\n const name = channel.name;\n // Check for a missing/empty name FIRST: `channel.name!` on a nameless\n // Channel keys as the string \"undefined\", which would otherwise report a\n // spurious duplicate for two nameless Channels before the accurate\n // missing-name error. Fail with the precise error instead.\n if (!name) {\n throw new ChannelConfigError(\n \"A managed Channel is missing a `name` — every declared Channel must \" +\n \"have a unique, non-empty name (pass createChannel({ name })).\",\n );\n }\n if (seen.has(name)) {\n throw new ChannelConfigError(\n `Duplicate managed Channel name \"${name}\" — every declared Channel ` +\n `must have a unique name.`,\n );\n }\n seen.add(name);\n }\n }\n\n /**\n * Resolve when every declared Channel — managed OR direct — has settled to\n * `online`/`setup_required`.\n *\n * A direct-adapter Channel is awaited too: its `settled` resolves once its own\n * transport is up (`channel.ɵruntime.start()` settling) and rejects if that\n * start fails, exactly as a managed Channel's `settled` tracks its activation.\n *\n * Activates lazily if not already started — so a first call rejects with the\n * same {@link ChannelConfigError} as the synchronous throw from\n * {@link activate} for an up-front misconfiguration (duplicate/missing Channel\n * names). Once activation has been kicked off, all OTHER failures are surfaced\n * here instead: this rejects with an `AggregateError` if any Channel settled\n * to `error` OR — when `timeoutMs` is given — did not settle in time. The\n * `timeoutMs` deadline is applied PER CHANNEL, so the aggregate carries each\n * failed Channel's real reason AND a named timeout for each Channel still\n * hanging: a genuine activation error is never masked by a sibling that hangs\n * (a pre-fix set-wide timeout discarded the real reason in that case).\n *\n * A STOPPED manager short-circuits and resolves: a Channel that settled to\n * `error` BEFORE {@link stop} already rejected its `settled` promise, so\n * awaiting it here would throw an `AggregateError` even though\n * {@link status}.overall is `\"stopped\"` — inconsistent with the case where the\n * Channel was still online at stop() (which resolves). A stopped manager has\n * nothing left to be ready for, so resolve uniformly.\n *\n * `ready()` is ONE-SHOT: it settles on the INITIAL activation outcome. Later\n * connection-health transitions (a live Channel dropping to `reconnecting`, or\n * giving up to `error`) are reported through {@link status} — where `online`\n * means currently-sendable — but do NOT re-arm or re-reject an already-settled\n * `ready()`.\n */\n async ready(opts?: { timeoutMs?: number }): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.activate();\n const entries = [...this.entries.entries()];\n // Apply `timeoutMs` PER CHANNEL rather than to the whole set. A single\n // set-wide timeout wrapping `allSettled` would, when one channel settles to\n // `error` while a sibling hangs, reject with only a generic timeout and\n // DISCARD the erroring channel's real reason. Timing out each channel's\n // `settled` independently lets `allSettled` collect BOTH a hung channel's\n // named timeout AND a failed channel's real error into one AggregateError.\n const results = await Promise.allSettled(\n entries.map(([name, e]) =>\n withTimeout(\n e.settled,\n opts?.timeoutMs,\n `channel \"${name}\" did not settle within ${opts?.timeoutMs}ms`,\n ),\n ),\n );\n const errors = results\n .filter((r): r is PromiseRejectedResult => r.status === \"rejected\")\n .map((r) => r.reason);\n if (errors.length > 0) {\n throw new AggregateError(\n errors,\n `ChannelManager.ready: ${errors.length} channel(s) failed to activate or settle in time`,\n );\n }\n }\n\n /**\n * Snapshot status. Every declared Channel — managed OR direct — appears keyed\n * by name in `channels`; a direct-adapter Channel reads `online` once its own\n * transport is up, exactly like a managed one.\n *\n * `overall` is folded over ALL declared Channels (see {@link computeOverall}),\n * by precedence `error` > `reconnecting` > `setup_required` > `connecting` >\n * `online`. `online` means every Channel can currently send. `reconnecting`\n * outranks `setup_required` because a dropped-but-retrying Channel is an active\n * outage, louder than a steadily-degraded unprovisioned one (only managed\n * Channels ever reach `reconnecting`; a direct Channel has no managed-session\n * drop signal). With no declared Channels at all, `overall` is `online` (nothing\n * is degraded); once every Channel has been stopped, `overall` is `stopped`.\n */\n status(): {\n overall: ChannelStatus;\n channels: Record<string, ChannelStatus>;\n } {\n const channels: Record<string, ChannelStatus> = {};\n for (const [name, entry] of this.entries) {\n channels[name] = entry.status;\n }\n // A stopped manager is `stopped` regardless of whether it was ever activated.\n // stop() before activate() (e.g. SIGTERM during startup) leaves `entries`\n // empty, and the empty-set fold below returns `online` — a torn-down manager\n // must never read healthy. Short-circuit before that fold. (After a normal\n // activate→stop, every entry is already `stopped` and the fold agrees, so\n // this is also consistent with the populated case.)\n if (this.stopped) {\n return { overall: \"stopped\", channels };\n }\n // Before activate() has run, `entries` is empty. Folding an empty set gives\n // `online` — correct for a manager that declares NO channels (nothing is\n // degraded), but a LIE for one that declares channels and simply has not\n // opened its socket yet: activation is lazy (deferred to the first\n // `ready()`), so a not-yet-activated manager must never read `online`.\n // Report `connecting` (\"not started\") for that case so `status()` is honest\n // before any `ready()`.\n if (!this.activated && this.channels.length > 0) {\n return { overall: \"connecting\", channels };\n }\n return { overall: this.computeOverall(Object.values(channels)), channels };\n }\n\n /**\n * Fold per-Channel statuses into a single overall status (see {@link status}).\n *\n * Every declared Channel — managed OR direct — participates: a started direct\n * Channel reads `online` and counts toward health exactly like a managed one,\n * and its `error` is a real outage that must dominate. Statuses are ranked\n * `error` > `reconnecting` > `setup_required` > `connecting` > `online`, so a\n * genuine failure still dominates a healthy sibling. (Only managed Channels ever\n * reach `reconnecting`; a direct Channel has no managed-session drop signal.)\n * The empty-input case (no declared Channels at all) stays `online` (nothing is\n * degraded).\n */\n private computeOverall(values: ChannelStatus[]): ChannelStatus {\n if (values.length === 0) {\n return \"online\";\n }\n if (values.every((v) => v === \"stopped\")) {\n return \"stopped\";\n }\n if (values.includes(\"error\")) {\n return \"error\";\n }\n if (values.includes(\"reconnecting\")) {\n return \"reconnecting\";\n }\n if (values.includes(\"setup_required\")) {\n return \"setup_required\";\n }\n if (values.includes(\"connecting\")) {\n return \"connecting\";\n }\n return \"online\";\n }\n\n /**\n * Wire the Channel's connection-health observer (if the handle exposes the\n * optional `onStateChange` seam) so {@link ChannelManager.status} reflects real\n * health instead of reporting `online` forever after a drop:\n *\n * - `reconnecting` → status `reconnecting` (dropped, Phoenix retrying);\n * - `online` → status `online` (rejoined, sendable again);\n * - `gave_up` → status `error` (dead after the bounded reconnect window);\n * - `fenced` → status `error` immediately (another activation superseded it).\n *\n * Makes NO re-activation — reconnection is delegated to the Phoenix connection\n * layer (see {@link ChannelManager}), which auto-rejoins under the persistent\n * adapter. A STOPPED manager (or an already-stopped entry) ignores late\n * connection events, so a drop that fires after {@link ChannelManager.stop}\n * never resurrects the Channel out of `stopped`.\n *\n * @param name - The Channel name (map key).\n * @param entry - The Channel's activation entry.\n */\n private registerConnectionObserver(name: string, entry: ChannelEntry): void {\n entry.handle?.onStateChange?.((state, detail) => {\n // A stopped manager (or a stopped entry) ignores late connection events.\n if (this.stopped || entry.status === \"stopped\") {\n return;\n }\n const cause = detail?.reason ?? detail?.code;\n const because = cause !== undefined ? ` — ${cause}` : \"\";\n if (state === \"reconnecting\") {\n entry.status = \"reconnecting\";\n entry.downSince ??= Date.now();\n this.log?.(\n `channel \"${name}\" managed session dropped; reconnecting (Phoenix auto-rejoin)${because}`,\n );\n this.startReconnectLog(name, entry);\n } else if (state === \"online\") {\n entry.status = \"online\";\n this.clearReconnectLog(entry);\n entry.downSince = undefined;\n this.log?.(`channel \"${name}\" managed session back online`);\n } else if (state === \"gave_up\") {\n // `error` here means \"not sendable\", NOT \"dead\": Phoenix keeps retrying\n // underneath and a successful rejoin restores `online`. Say so, or the\n // line reads as terminal (OSS-670). The repeat keeps running.\n entry.status = \"error\";\n this.log?.(\n `channel \"${name}\" managed session gave up reconnecting after ${this.downFor(entry)}; ` +\n `marking error (still retrying — a successful rejoin restores online)${because}`,\n );\n } else {\n entry.status = \"error\";\n this.clearReconnectLog(entry);\n this.log?.(\n `channel \"${name}\" managed session was generation-fenced by a replacement; marking error`,\n );\n }\n });\n }\n\n /** Rendered downtime for this outage episode (`\"45s\"`), or `\"unknown\"`. */\n private downFor(entry: ChannelEntry): string {\n return entry.downSince === undefined\n ? \"unknown\"\n : `${Math.round((Date.now() - entry.downSince) / 1000)}s`;\n }\n\n /**\n * Repeat a \"still down\" line for as long as this outage lasts. Runs THROUGH\n * `gave_up` on purpose: that transition is where the old behavior went quiet,\n * and an operator watching a silent process cannot tell a dead bot from an\n * idle one.\n */\n private startReconnectLog(name: string, entry: ChannelEntry): void {\n if (entry.reconnectLogTimer !== undefined) return;\n const timer = setInterval(() => {\n if (this.stopped || entry.status === \"stopped\") {\n this.clearReconnectLog(entry);\n return;\n }\n this.log?.(\n `channel \"${name}\" managed session still down after ${this.downFor(entry)}; Phoenix is retrying`,\n );\n }, this.reconnectLogIntervalMs);\n (timer as unknown as { unref?: () => void }).unref?.();\n entry.reconnectLogTimer = timer;\n }\n\n /** Stop this entry's \"still down\" repeat, if one is running. */\n private clearReconnectLog(entry: ChannelEntry): void {\n if (entry.reconnectLogTimer !== undefined) {\n clearInterval(entry.reconnectLogTimer);\n entry.reconnectLogTimer = undefined;\n }\n }\n\n /**\n * Drive a single entry to its terminal `stopped` state, tearing down its\n * handle AT MOST ONCE. Idempotent: it always sets `status = \"stopped\"`, and\n * only calls `handle.stop()` on the first invocation that sees a live,\n * not-yet-stopped handle (gated by {@link ChannelEntry.handleStopped}).\n *\n * This is the ONE guarded teardown path shared by both `stop()` and the\n * post-settle guard in {@link activate}/{@link startDirectChannel}. Because the\n * guard is per-entry and idempotent, a handle assigned in the same tick as\n * `stop()` is stopped exactly once even when both callers reach the entry, and a\n * late settle can never resurrect a `stopped` entry. It is transport-agnostic: a\n * managed entry's `handle.stop()` releases the gateway session, and a direct\n * entry's synthetic handle (assigned in {@link startDirectChannel}) routes the\n * same `handle.stop()` to `channel.ɵruntime.stop()` — so direct and managed\n * Channels share one bounded, resilient teardown.\n *\n * `handle.stop()` failures are logged (via {@link ChannelManager.log}) but NOT\n * rethrown: the real launcher's `stop()` rethrows after `session.disconnect()`,\n * and teardown must still complete for every other entry. The call is wrapped\n * in `Promise.resolve().then(...)` so a foreign/injected handle whose `stop()`\n * throws SYNCHRONOUSLY (before any promise is created) is caught by the same\n * `.catch` — otherwise the sync throw would escape, skip `resolveSettled()` in\n * the fulfilled-then-stopped branch of {@link activate}, and hang `settled`.\n *\n * An entry with no handle yet (a still-`connecting` Channel whose transport has\n * not come up) is only marked `stopped`: there is nothing to tear down, and the\n * post-settle guard releases the transport if it arrives after `stop()`.\n *\n * A WEDGED `handle.stop()` (one that never settles) is bounded by\n * {@link ChannelManagerArgs.stopHandleTimeoutMs}: after the deadline the call\n * is logged and abandoned so it can't hang `stop()` — and thus SIGTERM\n * shutdown — forever.\n *\n * @param entry - The Channel entry to stop.\n */\n private async stopEntry(entry: ChannelEntry): Promise<void> {\n entry.status = \"stopped\";\n // An unref'd interval would not hold the process open, but a stopped\n // manager must not keep logging about a session it no longer owns.\n this.clearReconnectLog(entry);\n if (entry.handle && !entry.handleStopped) {\n entry.handleStopped = true;\n const handle = entry.handle;\n // Bound handle.stop(): a wedged stop() (e.g. a socket.disconnect that\n // never returns) must not hang teardown — and thus SIGTERM shutdown —\n // forever. On timeout, log and abandon it (the call keeps running with a\n // settle handler attached inside withTimeout, so it never surfaces as an\n // unhandled rejection) so every OTHER entry still reaches `stopped`. The\n // `Promise.resolve().then(...)` wrap also routes a SYNCHRONOUS throw from\n // a foreign handle through the same timeout+catch.\n await withTimeout(\n Promise.resolve().then(() => handle.stop()),\n this.stopHandleTimeoutMs,\n `channel handle stop() timed out after ${this.stopHandleTimeoutMs}ms during teardown`,\n ).catch((err: unknown) =>\n this.log?.(\"channel handle stop() failed during teardown\", err),\n );\n }\n }\n\n /**\n * Stop every activated Channel exactly once and mark all statuses `stopped`.\n * Idempotent — a second call is a no-op.\n *\n * Resolves promptly: {@link stopEntry} stops only the handles that already\n * exist and never blocks on activations that have not settled. A hung connect\n * (which `ready({ timeoutMs })` tolerates) has no handle to stop yet, and\n * awaiting it here would hang teardown — and thus SIGTERM shutdown — forever.\n * Any handle that arrives after this point is torn down by the post-settle\n * guard in {@link activate}, which routes through the same idempotent\n * {@link stopEntry}, so nothing leaks and nothing double-stops.\n *\n * Teardown is resilient to a throwing `handle.stop()`: `Promise.allSettled`\n * over the per-entry `stopEntry` calls guarantees one rejection can't abort\n * the rest, so every entry reaches `stopped` and `stop()` always resolves.\n * It is equally resilient to a WEDGED `handle.stop()` that never settles: each\n * is bounded by {@link ChannelManagerArgs.stopHandleTimeoutMs} inside\n * {@link stopEntry}, so a single hung handle can't hang SIGTERM shutdown.\n */\n async stop(): Promise<void> {\n if (this.stopped) {\n return;\n }\n this.stopped = true;\n\n const entries = [...this.entries.values()];\n await Promise.allSettled(entries.map((entry) => this.stopEntry(entry)));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAwFA,IAAa,4BAAb,cAA+C,MAAM;CACnD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;;AAgHhB,MAAM,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;AAiFxC,eAAsB,uBACpB,QACA,SACA,mCACE,OACE,kCAEJ,KACA,UAMyB;CACzB,IAAI;AACJ,KAAI;AACF,QAAM,MAAM,4BAA4B;UACjC,KAAK;AACZ,MAAI,iBAAiB,IAAI,CACvB,OAAM,IAAI,MACR,oHACA,EAAE,OAAO,KAAK,CACf;AAEH,QAAM;;AAER,KAAI,CAAC,SACH,OAAM,IAAI,MACR,2EACD;AAEH,QAAO,IAAI,iCAAiC,CAAC,QAAQ,EAAE;EACrD,OAAO,OAAO;EACd,QAAQ,OAAO;EACf,OAAO;GAAE,WAAW,OAAO;GAAW,aAAa,OAAO;GAAa;EACvE,mBAAmB,OAAO;EAC1B,SAAS,OAAO;EAChB,GAAI,OAAO,mBAAmB,SA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}
|
|
@@ -56,6 +56,9 @@ function getOrCreateChannelManager(runtime, engine) {
|
|
|
56
56
|
if (existing) return existing;
|
|
57
57
|
const manager = new require_channel_manager.ChannelManager({
|
|
58
58
|
intelligence: runtime.intelligence,
|
|
59
|
+
runner: runtime.runner,
|
|
60
|
+
lockTtlSeconds: runtime.lockTtlSeconds,
|
|
61
|
+
lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,
|
|
59
62
|
channels: runtime.channels,
|
|
60
63
|
log: (msg, meta) => _copilotkit_shared.logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),
|
|
61
64
|
...engine ? { activateChannel: engine } : {}
|
|
@@ -117,6 +120,10 @@ function createCopilotRuntimeHandler(options) {
|
|
|
117
120
|
} else {
|
|
118
121
|
const matched = require_fetch_router.matchRoute(path, basePath);
|
|
119
122
|
if (!matched) throw jsonResponse({ error: "Not found" }, 404);
|
|
123
|
+
if (matched.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) {
|
|
124
|
+
route = matched;
|
|
125
|
+
throw jsonResponse({ error: "Not found" }, 404);
|
|
126
|
+
}
|
|
120
127
|
const methodError = validateHttpMethod(request.method, matched);
|
|
121
128
|
if (methodError) {
|
|
122
129
|
route = matched;
|
|
@@ -188,6 +195,7 @@ function createCopilotRuntimeHandler(options) {
|
|
|
188
195
|
return handler;
|
|
189
196
|
}
|
|
190
197
|
function dispatchRoute(runtime, request, route, options) {
|
|
198
|
+
if (route.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) throw jsonResponse({ error: "Not found" }, 404);
|
|
191
199
|
switch (route.method) {
|
|
192
200
|
case "agent/run": return require_handle_run.handleRunAgent({
|
|
193
201
|
runtime,
|
|
@@ -234,6 +242,10 @@ function dispatchRoute(runtime, request, route, options) {
|
|
|
234
242
|
runtime,
|
|
235
243
|
request
|
|
236
244
|
});
|
|
245
|
+
case "memories/recall": return require_memories.handleRecallMemories({
|
|
246
|
+
runtime,
|
|
247
|
+
request
|
|
248
|
+
});
|
|
237
249
|
case "memories/subscribe": return require_memories.handleSubscribeToMemories({
|
|
238
250
|
runtime,
|
|
239
251
|
request
|
|
@@ -366,6 +378,9 @@ function validateHttpMethod(httpMethod, route) {
|
|
|
366
378
|
case "memories/mutate":
|
|
367
379
|
if (method === "PATCH" || method === "DELETE") return null;
|
|
368
380
|
return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
|
|
381
|
+
case "memories/recall":
|
|
382
|
+
if (method === "POST") return null;
|
|
383
|
+
return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "POST" });
|
|
369
384
|
case "threads/update":
|
|
370
385
|
if (method === "PATCH" || method === "DELETE") return null;
|
|
371
386
|
return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-handler.cjs","names":["ChannelManager","logger","handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","runOnResponse","runOnError","isIntelligenceRuntime","handleRunAgent","handleSuggestAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","handleClearThreads","handleListThreads","handleCreateMemory","handleListMemories","handleSubscribeToMemories","handleRemoveMemory","handleUpdateMemory","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","handleGetThreadEvents","handleGetThreadState","handleAnnotate","handleDebugEvents","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAIA,uCAAe;EACjC,cAAc,QAAQ;EACtB,UAAU,QAAQ;EAYlB,MAAM,KAAK,SACTC,0BAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAA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,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
1
|
+
{"version":3,"file":"fetch-handler.cjs","names":["ChannelManager","logger","handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","runOnResponse","runOnError","isIntelligenceRuntime","handleRunAgent","handleSuggestAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","handleClearThreads","handleListThreads","handleCreateMemory","handleListMemories","handleRecallMemories","handleSubscribeToMemories","handleRemoveMemory","handleUpdateMemory","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","handleGetThreadEvents","handleGetThreadState","handleAnnotate","handleDebugEvents","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;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OAAO,OACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,SAAS,WAAW,OAAQ,QAAO;AAClD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,aACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;EAEJ,KAAK;AACH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ;AACE,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAOC,kCAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-handler.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"fetch-handler.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UAkHiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EA4EE;;;;;AAkFb;;;;EAnJE,QAAA;EAwJC;;;;;EAjJD,IAAA;EA+IE;;;;;EAxIF,IAAA,aAAiB,iBAAA;EA+IwB;;;EA1IzC,KAAA,GAAQ,mBAAA;EA2IR;;;;;;;;;EAhIA,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBAgFI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UAkHiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EA4EE;;;;;AAkFb;;;;EAnJE,QAAA;EAwJC;;;;;EAjJD,IAAA;EA+IE;;;;;EAxIF,IAAA,aAAiB,iBAAA;EA+IwB;;;EA1IzC,KAAA,GAAQ,mBAAA;EA2IR;;;;;;;;;EAhIA,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBAgFI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
|
|
@@ -13,7 +13,7 @@ import { handleGetRuntimeInfo } from "../handlers/get-runtime-info.mjs";
|
|
|
13
13
|
import { handleTranscribe } from "../handlers/handle-transcribe.mjs";
|
|
14
14
|
import { handleDebugEvents } from "../handlers/handle-debug-events.mjs";
|
|
15
15
|
import { handleArchiveThread, handleClearThreads, handleDeleteThread, handleGetThreadEvents, handleGetThreadMessages, handleGetThreadState, handleListThreads, handleSubscribeToThreads, handleUpdateThread } from "../handlers/intelligence/threads.mjs";
|
|
16
|
-
import { handleCreateMemory, handleListMemories, handleRemoveMemory, handleSubscribeToMemories, handleUpdateMemory } from "../handlers/intelligence/memories.mjs";
|
|
16
|
+
import { handleCreateMemory, handleListMemories, handleRecallMemories, handleRemoveMemory, handleSubscribeToMemories, handleUpdateMemory } from "../handlers/intelligence/memories.mjs";
|
|
17
17
|
import { handleAnnotate } from "../handlers/intelligence/annotate.mjs";
|
|
18
18
|
import { createJsonRequest, expectString, parseMethodCall } from "../endpoints/single-route-helpers.mjs";
|
|
19
19
|
import { fireInstanceCreatedTelemetry } from "../telemetry/instance-created.mjs";
|
|
@@ -55,6 +55,9 @@ function getOrCreateChannelManager(runtime, engine) {
|
|
|
55
55
|
if (existing) return existing;
|
|
56
56
|
const manager = new ChannelManager({
|
|
57
57
|
intelligence: runtime.intelligence,
|
|
58
|
+
runner: runtime.runner,
|
|
59
|
+
lockTtlSeconds: runtime.lockTtlSeconds,
|
|
60
|
+
lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,
|
|
58
61
|
channels: runtime.channels,
|
|
59
62
|
log: (msg, meta) => logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),
|
|
60
63
|
...engine ? { activateChannel: engine } : {}
|
|
@@ -116,6 +119,10 @@ function createCopilotRuntimeHandler(options) {
|
|
|
116
119
|
} else {
|
|
117
120
|
const matched = matchRoute(path, basePath);
|
|
118
121
|
if (!matched) throw jsonResponse({ error: "Not found" }, 404);
|
|
122
|
+
if (matched.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) {
|
|
123
|
+
route = matched;
|
|
124
|
+
throw jsonResponse({ error: "Not found" }, 404);
|
|
125
|
+
}
|
|
119
126
|
const methodError = validateHttpMethod(request.method, matched);
|
|
120
127
|
if (methodError) {
|
|
121
128
|
route = matched;
|
|
@@ -187,6 +194,7 @@ function createCopilotRuntimeHandler(options) {
|
|
|
187
194
|
return handler;
|
|
188
195
|
}
|
|
189
196
|
function dispatchRoute(runtime, request, route, options) {
|
|
197
|
+
if (route.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) throw jsonResponse({ error: "Not found" }, 404);
|
|
190
198
|
switch (route.method) {
|
|
191
199
|
case "agent/run": return handleRunAgent({
|
|
192
200
|
runtime,
|
|
@@ -233,6 +241,10 @@ function dispatchRoute(runtime, request, route, options) {
|
|
|
233
241
|
runtime,
|
|
234
242
|
request
|
|
235
243
|
});
|
|
244
|
+
case "memories/recall": return handleRecallMemories({
|
|
245
|
+
runtime,
|
|
246
|
+
request
|
|
247
|
+
});
|
|
236
248
|
case "memories/subscribe": return handleSubscribeToMemories({
|
|
237
249
|
runtime,
|
|
238
250
|
request
|
|
@@ -365,6 +377,9 @@ function validateHttpMethod(httpMethod, route) {
|
|
|
365
377
|
case "memories/mutate":
|
|
366
378
|
if (method === "PATCH" || method === "DELETE") return null;
|
|
367
379
|
return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
|
|
380
|
+
case "memories/recall":
|
|
381
|
+
if (method === "POST") return null;
|
|
382
|
+
return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "POST" });
|
|
368
383
|
case "threads/update":
|
|
369
384
|
if (method === "PATCH" || method === "DELETE") return null;
|
|
370
385
|
return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
|