UNPKG

@copilotkit/runtime

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

1 lines 85.3 kB
{"version":3,"file":"channel-manager.cjs","names":["MCPMiddleware","INTELLIGENCE_MEMORY_GRANT_HEADER","INTELLIGENCE_USER_ID_HEADER","AbstractAgent","EMPTY","EventType","deriveChannelActivationConfig","ChannelConfigError"],"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 { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../intelligence-platform/client\";\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 {\n Channel,\n ReplyContinuationOptions,\n ResolvedChannelMemory,\n} 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, the managed session can currently send, AND\n * the gateway did not report the Channel as missing a managed provider. A drop\n * moves the Channel to `reconnecting` (not `online`); a successful rejoin\n * restores `online`.\n * - `setup_required`: the Channel is declared but has no managed provider yet —\n * a valid degraded state, not a failure. Reached when the gateway reports the\n * provider as unattached/disabled/undeclared on the control join reply (see\n * {@link ChannelLegs}), or when the activation engine throws a\n * `SETUP_REQUIRED` error.\n *\n * NOTE: between the 2026-07-29 realtime-boundary cutover and the introduction\n * of {@link ChannelLegs}, this state had NO producer — the engine stopped\n * classifying it and nothing else set it, so a Channel with no Slack app at\n * all reported `online`. Do not reintroduce a code path that describes\n * `setup_required` without one that can actually emit it.\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 * control link gave up reconnecting after its bounded reconnect window.\n *\n * A Channel may carry developer-supplied direct adapters alongside the managed\n * Intelligence adapter. The managed engine owns the shared Channel lifecycle;\n * each adapter still receives only its own ingress and sends only its own\n * provider output.\n */\nexport type ChannelStatus =\n | \"connecting\"\n | \"online\"\n | \"setup_required\"\n | \"reconnecting\"\n | \"stopped\"\n | \"error\";\n\n/**\n * Managed provider attachment state for one Channel, as reported by the gateway\n * on the control join reply.\n *\n * `unknown` is this package's own value for \"the gateway did not tell us\" — a\n * gateway predating the provider-state contract, one whose lookup failed, or a\n * non-gateway handle. It must never be read as \"no provider attached\".\n */\nexport type ChannelProviderLeg =\n | \"attached\"\n | \"unhealthy\"\n | \"not_attached\"\n | \"disabled\"\n | \"channel_not_declared\"\n | \"unknown\";\n\n/**\n * The two independent things that have to be true for a managed Channel to\n * work, reported separately so a caller can assert the one it cares about.\n *\n * `status` is the fold of the two and matches this Channel's entry in\n * {@link ChannelsControl.status}'s `channels` map.\n *\n * The legs exist because they are genuinely separable: the control socket can be\n * joined and sendable while no Slack/Teams app is bound to the Channel at all.\n * Before they were split, `overall: \"online\"` proved only the socket, and\n * onboarding guidance used it to certify end-to-end success.\n */\nexport interface ChannelLegs {\n /** Fold of {@link transport} and {@link provider}. */\n status: ChannelStatus;\n /** Runtime ⇄ Gateway control socket for this Channel. */\n transport: ChannelStatus;\n /** Whether a managed provider is bound to this Channel. */\n provider: ChannelProviderLeg;\n}\n\n/**\n * Recognised provider states, used to validate what crosses the seam.\n *\n * Deliberately duplicates `PROVIDER_STATES` in\n * `@copilotkit/channels-intelligence`'s `realtime-gateway.ts` rather than\n * importing it: this package must not take a static dependency on\n * channels-intelligence (it is reached only through a dynamic import), so the\n * `providerStates` seam is duck-typed as `Record<string, string>`.\n *\n * A state added there needs adding here too, plus a `case` in\n * {@link foldChannelLegs}. Until both land it fails OPEN — an unrecognised state\n * becomes `unknown` and the Channel keeps its transport-derived status, rather\n * than being wrongly certified or condemned.\n */\nconst PROVIDER_LEGS: ReadonlySet<string> = new Set<ChannelProviderLeg>([\n \"attached\",\n \"unhealthy\",\n \"not_attached\",\n \"disabled\",\n \"channel_not_declared\",\n]);\n\n/**\n * Fold a Channel's transport and provider legs into its single status.\n *\n * The transport leg dominates whenever it is not `online`: while the control\n * socket is connecting, retrying, stopped, or failed, whatever the gateway last\n * said about the provider is stale or irrelevant — the Channel cannot serve a\n * turn either way, and reporting `setup_required` for a Channel that is actually\n * mid-reconnect would hide the outage.\n *\n * Once the transport is `online` the provider leg decides, which is the whole\n * point of the split: a joined socket with no provider bound is\n * `setup_required`, not `online`.\n *\n * `unknown` keeps the transport-derived answer. That is what makes an older\n * gateway (or a gateway whose lookup failed) behave exactly as it did before\n * provider states existed, instead of turning every Channel into\n * `setup_required`.\n *\n * @param transport - Control-socket status for the Channel.\n * @param provider - Reported provider attachment state.\n * @returns The folded Channel status.\n */\nexport function foldChannelLegs(\n transport: ChannelStatus,\n provider: ChannelProviderLeg,\n): ChannelStatus {\n if (transport !== \"online\") {\n return transport;\n }\n switch (provider) {\n case \"attached\":\n case \"unknown\":\n return \"online\";\n case \"unhealthy\":\n return \"error\";\n case \"not_attached\":\n case \"disabled\":\n case \"channel_not_declared\":\n return \"setup_required\";\n }\n}\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 its ACTIVATION — that is,\n * each Channel either activated or failed to. Rejects if any Channel failed to\n * activate, or — when `timeoutMs` is given — if the whole set has not settled\n * in time.\n *\n * Readiness is about activation, NOT about provider health: a Channel whose\n * transport joined but whose provider leg is `unhealthy` folds to a status of\n * `error` (see {@link foldChannelLegs}) while its activation settled normally.\n * So `ready()` resolving and `status().overall === \"error\"` can both be true at\n * once, by design — provider attachment is the Gateway's answer to a question\n * asked after activation, and it can change at any later rejoin. Assert\n * end-to-end reachability with {@link ChannelsControl.status}, not here.\n */\n ready(opts?: { timeoutMs?: number }): Promise<void>;\n /**\n * Snapshot the overall status, the per-Channel status map, and the per-Channel\n * transport/provider legs.\n *\n * `overall === \"online\"` does NOT by itself prove a Channel can receive\n * provider traffic unless the provider leg is `attached`: read `detail` when\n * you need to assert that a Channel is genuinely reachable from Slack/Teams,\n * because a `provider` of `unknown` leaves `status` transport-derived.\n */\n status(): {\n overall: ChannelStatus;\n channels: Record<string, ChannelStatus>;\n detail: Record<string, ChannelLegs>;\n };\n /** Tear down every activated Channel. Idempotent. */\n stop(): Promise<void>;\n}\n\ninterface ChannelRunErrorDetails {\n readonly category: \"validation\";\n readonly provider: \"slack\" | \"teams\";\n readonly operation: string;\n readonly effectKind: string;\n readonly providerCode: \"invalid_arguments\" | \"invalid_blocks\";\n readonly validationMessages: readonly string[];\n readonly retryable: false;\n readonly deliveryId: string;\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\",\n detail?: { reason?: string; code?: string },\n ) => void,\n ): void;\n /**\n * Optional seam: managed provider attachment state per declared Channel, as\n * reported on the newest gateway control join reply.\n *\n * A getter, so each read reflects the current join reply — the gateway's join\n * hooks re-fire on every auto-rejoin, so a Channel provisioned while the\n * runtime was disconnected is picked up without re-activating.\n *\n * `undefined` (or an absent method) means \"not reported\", NOT \"no provider\".\n * A gateway predating this contract, a gateway whose database read failed, and\n * a non-gateway/test handle all land here, and all must fall back to\n * transport-only status rather than claim a Channel is unprovisioned.\n */\n providerStates?(): Readonly<Record<string, string>> | undefined;\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 /** Must match web Intelligence runs so channel + HTTP share the same lock key. */\n lockKeyPrefix?: string;\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 * Initial delay (ms) before a \"still down\" log while a managed session is\n * disconnected. Later reminders back off exponentially to a 15-minute cap,\n * keeping a prolonged outage visible without flooding logs. Injectable so\n * tests can use a shorter first delay. 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 /** Next \"still down\" logger for this outage; cleared on recovery/teardown. */\n reconnectLogTimer?: ReturnType<typeof setTimeout>;\n /** Delay before the next reminder; doubles after each emitted reminder. */\n reconnectLogDelayMs?: number;\n /** Next retry after a transient initial activation failure. */\n activationRetryTimer?: ReturnType<typeof setTimeout>;\n /** Delay before the next activation retry; doubles after each failed attempt. */\n activationRetryDelayMs?: number;\n /** Reject the retry wrapper when teardown cancels a pending retry. */\n cancelActivationRetry?: () => void;\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 /** Optional per-Channel override for managed tool-call visibility. */\n showToolStatus?: boolean;\n /** Optional per-Channel tuning for continuation messages on long replies. */\n replyContinuation?: ReplyContinuationOptions;\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 deliveryId: string;\n signal?: AbortSignal;\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\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 deliveryId: string;\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 lockKeyPrefix?: string;\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 ...(config.showToolStatus !== undefined\n ? { showToolStatus: config.showToolStatus }\n : {}),\n ...(config.replyContinuation !== undefined\n ? { replyContinuation: config.replyContinuation }\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 services.lockKeyPrefix,\n ),\n loadHistory: async ({ deliveryId, threadId, appUserId }) => {\n const history = await services.intelligence.getThreadMessages({\n threadId,\n userId: appUserId,\n channelDeliveryId: deliveryId,\n });\n return Promise.all(\n history.messages.map((message) =>\n toAgentMessage(message, services.intelligence),\n ),\n );\n },\n });\n}\n\ninterface CanonicalRunArgs {\n agent: AbstractAgent;\n deliveryId: string;\n signal?: AbortSignal;\n threadId: string;\n runId: string;\n userId: string;\n memory?: ResolvedChannelMemory;\n agentId: string;\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/** Attach grant-scoped Intelligence Memory tools to one isolated Channel agent. */\nexport function attachChannelMemory(\n agent: AbstractAgent,\n intelligence: CopilotKitIntelligence,\n memory: ResolvedChannelMemory | undefined,\n): void {\n if (!memory) return;\n const middlewareAgent = agent as AbstractAgent & {\n use?: (middleware: unknown) => void;\n };\n if (typeof middlewareAgent.use !== \"function\") {\n const error = new Error(\n \"Channel Memory requires an agent with middleware support\",\n ) as Error & { code?: string };\n error.name = \"ChannelMemoryAgentUnsupportedError\";\n error.code = \"channel_memory_agent_unsupported\";\n throw error;\n }\n middlewareAgent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(memory.grant),\n ...(memory.user\n ? { [INTELLIGENCE_USER_ID_HEADER]: memory.user.id }\n : {}),\n },\n },\n ]),\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 lockKeyPrefix?: string,\n): Promise<{\n iterations: number;\n interrupted: boolean;\n deliveryError?: unknown;\n}> {\n const lock = await intelligence.ɵacquireThreadLock({\n threadId: args.threadId,\n runId: args.runId,\n userId: args.userId,\n agentId: args.agentId,\n channelDeliveryId: args.deliveryId,\n ttlSeconds: lockTtlSeconds,\n ...(lockKeyPrefix !== undefined ? { lockKeyPrefix } : {}),\n });\n const canonicalThreadId = lock.threadId;\n const canonicalRunId = lock.runId;\n let result = { iterations: 0, interrupted: false };\n attachChannelMemory(args.agent, intelligence, args.memory);\n const outer = new ChannelOuterAgent(\n args.agent,\n canonicalThreadId,\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(() =>\n runner.stop({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n }),\n )\n .catch(() => false);\n };\n const abortCanonicalRun = (): void => {\n try {\n args.agent.abortRun();\n } catch {\n // The exact runner stop remains the authoritative cancellation path.\n }\n stopCanonicalRun();\n };\n args.signal?.addEventListener(\"abort\", abortCanonicalRun, { once: true });\n heartbeatTimer = setInterval(() => {\n intelligence\n .ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: lockTtlSeconds,\n ...(lockKeyPrefix !== undefined ? { lockKeyPrefix } : {}),\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 await new Promise<void>((resolve, reject) => {\n let terminalError:\n | (Error & {\n code?: string;\n category?: string;\n provider?: string;\n operation?: string;\n effectKind?: string;\n providerCode?: string;\n validationMessages?: readonly string[];\n retryable?: boolean;\n deliveryId?: string;\n details?: unknown;\n })\n | undefined;\n const stream = runner.run({\n threadId: canonicalThreadId,\n agent: outer,\n input: {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\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 });\n stream.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 const details = safeChannelRunErrorDetails(event);\n terminalError = new Error(\n message,\n details ? { cause: details } : undefined,\n );\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 if (details) {\n terminalError.category = details.category;\n terminalError.provider = details.provider;\n terminalError.operation = details.operation;\n terminalError.effectKind = details.effectKind;\n terminalError.providerCode = details.providerCode;\n terminalError.validationMessages = details.validationMessages;\n terminalError.retryable = details.retryable;\n terminalError.deliveryId = details.deliveryId;\n terminalError.details = details;\n }\n },\n error: reject,\n complete: () => {\n if (terminalError) {\n reject(terminalError);\n } else {\n resolve();\n }\n },\n });\n if (args.signal?.aborted) {\n abortCanonicalRun();\n }\n });\n } finally {\n args.signal?.removeEventListener(\"abort\", abortCanonicalRun);\n if (heartbeatTimer !== undefined) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n }\n // Always release the product thread lock from the Runtime side. Gateway\n // may also release on terminal AG-UI ingestion; cleanup is idempotent and\n // covers runner paths that never stream terminal events (or lose them).\n await intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n })\n .catch(() => undefined);\n }\n\n if (heartbeatError !== undefined) {\n await stopPromise;\n throw heartbeatError;\n }\n return result;\n}\n\nfunction safeChannelRunErrorDetails(\n event: BaseEvent,\n): ChannelRunErrorDetails | undefined {\n if (\n !(\"details\" in event) ||\n typeof event.details !== \"object\" ||\n event.details === null ||\n Array.isArray(event.details)\n ) {\n return undefined;\n }\n const details = event.details as Record<string, unknown>;\n const allowed = new Set([\n \"category\",\n \"provider\",\n \"operation\",\n \"effectKind\",\n \"providerCode\",\n \"validationMessages\",\n \"retryable\",\n \"deliveryId\",\n ]);\n if (\n !Object.keys(details).every((field) => allowed.has(field)) ||\n details.category !== \"validation\" ||\n (details.provider !== \"slack\" && details.provider !== \"teams\") ||\n !boundedString(details.operation, 80) ||\n !boundedString(details.effectKind, 80) ||\n (details.providerCode !== \"invalid_arguments\" &&\n details.providerCode !== \"invalid_blocks\") ||\n details.retryable !== false ||\n !boundedString(details.deliveryId, 512) ||\n !Array.isArray(details.validationMessages) ||\n details.validationMessages.length > 5 ||\n !details.validationMessages.every(\n (validationMessage) =>\n typeof validationMessage === \"string\" &&\n validationMessage.length <= 256 &&\n validationMessage.startsWith(\"invalid field at /\"),\n )\n ) {\n return undefined;\n }\n return details as unknown as ChannelRunErrorDetails;\n}\n\nfunction boundedString(value: unknown, maxLength: number): value is string {\n return (\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength\n );\n}\n\n/** Convert canonical Intelligence history into AG-UI messages. */\nasync function toAgentMessage(\n message: {\n id: string;\n role: string;\n activityType?: string;\n content?: unknown;\n toolCalls?: Array<{ id: string; name: string; args: string }>;\n toolCallId?: string;\n },\n intelligence: CopilotKitIntelligence,\n): Promise<Message> {\n const content = await hydrateManagedContent(message.content, intelligence);\n return {\n id: message.id,\n role: message.role as Message[\"role\"],\n content: content ?? \"\",\n ...(message.activityType ? { activityType: message.activityType } : {}),\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/** Resolves managed asset references only at the authorized Runtime boundary. */\nasync function hydrateManagedContent(\n content: unknown,\n intelligence: CopilotKitIntelligence,\n): Promise<unknown> {\n if (Array.isArray(content)) {\n return Promise.all(\n content.map(async (part) => {\n if (\n typeof part !== \"object\" ||\n part === null ||\n !(\"source\" in part) ||\n typeof part.source !== \"object\" ||\n part.source === null ||\n !(\"value\" in part.source) ||\n typeof part.source.value !== \"string\" ||\n !part.source.value.startsWith(\"cpki-asset://\")\n ) {\n return part;\n }\n const assetId = part.source.value.slice(\"cpki-asset://\".length);\n const asset = await intelligence.ɵgetManagedChannelAsset(assetId);\n return {\n ...part,\n source: {\n type: \"data\",\n value: Buffer.from(asset.bytes).toString(\"base64\"),\n mimeType:\n asset.mimeType ??\n (\"mimeType\" in part.source &&\n typeof part.source.mimeType === \"string\"\n ? part.source.mimeType\n : \"application/octet-stream\"),\n },\n };\n }),\n );\n }\n\n if (\n typeof content === \"object\" &&\n content !== null &&\n \"assetId\" in content &&\n typeof content.assetId === \"string\"\n ) {\n const asset = await intelligence.ɵgetManagedChannelAsset(content.assetId);\n return {\n ...content,\n source: {\n type: \"data\",\n value: Buffer.from(asset.bytes).toString(\"base64\"),\n mimeType:\n asset.mimeType ??\n (\"mimeType\" in content && typeof content.mimeType === \"string\"\n ? content.mimeType\n : \"application/octet-stream\"),\n },\n };\n }\n\n return content;\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/** Whether a failed initial activation can recover without new configuration. */\nfunction isRetryableActivationError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) {\n return false;\n }\n const value = err as { code?: unknown; retryable?: unknown };\n return (\n (value.code === \"GATEWAY_UNREACHABLE\" ||\n value.code === \"GATEWAY_JOIN_FAILED\") &&\n value.retryable === true\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/** First delay (ms) before logging that a dropped session is still down. */\nconst DEFAULT_RECONNECT_LOG_INTERVAL_MS = 30_000;\n\n/** Longest delay (ms) between reminders during one continuous outage. */\nconst DEFAULT_RECONNECT_LOG_MAX_INTERVAL_MS = 15 * 60_000;\n\n/** First delay (ms) before retrying a transient initial activation failure. */\nconst DEFAULT_ACTIVATION_RETRY_DELAY_MS = 1_000;\n\n/** Longest delay (ms) between transient initial activation attempts. */\nconst DEFAULT_ACTIVATION_RETRY_MAX_DELAY_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 through the managed engine, tracks per-Channel lifecycle\n * status, exposes readiness, and tears everything down. Existing direct\n * adapters remain on the Channel; the launcher attaches the one managed\n * adapter before starting the combined adapter array.\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 * permanent activation failure is recorded as the Channel's status (`error`,\n * or `setup_required` for a missing provider) and surfaced through\n * {@link status} and {@link ready} rather than thrown. A retryable initial\n * gateway outage stays unsettled and retries until it connects or the manager\n * stops.\n *\n * Established-session reconnection is delegated to the Phoenix connection\n * layer that backs the launcher. When a managed control socket drops, Phoenix's\n * `Socket` reconnects and rejoins with the same Runtime declaration. The manager\n * never re-activates an already-started Channel. It does retry a transient\n * INITIAL gateway activation failure: that happens before the launcher adds or\n * starts the managed adapter, so a later attempt is safe.\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 lockKeyPrefix?: string;\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.lockKeyPrefix = args.lockKeyPrefix;\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 ...(this.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: this.lockKeyPrefix }\n : {}),\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. Transient gateway failures retry with exponential\n * backoff; other outcomes transition to `online`/`setup_required`/`error`.\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 control link 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 // Every declared Channel gets the managed adapter. Any developer-supplied\n // direct adapters stay in the same adapter array and are started by the\n // launcher's single `channel.ɵruntime.start()` call.\n for (const channel of this.channels) {\n channel.ɵruntime.enableIntelligenceMemory();\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 // The deferred activation callbacks capture `entry` and run only after\n // the literal has fully initialized, so referencing it there is safe.\n const entry: ChannelEntry = {\n status: \"connecting\",\n handle: undefined,\n handleStopped: false,\n settled,\n };\n\n // Invoke the engine synchronously so activation is observably started the\n // moment activate() returns. Only a typed transient gateway failure is\n // retried; config errors stay on the existing terminal path.\n let activation: Promise<ChannelsHandle>;\n try {\n const config = deriveChannelActivationConfig({\n intelligence: this.intelligence,\n channel,\n runtimeInstanceId,\n });\n activation = this.activateWithRetry(config, channel, name, entry);\n } catch (err) {\n activation = Promise.reject(err);\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 const hasDirectAdapter = channel.adapters.some(\n (adapter) => !adapter.__intelligenceChannel,\n );\n if (hasDirectAdapter) {\n try {\n // Managed setup may be incomplete while a developer-owned\n // transport is fully configured. Keep that transport alive;\n // a later runtime restart can attach the managed adapter once\n // Intelligence setup is complete.\n await channel.ɵruntime.start();\n entry.handle = {\n metadata: {},\n stop: () => channel.ɵruntime.stop(),\n };\n if (this.stopped) {\n await this.stopEntry(entry);\n resolveSettled();\n return;\n }\n } catch (directError) {\n if (this.stopped) {\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 adapters while managed setup is incomplete`,\n directError,\n );\n rejectSettled(directError);\n return;\n }\n }\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 * Retry only transient failures from the pre-adapter gateway connection.\n * Permanent errors reject on the first attempt; teardown cancels a pending\n * timer while preserving the exis