## What does this PR do?
Fixes a Vue `DataCloneError` that occurred when uploaded attachment
sources crossed the `structuredClone` boundary in core. Vue’s deep
`ref()` conversion wrapped nested attachment sources in reactive
proxies; `useAttachments` now keeps the attachment container shallow
with `shallowRef()`, preserving externally supplied sources as raw
cloneable values before they reach AG-UI/core payloads.
The change is intentionally Vue-only: core and React are untouched
because the defect is caused by Vue’s reactivity behavior at the
framework boundary. Focused regressions cover both the attachment hook
and `CopilotChat` submission path, including non-reactivity and
successful `structuredClone` behavior.
## Related PRs and Issues
- [CopilotKit issue
#3](https://github.com/enekesabel/CopilotKit/issues/3)
## Verification
- `pnpm nx run @copilotkit/vue:check-types` — passed.
- `pnpm nx run @copilotkit/vue:test --
src/v2/hooks/__tests__/use-attachments.test.ts
src/v2/components/chat/__tests__/CopilotChat.attachments.test.ts` —
passed, 18 tests in 2 files.
- `pnpm nx run @copilotkit/vue:build` — passed.
- Pre-commit package gate (`test-and-check-packages`) — passed: 1073
tests, publint, and attw.
- `pnpm nx run @copilotkit/vue:lint` — remains blocked by 171
pre-existing errors across unrelated Vue files; no lint errors were
introduced in the changed files.
- `git diff --check upstream/main...HEAD` — passed.
## Scope and exclusions
- Changed files are limited to
`packages/vue/src/v2/hooks/use-attachments.ts`, its focused hook and
`CopilotChat` tests, and the related `packages/vue/PARITY.md` and
`packages/vue/AGENTS.md` guidance.
- No core, React, workflow, or package-wide lint cleanup is included.
- The `PARITY.md` change removes accidental table-format churn and
retains only the meaningful attachment parity note.
## Checklist
- [x] I have read the [Contribution
Guide](https://github.com/CopilotKit/CopilotKit/blob/main/CONTRIBUTING.md)
- [x] If the PR changes or adds functionality, I have updated the
relevant documentation
- [x] "Allow edits by maintainers" is checked (lets us help iterate on
your PR directly — faster turnaround for everyone)
Fixes#2596
## Summary
`@copilotkit/runtime-client-gql` was still assuming abort-shaped errors
always expose a string `message`, which could turn an early-stop path
into a secondary TypeError instead of a clean abort suppression or the
original failure. This branch centralizes abort detection behind a
null-safe helper and keeps the existing abort phrases unchanged.
## Changes
- Replaced the duplicated abort checks in
`packages/runtime-client-gql/src/client/CopilotRuntimeClient.ts` with a
shared `isAbortError(unknown)` helper that only inspects string
messages.
- Added focused regression coverage in
`packages/runtime-client-gql/src/client/__tests__/CopilotRuntimeClient.test.ts`
for a string abort cause, an object without `message`, known abort
suppression in the stream path, and non-abort stream errors surfacing
normally.
- Added `.changeset/guard-abort-error-message.md` for the patch release
note.
## Scope
Only `packages/runtime-client-gql` and its local changeset are touched.
The abort phrases, caller-facing API, structured GraphQL error handling,
and stream close behavior for known aborts are unchanged.
## Test Plan
- [x] `npx nx run @copilotkit/runtime-client-gql:graphql-codegen` -
regenerated the package GraphQL artifacts used by the client imports.
- [x] `pnpm run build` - workspace build completed successfully.
- [x] `pnpm -C packages/runtime-client-gql exec vitest run
src/client/__tests__/CopilotRuntimeClient.test.ts` - 4/4 passed. Covers
a string abort cause in the fetch path, an object with no `message` in
the fetch path, known abort suppression in the stream path, and
non-abort stream errors surfacing.
- [x] `pnpm exec oxfmt --write
packages/runtime-client-gql/src/client/CopilotRuntimeClient.ts
packages/runtime-client-gql/src/client/__tests__/CopilotRuntimeClient.test.ts`
- formatted the touched source and test files.
- [x] `pnpm exec oxlint
packages/runtime-client-gql/src/client/CopilotRuntimeClient.ts
packages/runtime-client-gql/src/client/__tests__/CopilotRuntimeClient.test.ts`
- 0 warnings, 0 errors.
`useAgent` always returns a fully-constructed `AbstractAgent`: a provisional
stand-in while the runtime is still connecting (or in an error state), swapped
for the real agent once the `/info` sync resolves. The returned type claimed
`agent` was always the real agent, giving consumers no way to tell the two
apart — so one-time subscriptions (e.g. `onRunFinalized`) registered during the
provisional window landed on the placeholder and missed events until the effect
re-ran after the swap.
Add an `isReady` flag to the return value: `false` while the agent is
provisional, `true` once the real (or locally-registered) agent is bound.
Additive and backward compatible.
Also fix the docs' "Event Subscription" example, which used an empty
`useEffect` dependency array and therefore never re-subscribed when the agent
reference changed.
Note: the original crash from #5000 ("Cannot read properties of undefined
(reading 'subscribers')") no longer reproduces on `main` — the provisional-agent
work (#5533/#5635) guarantees a fully-constructed agent, so `subscribe()` is
always safe. The added tests lock in that no-crash behavior and cover the new
`isReady` transition.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Six pre-existing `@copilotkit/channels-intelligence` HTTP-transport
robustness items surfaced by the pre-merge CR of #5983 (Linear OSS-497).
All confirmed against `main` after #5983 merged; none introduced by it.
Each is an independent, focused commit with a test.
## Fixes
1. **Heartbeat starvation mid-turn** — `HttpDeliverySource.runLoop`
heartbeated only at the top of each iteration, then blocked on
`onDelivery` for up to `turnTimeoutMs` (120s). With a 15s cadence, a
turn longer than the cadence sent no heartbeat, so app-api could mark a
healthily-working runtime stale mid-turn and withhold new deliveries.
Heartbeating now runs on a standalone recurring timer, independent of
the claim loop.
2. **`stop()` shutdown latency** — `stop()` set `running=false` then
awaited the loop, which only rechecked after its current sleep (≤15s
idle) or `onDelivery` (≤120s mid-turn); sleeps were `unref`'d but not
interruptible. Added a `stopWait` promise that the poll-sleep and
turn-wait both race, so shutdown is prompt. A mid-turn stop leaves the
lease for app-api to re-lease and does **not** nack (the turn didn't
fail); the turn's eventual settlement is always handled so a post-stop
rejection never surfaces as unhandled. *(1 & 2 share the runLoop
lifecycle, so they land in one commit.)*
3. **Empty-text `update` silently acked** — the `if (!text) return { ok:
true }` guard ran for both `post` and `update`. An empty POST is a legit
no-op, but an empty UPDATE (e.g. clearing a message body) that this
post-only fallback egress can't express was acked as success. Now
returns `{ ok: false, code: "empty_update" }`; empty posts still no-op.
4. **Static `adapter` on egress** — `emit` posted `this.cfg.adapter`
(default `"slack"`) alongside a possibly-Teams `replyTarget`. Confirmed
app-api's egress route (`sendChannelEgressMessage`) routes on
`replyTarget.adapter` + `channelName` and ignores this field, so it's
latent — but now derived from the delivery's own reply route to avoid
the contradiction. *(Note: the listener heartbeat's
`declaredChannels[].adapter` is intentionally left alone — app-api
genuinely consumes it for per-adapter health/conflict via the
`channel_adapter_configs.provider` join, and declaring the bot's full
adapter set is a separate design change, not a robustness cleanup.)*
5. **`projectId` strict-`number` only** — the realtime scope build
accepted `projectId` only as a JS `number` while org/channel were
`String()`-coerced, so a numeric-string on the untyped wire silently
fell back to the transport-default projectId, defeating per-delivery
scope authority. Extracted a `coerceWireProjectId` helper (number or
numeric-string → positive integer) with fallback.
6. **File/history client ignored injectable `fetch`** —
`fetchFile`/`getHistory`/`uploadFile` hardcoded `globalThis.fetch`, so
an injected `config.fetch` was honored everywhere except
binary/history/upload. The transport's `FetchLike` is text-only and
can't satisfy the binary client, so the file/history client got its
**own** injectable full `fetch` (`typeof fetch`), resolved via a single
helper with a global fallback.
Plus a small `docs` commit fixing a doc-comment placement displaced by
the item-5 export.
## Testing
- `nx run @copilotkit/channels-intelligence:test` — **178 passed** (170
baseline + 8 new).
- `nx run @copilotkit/channels-intelligence:check-types` — clean.
- lefthook (full package test + typecheck) ran on every commit.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Follow-up to the OSS-497 robustness cluster after a 3-agent adversarial review.
- Empty-text update: reclassify from a hard {ok:false} failure to a logged
no-op. The failure path threw up the run and nack'd the WHOLE turn retryably,
re-running valid work to dead-letter for a condition a retry can't fix (an
agent clearing a message body the post-only fallback can't express). Now it is
skipped with a distinct warning log — surfaced, not silent, and not turn-fatal.
- Injectable fetch: plumb it through the transports. Both HttpDeliverySource and
RealtimeGatewayTransport now accept a binary-capable /
and forward it to IntelligenceFileHistoryClient, so a consumer injecting a
fetch has it honored on the download/history/upload paths (previously the
client-level injectable was reachable only by constructing the client directly).
- coerceWireProjectId: use Number.isSafeInteger so a numeric string beyond
MAX_SAFE_INTEGER is rejected (was silently coerced to a lossy integer).
- Malformed-present projectId: log before falling back to the transport scope
(an absent projectId still falls back quietly), mirroring the loud drops in
the same function instead of silently masking a wire-corruption signal.
- Restart safety: guard the recurring heartbeat with a run generation so a
stop->start while a heartbeat POST is in flight can't leave two reschedule
chains doubling the heartbeat rate; bump the generation on stop().
- Remove now-dead lastHeartbeatAt state (only reader was the removed in-loop
heartbeat check).
Tests: empty-update now asserts log + no-op; added transport fileFetch
wire-through, adapter-from-route fallback, no-unhandled-rejection after a
mid-turn stop, heartbeat-stops-after-stop, elapsed-time bounds on the stop()
promptness tests, and coerceWireProjectId edge cases (leading zeros, > safe int).
nx test (green) + check-types (clean).
The coerceWireProjectId export (added for OSS-497) was inserted directly above
assertValidChannelRealtimeScope, displacing that function's doc comment onto the
helper. Reorder so each function carries its own docblock.
IntelligenceFileHistoryConfig's fetchFile/getHistory/uploadFile hardcoded
globalThis.fetch, so a consumer (or test) injecting a fetch had it honored
everywhere EXCEPT the binary download, history, and upload paths. The transport's
FetchLike is text-only ({ ok, status, text() }) and cannot satisfy the binary
client (.body/.arrayBuffer()/.headers/.json()), so add the client's OWN
injectable full `fetch` (typeof fetch) on its config, resolved via a single
resolveFetch() helper that falls back to the global fetch. Each caller keeps its
existing degrade/throw contract for the no-fetch runtime.
Surfaced by the pre-merge CR of #5983 (OSS-497).
Two coupled HttpDeliverySource runLoop lifecycle robustness fixes:
Heartbeat starvation: the loop heartbeated only at the top of each iteration,
then blocked on onDelivery for up to turnTimeoutMs (120s). With a 15s cadence,
a turn longer than the cadence sent no heartbeat for its whole duration, so
app-api could expire the activation and mark a healthily-working runtime stale
mid-turn, withholding new deliveries. Move heartbeating to a standalone
recurring timer that fires on cadence regardless of what the loop is doing
(rescheduling only after each heartbeat settles, so no overlap).
Shutdown latency: stop() set running=false then awaited the loop, but the loop
only rechecked after its current sleep (up to cadence, idle) or onDelivery (up
to turnTimeoutMs, mid-turn) — the sleeps were unref'd but not interruptible, so
shutdown could take up to 15s idle or 120s mid-turn. Add a stopWait promise that
stop() resolves; the poll-sleep and the turn-wait both race it, so shutdown is
prompt. A mid-turn stop leaves the lease for app-api to re-lease and does NOT
nack (the turn didn't fail); the turn's eventual settlement is always handled so
a post-stop rejection never surfaces as unhandled.
Surfaced by the pre-merge CR of #5983 (OSS-497).
RealtimeGatewayTransport.toIngressEnvelope built the per-delivery scope with
`typeof delivery.projectId === 'number' ? delivery.projectId : this.scope.projectId`,
while organizationId/channelId were String()-coerced. The delivery.available
payload is untyped JSON, so a numeric-string projectId ('9' on the wire) failed
the strict check and silently substituted the transport-default projectId —
defeating the per-delivery scope authority and routing the render-accept under
the wrong project.
Extract a `coerceWireProjectId` helper (number or numeric-string -> positive
integer, else undefined) and use it with a fallback to the transport default.
Surfaced by the pre-merge CR of #5983 (OSS-497).
HttpEgressSink.emit posted the static `this.cfg.adapter` (default "slack")
alongside a possibly-Teams `replyTarget`, so a Teams delivery through the
fallback egress carried a contradictory `adapter: "slack"`. app-api's egress
route (sendChannelEgressMessage) routes on `replyTarget.adapter` + channelName
and ignores this top-level field, so this is latent — but one provider-agnostic
runtime serves every adapter its bot has attached, so posting the config default
is misleading. Derive the posted adapter from the delivery's own reply route,
falling back to the config adapter when the route carries none.
Note: the listener heartbeat's declaredChannels[].adapter is NOT changed here —
app-api genuinely consumes it (the channel_adapter_configs.provider join) for
per-adapter health/conflict reporting, and the runtime only knows its single
configured adapter; declaring the bot's full adapter set is a separate design
change, not this robustness cleanup.
Surfaced by the pre-merge CR of #5983 (OSS-497).
HttpEgressSink.emit ran the `if (!text) return { ok: true }` no-op guard for
both post and update ops. An empty POST is a legitimate no-op (nothing to say),
but an empty UPDATE — a real intent such as clearing a message body that this
post-only fallback egress cannot express — was acked as success while nothing
was sent, inconsistent with the module's fail-loud posture. Return
`{ ok: false, code: 'empty_update' }` for that case; empty posts still no-op.
Surfaced by the pre-merge CR of #5983 (OSS-497).
The getMessages JSDoc cited "what was in the image" as a use case, but
image/file parts contribute no text in this mapping — read_thread is
text-only. Image content reaches the model only via conversationStore's
seeding of agent.messages. Tweak the comment so it no longer implies
read_thread can see image content.
## Release monorepo v1.63.1
**Scope:** `monorepo` | **Bump:** `patch`
---
### How this release process works
1. **This PR was created automatically** by the "release / create-pr"
workflow.
It bumped the `monorepo` packages to `1.63.1`
and generated AI-enhanced release notes.
2. **CI runs on this PR** — the full test suite (unit tests, lint, type
checks, build)
must pass before merging. This is the review gate.
3. **Review the release notes** in `release-notes.md` in this PR.
If a Notion draft was created, you can edit the release notes there
before merging.
4. **When this PR is merged**, the `release / publish` workflow
automatically:
- Builds all packages
- Publishes the `monorepo` packages to npm at version `1.63.1`
- Creates git tag `monorepo/v1.63.1`
- Creates a GitHub Release with the final release notes
### Before merging
- [ ] CI is green (tests, lint, types, build)
- [ ] Version bumps look correct
- [ ] Release notes are accurate (edit in Notion if a draft was created)
---
> **Do not merge until CI is fully green.** The full test suite runs
automatically on this PR.
- emoji: match Teams codepoint hex case-insensitively (providers may send
upper-case) + document single-codepoint-only parsing; cover 1F504_refresh.
- emoji: note the dormant outbound Teams asymmetry in toPlatformEmoji
(unicode vs `<codepoint>_<name>`) as a TODO for when outbound reactions land.
- channels-slack: split the tool-only status-clear test so one mirrors the
real event order (RUN_FINISHED before finish()) and one isolates the
finish() backstop.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The run renderer only cleared Slack's native "is thinking…" assistant
status from onFirstReply() (streamed-text paths) or the error/interrupt
paths. A turn whose reply streamed NO text — a tool-only / file-only
reply such as a posted chart — never triggered onFirstReply, so the
status indicator lingered forever.
finish() now clears the status as a backstop when statusMode is on and
no reply was posted. The postedReply guard prevents a redundant clear on
the normal streamed-text path (onFirstReply already cleared it).
Adds regression tests covering both the tool-only clear and the
postedReply guard.
Normalize inbound reaction emoji to a canonical cross-platform name at the
central channels-core ingress, so onReaction handlers match one value
regardless of provider.
- channels-ui/emoji: add "teams" and "whatsapp" to EmojiPlatform and canonical
entries for refresh/laugh/surprised/sad/angry. Teams normalizes its
<codepoint>_<name> emoji codes (1f504_refresh -> refresh) and classic bare
names (like -> thumbs_up); an out-of-range codepoint degrades to passthrough
instead of throwing. WhatsApp uses the unicode path like Discord/Telegram.
- channels-core: add teams+whatsapp to EMOJI_PLATFORMS; IncomingReaction gains
an optional source `platform`; onReaction normalizes by
evt.platform ?? adapter.platform.
- channels-intelligence: the managed reaction dispatch passes the delivery's
source platform (env.platform) so managed reactions normalize too.
## Summary
- Extract the platform-neutral Channels foundation into
`@copilotkit/channels-core`.
- Make `@copilotkit/channels` the batteries-included consumer entry
point, with adapter and UI subpaths.
- Release the umbrella, core, UI, and all six adapters as one shared
`channels` version scope.
- Verify the packed consumer contract and migrate the Slack and Teams
examples to the umbrella.
## Why
Consumers should be able to install one Channels package without making
the runtime or selective integrations depend on every platform SDK.
Shipping the complete Channels family together prevents adapter/core
version drift and makes the umbrella's exact dependency set release as a
compatible unit.
## How
- Move shared bot/runtime primitives into `channels-core` and invert
adapter/runtime dependencies.
- Add exact workspace dependencies and export subpaths from the umbrella
package.
- Consolidate the existing release configuration and all three release
workflow selectors into one shared `channels` scope containing all nine
packages.
- Use `@copilotkit/channels` as the version source: the next minor
release resolves to `0.2.0` and bumps every Channels package together.
- Publish scoped packages in dependency order for both stable and canary
releases: UI, core, adapters, then the umbrella.
- For a stable Channels release, publish the UI/core/adapters first, run
the registry-backed packed-consumer verifier against those newly
published exact versions, then publish the umbrella.
- Generate Channels release notes from `channels/v*` tags rather than
the monorepo `v*` tags.
- Verify builds, type checks, tests, package artifacts, examples, and
release workflow scope synchronization locally.
### First stable release sequence
1. Bootstrap the currently unpublished `@copilotkit/channels-core`
package on npm and configure npm trusted publishing for every Channels
package against this repository's `release / publish` workflow and `npm`
environment.
2. Create and merge the `channels` minor release PR. The stable workflow
publishes the Channels family in the staged order above and validates
the packed umbrella from the registry before the umbrella is released.
3. Create and merge a subsequent `monorepo` release PR so the published
`@copilotkit/runtime` switches from the historical umbrella dependency
to `@copilotkit/channels-core`.
- [P1] History/files were absent on the NORMAL managed path: defaultActivateChannel
never forwarded the app-api HTTP URL, so the transport (which installs
fetchFile/getHistory/uploadFile only when appApiBaseUrl is set) ran without
them for Channels started by the CopilotRuntime handler — only manual
low-level launcher callers got file/history. Thread intelligence.ɵgetApiUrl()
through ChannelActivationConfig.apiUrl → defaultActivateChannel →
startChannelsOverRealtimeGateway({ appApiBaseUrl }). The launcher + transport
already accepted it.
- [P2] Managed turns exposed the provider profile under a non-public `displayName`
field, leaving PlatformUser.name undefined. Map env.user.displayName -> name
(parity with the direct Slack adapter, which populates `name`).
Tests: deriver returns apiUrl; defaultActivateChannel forwards appApiBaseUrl to
the launcher opts; onMessage sees message.user.name. channel-activation-config +
channels-intelligence (170) green; runtime build type-checks. (channel-manager.test
executes in CI — local vitest hits the known optional-peer-dep resolution flake.)
Trivial items from the CR confirmation rounds (no behavior change to production
paths):
- intelligence-adapter.test.ts: `delete source.getHistory` was inert (getHistory
is a prototype method; delete only removes own props), so the "no getHistory"
branch was never actually exercised. Shadow with an own `undefined` instead so
the `source?.getHistory?.()` short-circuit is genuinely tested.
- in-memory-transports.ts: mirror the production `limit <= 0 -> []` guard in
InMemoryDeliverySource.getHistory (was `slice(-limit)` → returns ALL for 0).
- realtime ack(): log the empty-turn (no accepted frames) drop so the OSS-491
redelivery pile-up is diagnosable (every other drop path here logs).
- http-transports.ts: remove two orphaned JSDoc comments dangling over
ClaimResponse (leftovers from the file/history extraction).
- intelligence-adapter.ts: correct an inaccurate op-id comment (mintOp is the
${turnId}:${seq} source; the render path keys on ${turnId}:${slot}:${seq}).
channels-intelligence 170 tests + check-types green.
From the 7-agent CR confirmation round:
- RealtimeGatewayTransport.stop() now halts intake (a `stopped` guard in
handleDeliveryAvailable — the session exposes no `off` to detach the
DELIVERY_AVAILABLE listener) and DRAINS the in-flight delivery (awaits the
serial `processing` chain) before clearing state, so a turn settling at stop
time still sends its terminal signal instead of silently no-oping and
redelivering. Mirrors HttpDeliverySource.stop().
- Realtime nack() truncates the reason to 500 chars (parity with HTTP).
- getMessages drops empty content parts before join(" ") so a read_thread
transcript isn't corrupted with doubled/leading/trailing spaces (a test had
enshrined "part one part two").
- Removed dead imports (buildContentParts, AgentContentPart, ChannelFileRef)
left in http-transports.ts after the file/history extraction.
Deferred (delivery-contract / design; need coordination — folded into OSS-491):
timeout-nack can redeliver a still-running turnId (overlap); realtime push()
no-state fallback vs HTTP fail-loud (documented intentional — parity Q); the
empty-turn completion signal.
Tests: stop() drains in-flight + ignores post-stop deliveries; getMessages
assertion corrected. channels-intelligence 170 tests + check-types green.
Pre-merge 7-agent CR of #5983 surfaced several realtime-transport defects (all
in channels-intelligence). Fixes:
- Poison-payload re-lease loop: an unmappable delivery (unmodeled reply-target
adapter / unknown input.kind) with a valid lease was logged + dropped, so
app-api re-leased the identical payload forever. It now fails NON-retryable
(dead-letter), mirroring the HTTP path. nack() gains a `retryable` param.
- Double-terminal-signal race: realtime ack()/nack() deleted delivery state
AFTER the wire push, so a per-turn-timeout nack could race a late dispatch ack
and emit BOTH fail + complete_requested. Now delete-before-push (XOR).
- Concurrent dispatch: deliveries were handled fire-and-forget; now processed
serially (parity with the HTTP runLoop) so an in-flight redelivery can't reset
the shared per-turn seq counter or run two turns of one conversation at once.
- actor.displayName was carried through the claim mapper then dropped in
dispatchTo (`{ id }` only) — now forwarded to handlers (OSS-476 identity).
- fetchFile enforced MAX_INBOUND_FILE_BYTES only against declared content-length;
the actual read was unbounded. Now streams and aborts past the cap.
- getHistory returned the FULL history for limit<=0 (slice(-0)) and hydrated file
bytes for over-returned messages it then discarded. Now caps to the most recent
`limit` BEFORE hydrating; limit<=0 -> [].
- stream() posted an empty text frame for an empty stream; now skips the post.
- HTTP withTimeout/defaultSleep timers now unref() (parity with realtime).
- Corrected the inaccurate thread_started comment in claim-mapping.ts.
Deferred to OSS-491 (delivery-terminal-signal contract, needs app-api
coordination): an empty turn (reaction/command that posts nothing) has no valid
completion signal (acceptedThrough requires >=1) and redelivers; and the
run_error swallow on the HTTP-fallback render path.
Tests: poison non-retryable, single-terminal XOR, serial dispatch, displayName
forwarding, getHistory limit<=0 + cap. channels-intelligence 169 tests + check-types green.
The realtime-gateway transport had drifted from the HTTP transport: it built a
text-only ingress envelope that coerced commands/reactions/interactions into
empty turns, keyed conversations per-turn (breaking threaded follow-ups),
dropped the provider actor identity, and implemented none of
fetchFile/getHistory/uploadFile (so the realtime path silently ran with no
history and no file support). It also had no `delete` render kind. This brings
the realtime path to full parity with direct.
- claim-mapping: extract the claim→ingress mapping (ClaimedDelivery,
conversationKeyFromReplyTarget, mapDeliveryToEnvelope) into a shared module
both transports use, so they cannot drift again. Add the provider `actor` to
the claim turn and map it to `env.user` (fixes identity on BOTH paths).
- realtime transport: build the envelope via the shared mapper — real kind
discrimination, thread-stable conversationKey, actor→user — instead of the
text-only inline build. Fail-closed: an unmodeled reply-target/kind is
dropped+logged, not crashed.
- file/history: extract fetchFile/getHistory/uploadFile into a shared
IntelligenceFileHistoryClient (HTTP-only — the gateway never relays bytes or
history). The realtime transport gains them when configured with
`appApiBaseUrl` + `apiKey` (threaded through the launcher); absent that, the
methods stay undefined and the adapter degrades exactly as before.
- delete render kind: add `{ kind: "delete"; ref }` to ChannelRenderEvent
(mirrors the frozen Intelligence contract) and route thread.delete through a
render frame when a render sink is wired (OSS-420), like post/update/file.
Tests: shared-mapper unit tests (actor→user, kind discrimination,
conversationKey, unmodeled-adapter throw); realtime tests for non-text kind +
identity + thread-stable key and file/history capability toggling; a
delete-render-frame test. Full suite + check-types + build green.
Combines the two OSS-473 follow-ups (originally #5972 + #5973, now
folded here) into one PR for a single review/merge. Base is `main`
(OSS-473/#5963 has merged). Reviewable **commit-by-commit** — the
mechanical rename is isolated in commit 1; the behavior changes are
commits 2–4.
## Commit 1 — `refactor(channels)`: scrub residual internal "bot" naming
(closes OSS-485)
Mechanical, naming-only, **no behavior change** — the last internal
"bot" vestiges left out of 473's atomic telemetry-surface commit.
- `bot` local variable → `channel` in `create-channel.ts` internals +
the ~15 tests that exercise it.
- `BotNode` type → `ChannelNode` in `@copilotkit/channels-ui` and
**every** importer (channels,
slack/teams/discord/telegram/whatsapp/intelligence adapters, slack/teams
examples — 256 refs).
- `botName` adapter-SPI option → `channelName` on `AdapterStartContext`
+ its `create-channel` caller + the one consumer
(`IntelligenceAdapter.start` ctx), in one change so the SPI can't drift.
(Phoenix wire contract was already `channelName` as of 473.)
- Stale `bot-ui`/`bot-slack` comment refs →
`channels-ui`/`channels-slack`; `Symbol.for("copilotkit.bot-ui.*")` →
`"copilotkit.channels-ui.*"`.
- **Kept** (out of scope): the platform `isBot?` author flag (unrelated
semantic) and example `bot` instance vars / "demo bot" prose
(user-facing).
## Commits 2–4 — `fix`: realtime-transport reliability & parity
hardening (closes OSS-482)
The self-contained observability/robustness subset of the OSS-473 CR
follow-ups (`packages/channels-intelligence` transport +
`packages/runtime` manager). Each hardening ships with a test that fails
without the fix.
- **`emit()` fail-loud** (`intelligence-adapter.ts`) — returned a
synthetic `MessageRef` on `{ ok: false }`, acking a failed
post/update/delete as success (silent egress drop). Now throws → the
delivery is nacked/retried.
- **Realtime delivery dispatch** (`realtime-gateway-transport.ts`) — the
`void handleDeliveryAvailable(...)` fire-and-forget had no error
boundary and no deadline. Replaced with a `.catch` + a bounded per-turn
timeout that nacks + logs on failure/timeout (parity with the HTTP
`runLoop`).
- **`ChannelManager.stop()` per-handle timeout** — a wedged
`handle.stop()` hung teardown/SIGTERM forever. Each is now bounded by
`stopHandleTimeoutMs` (default 5000); on timeout it's logged and
abandoned so other entries still stop.
- **`ChannelManager.ready({ timeoutMs })`** — a set-wide timeout
discarded an erroring channel's reason when a sibling hung. The deadline
is now **per channel**, so the `AggregateError` carries both the real
activation error **and** a named timeout for each hanging channel.
- **Forward `ChannelManager` `log` down** to the launcher/transport so
transport-level drop diagnostics (e.g. a version-skew
missing-`leaseToken` outage) aren't silent in the managed path.
- **`examples/slack/.env.example`** — OpenAI-only `AGENT_MODEL`
guidance; removed never-read `ANTHROPIC_API_KEY`/`GOOGLE_API_KEY`;
blanked the presence-gated `LINEAR_API_KEY`/`NOTION_*` placeholders (a
non-blank value wires a broken MCP); documented `NOTION_MCP_PORT`; added
WhatsApp to the adapter list.
### Already landed in OSS-473 (not re-done here)
The reconnect **"gave-up → error" escalation** is fully implemented on
`main`: `realtime-gateway.ts` bounds the reconnect window
(`reconnectGiveUpMs`, default 60s) and emits a terminal `gave_up`; the
launcher exposes `onStateChange`;
`ChannelManager.registerConnectionObserver` maps `gave_up → error`
(covered by `realtime-gateway.test.ts` +
`channel-manager-reconnect.test.ts`).
### Explicitly EXCLUDED — owned by OSS-474 / OSS-476
Left untouched (overlap in-flight work): no cross-turn history on the
realtime path (per-turn `conversationKey`) → OSS-474/476; empty-turn
`ack()` redelivery livelock → OSS-474/475/476; non-text parity
(command/interaction/reaction) → OSS-476; `thread.delete()` render frame
→ OSS-476 (PR #554); durable StateStore on the managed realtime path →
OSS-474/476.
## Testing
- **DoD grep** — `grep -rn "\bbot\b\|botName\|BotNode" packages/channels
packages/channels-ui` (`.ts`/`.tsx`, excl. `dist/`) → **0**; `BotNode`
gone repo-wide.
- **check-types** green across all 8 channels packages +
`@copilotkit/runtime`.
- **tests** green: channels 155, channels-ui 23, slack 277, teams 88,
discord 193, telegram 149, whatsapp 73, channels-intelligence 144,
runtime `channel-manager` 40; slack-example 63, teams-example 2. Full CI
matrix (incl. `unit` 20.x/22.x/24.x) green on this branch.
- Each 482 hardening has a test that fails pre-fix (no silent ack;
dispatch nacks on throw/timeout; `stop()` resolves + logs on a wedged
handle; `ready()` aggregate preserves the real reason;
`defaultActivateChannel` forwards `log`).
Closes OSS-485. Closes OSS-482.
Two fixes from the pre-merge adversarial CR of this PR (both pre-existing,
flagged as in-subject):
- ChannelManager.status() reported overall "online" for a manager stopped
BEFORE activate() (e.g. SIGTERM during startup): `entries` is empty, so the
empty-set fold returned "online" — a torn-down manager reading healthy. Now
short-circuits to "stopped" when `this.stopped`, matching the documented
status() contract. New red-green test covers the stop()-before-activate() case.
- examples/slack/.env.example: COPILOTKIT_INTELLIGENCE_WS_URL example was
ws://localhost:4401, but derivation is a scheme-only swap of the :4201 API URL
(→ ws://localhost:4201) and 4401 is used nowhere — a user uncommenting it hit a
dead port. Corrected to :4201 and clarified the derivation note.
Three ChannelManager observability/robustness hardenings from the OSS-473 CR.
stop() per-handle timeout: stopEntry awaited handle.stop() unbounded, so a
wedged stop() (e.g. a socket.disconnect that never returns) hung teardown — and
thus SIGTERM shutdown — forever. Each handle.stop() is now bounded by
stopHandleTimeoutMs (default 5000); on timeout it is logged and abandoned so
every other entry still reaches `stopped`.
ready() surfaces the real reason on hang: ready({ timeoutMs }) wrapped the whole
`allSettled` in one timeout, so when one channel settled to `error` while a
sibling hung, it rejected with only a generic timeout and DISCARDED the erroring
channel's reason. The deadline is now applied PER CHANNEL, so the AggregateError
carries both each failed channel's real reason AND a named timeout for each
still-hanging channel.
Log forwarding: the manager's `log` reached activation-level events only; the
default engine (defaultActivateChannel → startChannelsOverRealtimeGateway) never
passed it down, so transport-level drop diagnostics (e.g. a version-skew
missing-leaseToken outage) were silent in the managed path. `log` is now
forwarded down to the launcher/transport.
Note: the reconnect "gave-up → error" escalation from the same CR is already
implemented end-to-end in OSS-473 (realtime-gateway.ts reconnectGiveUpMs +
ChannelManager.registerConnectionObserver) and is not re-done here.
Tests: stop() resolves + logs a timeout when handle.stop() never settles;
ready() aggregate contains both a real activation error and the hung sibling's
named timeout; defaultActivateChannel forwards its log sink to the launcher opts.
Two transport reliability hardenings on the managed realtime path, from the
OSS-473 CR.
emit() fail-loud: IntelligenceAdapter.emit() returned a synthetic MessageRef on
`{ ok: false }`, acking a failed post/update/delete as success (silent egress
drop on the HTTP-fallback path). It now throws with the failure code so the
failure propagates up the render/run path and the delivery is nacked/retried.
Realtime delivery dispatch: `session.on(delivery.available)` fired
`void this.handleDeliveryAvailable(...)` with no error boundary and no per-turn
deadline — an onDelivery rejection became an unhandled rejection (silent drop)
and a hung handler pinned the delivery forever. Replaced the `void` with a
`.catch` and wrapped the turn in a bounded per-turn timeout that nacks + logs on
failure/timeout (parity with the HTTP runLoop's turnTimeoutMs).
Tests: egress `{ ok: false }` makes thread.post throw (no silent ack); an
onDelivery throw and an onDelivery that exceeds deliveryTimeoutMs both nack
(channel.delivery.fail.v1) and log.
Follow-up to the OSS-473 clean-break rename (#5963). Scrubs the last
internal "bot" vestiges deliberately left out of 473's atomic
telemetry-surface commit. Naming-only, no behavior change.
- `bot` local variable → `channel` in create-channel.ts factory internals
and the ~15 test files that exercise it.
- `BotNode` type → `ChannelNode` in @copilotkit/channels-ui and every
importer (channels, slack/teams/discord/telegram/whatsapp/intelligence
adapters, and the slack/teams examples).
- `botName` adapter-SPI option → `channelName`: renamed on
AdapterStartContext, its create-channel caller, and the one adapter that
reads it (IntelligenceAdapter.start ctx) in the same change so the SPI
cannot drift. The Phoenix wire contract was already `channelName` (473).
- Stale `bot-ui`/`bot-slack` package refs and "bot core"/"the bot" prose in
channels/channels-ui comments → `channels-ui`/`channels-slack`/"channel".
- `Symbol.for("copilotkit.bot-ui.*")` → `"copilotkit.channels-ui.*"`.
Deliberately kept: the platform `isBot?` author flag (an unrelated
"is this message author a bot account" semantic), and example `bot`
instance variables / "demo bot" prose (user-facing, out of this ticket's
internal-symbol scope).
Validation: DoD grep returns zero internal bot symbols in
packages/channels + packages/channels-ui; check-types + test green across
all 8 channels packages (1093 tests) and both examples.
## Problem
On the managed Teams path the agent always reported "no earlier
messages" / "I don't see the image in this thread."
`HttpDeliverySource.getHistory` was **Slack-only**: it keyed off
`threadTs` and returned `[]` for any route without one. A Teams route is
`{ adapter: 'teams', tenantId, conversationId }` (no `threadTs`), so it
short-circuited *before making any request* — starving **both** history
mechanisms on Teams:
- `agent.messages` seeding (`conversationStore.getOrCreate`), and
- the `read_thread` tool (via `thread.getMessages()`).
## Fix
- **`getHistory` is now adapter-aware** (mirrors
`conversationKeyFromReplyTarget`'s per-adapter switch): Slack keys off
`teamId`/`channel`/`threadTs`; Teams sends `adapter=teams` + `tenantId`
+ `conversationId`, matching app-api's
`teams:{tenantId}:{conversationId}` thread_key. app-api's
`/api/channels/history` route already accepts this shape. **Slack query
and order are unchanged.**
- **Add `getMessages` to the adapter** so `thread.getMessages()` (the
`read_thread` tool) reads reconstructed history via the transport and
maps it to `ThreadMessage[]`. Without it `Thread.getMessages()` returns
`[]` and thread-reading tools (summaries, "what was in the image") see
nothing even when history exists.
## Tests
- New: Teams-shaped `getHistory` query, and the
missing-`tenantId`/`conversationId` short-circuit (no request).
- All 115 `channels-intelligence` tests pass; `check-types` clean.
## Notes
Verified end-to-end against a live managed Teams bot as a dist patch
before porting to source (history seeding + `read_thread` both start
returning the thread's messages). The app-api counterpart (Teams
ingress: reactions, inline-media/Graph file ingest, slash commands) is a
separate PR in the Intelligence repo.
Classify per-channel state on channel_declaration_unavailable rejects so a
runtime_conflict is a hard error rather than being downgraded to setup_required;
make gave_up recoverable (a later rejoin restores online); and route Phoenix
channel-level close/error through the same health transition as socket drops.
The PR's documented snippet — `await handler.channels.ready(...)` with no
`!`/`?.` — did not type-check under strict TS because
`createCopilotRuntimeHandler` always returned `channels?: ChannelsControl`.
Encode channel-presence at the type level:
- runtime.ts: `CopilotRuntime` is now a `const` typed as `CopilotRuntimeConstructor`
(backed by an internal `CopilotRuntimeShim` class; behavior unchanged). A
class constructor cannot vary its return type across overloads, so the two
construct-signature overloads live on the constructor interface: `intelligence`
+ a non-empty `channels` tuple returns a `RuntimeWithDeclaredChannels`-branded
runtime; every other config (SSE, intelligence-without-channels, empty
`channels: []`, or a non-literal `Channel[]` variable) stays unbranded. The
brand is a phantom (compile-time-only) property. `export interface CopilotRuntime`
preserves the name as a type for existing `runtime: CopilotRuntime` / `as
CopilotRuntime` sites.
- fetch-handler.ts: overload `createCopilotRuntimeHandler` — a branded runtime
(unless `activateChannels: false`, constrained to `true | undefined`) returns
the new `CopilotRuntimeFetchHandlerWithChannels` (non-optional `channels`);
everything else keeps the optional shape. Opting out of activation honestly
falls through to the optional overload.
- Added a compile-time type test (checked by `tsc --noEmit`, the `check-types`
gate). It probes the optionality modifier structurally (`{} extends Pick<T,K>`)
rather than for `undefined`, since this package compiles `strict: false`.
Confirmed it fails pre-change on the required-channels assertion and passes
after. Dropped the now-unnecessary `!` in handler-channels.test.ts.
Call sites: the second overload is byte-identical to the former single signature,
so every `createCopilotRuntimeHandler` caller (node/express/hono endpoints,
integration servers, examples) and every `new CopilotRuntime` site resolves
unchanged; only inline non-empty-`channels` construction gains the (strict
supertype-assignable) branded type. Verified via a clean full-package check-types.
P1#2 — reachable setup_required on the PRODUCTION engine path.
connectRealtimeGateway no longer flattens every join rejection into a
generic Error. A join `.receive("error", reason)` whose reason is a known
setup-required code (`channel_declaration_unavailable`, and defensively
`adapter_setup_required` / `not_configured`) now rejects with a
distinguishable `RealtimeGatewaySetupRequiredError` (`code === "SETUP_REQUIRED"`,
raw reason preserved). ChannelManager already detects that code, so an
unconfigured managed provider now degrades to `setup_required` (ready()
resolves) instead of `error`. All other reasons keep the generic error and
the socket-leak teardown is unchanged.
P1#3 — status() reflects real connection health instead of `online` forever.
ConnectedRealtimeGatewaySession exposes `onStateChange(cb)` over
`RealtimeGatewayConnectionState` (`online` | `reconnecting` | `gave_up`),
driven by the real Phoenix seams: an unexpected socket drop → `reconnecting`;
a successful (re)join (the join-push recHooks survive Phoenix `resend`, so
`"ok"` re-fires on every auto-rejoin) → `online`; and a BOUNDED give-up —
Phoenix retries forever, so a `reconnectGiveUpMs` window (default 60000, runs
from the first drop of an episode, cleared on rejoin) elapsing while still
reconnecting → `gave_up` (terminal). Our own disconnect() stays silent.
ChannelManager wires this in place of the log-only onClose breadcrumb:
`reconnecting`→status reconnecting, `online`→online, `gave_up`→error; a
stopped manager/entry ignores late events. computeOverall now ranks
`error > reconnecting > setup_required > connecting > online`. ready() keeps
its one-shot semantics (settles on the initial outcome); later health
transitions move only status(). Docs updated to state `online` means
currently-sendable.
Wording: the direct-adapter skip comment/log now states delivery is
exclusive-per-platform (managed OR direct per platform, not both — attaching
both would double-deliver) with true coexistence tracked in OSS-484. Skip
behavior unchanged.
Call-sites for the changed signatures:
- connectRealtimeGateway error shape: only caller is
startChannelsOverRealtimeGateway (realtime-gateway-launcher.ts:216); it
awaits and lets the rejection propagate, so the setup-required error flows
through unchanged (no branch to update).
- new ConnectedRealtimeGatewaySession.onStateChange: passed through in
startChannelsWithGatewaySession and startChannelsOverRealtimeGateway
(realtime-gateway-launcher.ts); added to ChannelsHandle (runtime.ts) and the
manager's local ChannelsHandle view (channel-manager.ts); exported from
index.ts. RealtimeGatewaySession (base, no observer) consumers
(realtime-gateway-transport.ts) unaffected.
- manager onClose→state transitions: registerOnClose renamed to
registerConnectionObserver; sole caller is the online settle handler in
activate().