Commit Graph

666 Commits

Author SHA1 Message Date
copilotkit-qa-bot[bot] f236329630 test(runtime): harden request auth isolation coverage 2026-09-01 08:39:00 -07:00
copilotkit-qa-bot[bot] 9c5a3ead46 Merge remote-tracking branch 'origin/main' into codex/fac-121-configurable-channels 2026-09-01 07:47:35 -07:00
Mike Ryan f3b1ef345b fix(integrations): standardize Intelligence project key name 2026-08-31 20:23:15 -07:00
copilotkit-qa-bot[bot] e55c6f7b41 test(runtime): cover repeated request auth isolation 2026-08-31 15:09:09 -07:00
maxkorp 3a64564508 chore: release monorepo v1.70.0 2026-08-31 19:34:27 +00:00
Maximiliano Korp cd7748f25b fix(runtime): harden entitlement resolution 2026-08-31 10:46:15 -07:00
Maximiliano Korp b7ca2d027d test(telemetry): align managed identity metadata assertions 2026-08-31 10:46:15 -07:00
Maximiliano Korp 714daf8949 fix(runtime): scope channel connection telemetry 2026-08-31 10:46:14 -07:00
Mike Ryan 88567315c7 docs(runtime): standardize Intelligence project key name 2026-08-31 10:46:13 -07:00
Mike Ryan 5c50ba4abe fix(runtime): repair V1 telemetry imports after move 2026-08-31 10:46:13 -07:00
Mike Ryan 0a99ef580a fix(runtime): restore managed authority contracts 2026-08-31 10:46:13 -07:00
Mike Ryan 210c9a0138 fix(runtime): accept App API entitlement responses 2026-08-31 10:46:12 -07:00
Mike Ryan f1ac08938a feat(runtime): use managed Intelligence authority 2026-08-31 10:46:12 -07:00
Tyler Slaton d477ca7396 chore: merge main into AG-UI dependency bump 2026-08-31 09:26:33 -07:00
Mike Ryan 9e27e10830 feat(runtime): expose Learning Container selector 2026-08-28 10:17:27 -07:00
Markus Ecker 71d9731d45 chore(deps): bump @ag-ui/* to 0.0.59
Moves the published packages from 0.0.57 to the current AG-UI release across
@ag-ui/client, core, encoder and proto — 27 declarations in 18 packages.

0.0.59 is the first release carrying the subagent protocol surface
(SUBAGENT_STARTED/FINISHED/ERROR, subagentRunId) along with the null-omission
cleanup, so this is the dependency CopilotKit's subagent work needs.

Scope is packages/** plus the release script noted below. The examples and
showcases sit on a spread of older pins (0.0.40 through 0.0.58) and are left
alone.

One behavioural change comes with the bump. channels-core ships
sanitizeAgentEventStream because @ag-ui/client used to reject a TOOL_CALL_START
carrying parentMessageId: null — the shape @ag-ui/langgraph emits for an
interrupt-triggering tool call. 0.0.59 accepts that null and treats it as
absent, so the two tests asserting the run dies WITHOUT the sanitizer no longer
hold. They now assert the run survives, and the one at agent level still checks
the tool call actually arrives so it cannot pass vacuously. The sanitizer is
untouched and its coercion tests are unchanged; it is simply no longer the
thing keeping such a run alive.

The bump also broke the packed Angular consumer matrix. That job generates a
smoke app from scripts/release/lib/angular-package.ts, whose manifest restated
"@ag-ui/client": "0.0.57" as a literal while packages/angular moved to 0.0.59.
pnpm then installed both copies and the app failed to compile:

  TS2322: Type 'SmokeAgent' is not assignable to type 'AbstractAgent'.
    Types have separate declarations of a private property '_debug'.

The smoke app imports AbstractAgent directly, so it has to resolve the identical
copy the library ships against. Read that version off the packed manifest --
which verify-angular-package.ts already parses for the Angular support contract
-- instead of restating it, so no future AG-UI bump can desynchronise it.
2026-08-28 16:18:52 +02:00
Benjamin Taylor 6ccff843c7 fix(telemetry): stamp sampling metadata and emitter markers on every event
The v2 runtime client gated anonymous events at 5% and let identified
callers through at 100%, then sent without recording which branch the
event took. A quarter of runtime volume — 24.4% in August and roughly
doubling each month — arrived carrying no record of its own sampling, so
it could not be weighted from the data alone. Downstream had to hardcode
a x20 assumption, which both understates real volume and overstates
growth as the sampled/unsampled mix drifts.

Extract the v1 client's sampling block into shared/telemetry/sampling so
the two clients cannot drift again, and call it from both. Identified
events weigh 1, anonymous ones 1/sampleRate.

Carry telemetry_identified explicitly rather than letting consumers infer
identity from sampleWeight === 1: under COPILOTKIT_TELEMETRY_SAMPLE_RATE=1
anonymous events also weigh 1 and the two populations stop being
distinguishable.

The v1 client also sends every capture to both Segment and the lambda
sink, so one request produces two rows with nothing marking them as
copies. Stamp telemetry_emitter, telemetry_transport, and a per-capture
telemetry_event_id shared by both copies, making the dedupe explicit
instead of inferred from $lib. Both transports keep flowing.

Refs OSS-1017, OSS-1018, OSS-1019

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 17:20:34 -05:00
MikeRyanDev 8617f5b76b chore: release monorepo v1.69.3 2026-08-27 16:47:48 +00:00
Maximiliano Korp eeb01fc33f fix(runtime): keep thread naming task after transcript 2026-08-26 11:28:30 -07:00
David McKay b4145f42fc fix(runtime): stop reporting every connect failure as a 404 (closes OSS-971)
The Intelligence connect handler classified a handful of platform rejections and
flattened everything else into HTTP 404 "Connect plan not available", writing the
real cause only to server-side stderr.

That made every unrecognised failure look like a missing thread. A 500 from
app-api, a socket timeout, a connection reset and a bug in our own code all
produced the same misleading answer, and the only way to find out what actually
happened was to read the runtime container's logs.

It cost a customer a day. Their Redis filled, app-api returned 500 on a
join-code write, and their engineer saw a 404 naming a "connect plan" that had
nothing to do with the failure. The platform was up and the request was
retryable; the reported status said neither.

Now:

  - a status we already special-case (400, 401, 403, 404, 409) still reports as
    a rejection with its message, unchanged;
  - any other status from the platform passes through as itself, so a 503 stays
    a 503 and the caller knows to retry; and
  - an error carrying no status never reached the platform, so it reports 502
    rather than 404, which says "the thing behind me is unreachable" instead of
    asserting the thread does not exist.

Every branch now returns the underlying message rather than burying it in a log
line the caller cannot see.

The SSE run path in handlers/shared/sse-response.ts has the same shape and is not
addressed here: it returns 200 and text/event-stream before the run starts, so a
later throw closes the stream with no events and no error frame. That needs its
own change to the streaming contract.
2026-08-26 07:55:31 -07:00
tylerslaton 9629e930d1 chore: release monorepo v1.69.2 2026-08-26 00:18:42 +00:00
Benjamin Taylor b8283ef4e1 refactor(scripts): match dead hosts case-insensitively, carry each reason with its host
DNS is case-insensitive, so a capitalized host in prose would have slipped the
literal match. Env var names stay case-sensitive — `ignoreCase` is opt-in per
rule. The per-host reason moves onto the constant so adding a third host cannot
silently inherit the wrong message.

Also restores the TSDoc's original framing of what an override is for
("non-production or future self-hosted"), matching the runtime skill's wording
rather than diverging from it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 15:45:27 -05:00
Benjamin Taylor b057744684 fix(docs): stop shipping stale Intelligence config claims, and gate the dead hosts (refs OSS-961)
The packaged runtime skill up to v1.62.2 prescribed `api.copilotkit.ai` /
`realtime.copilotkit.ai`. The first host is a CNAME onto the legacy Copilot
Cloud ALB, where no listener rule matches it, so every request gets the ALB
default action: a 404 with an empty body. The second has no DNS record at all.
A reader who followed that page converted a working OSS install into a 502.

The hosts themselves were corrected in v1.64.0, but two shipped surfaces still
carried stale claims about the same step, and nothing stopped the hosts from
coming back a third time:

- The debug skill said Intelligence "requires ... `apiUrl`, `wsUrl`, `apiKey`,
  `tenantId`". Three errors in one line: `apiUrl`/`wsUrl` have been optional
  with managed defaults since v1.64.0, and `tenantId` has never existed on
  `CopilotKitIntelligenceConfig` — the API key carries the project (its token
  format is `cpk-{projectId}_...`) and the platform resolves the organization
  server-side, so there is no org or tenant field for a caller to pass.
- `CopilotKitIntelligence`'s own TSDoc showed only `*.internal` placeholders,
  so the class's hover docs never named the pair that actually serves prod.

`validate-intelligence-env-names` — already the unfiltered guard for this same
config surface (OSS-881) — now also fails on either dead host. The
channels-intelligence realtime test is allowlisted: it needs a hostname that
genuinely does not resolve, since `getaddrinfo ENOTFOUND` is the condition
under test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 15:35:55 -05:00
MikeRyanDev 6053e4e262 chore: release monorepo v1.69.1 2026-08-25 18:50:37 +00:00
Ben Taylor d85b0b5db9 fix(runtime): reject runner passed alongside intelligence (closes OSS-933) (#6670)
## Problem

`runner` and `intelligence` are mutually exclusive by construction, but
the exclusivity was enforced in only one direction and only for object
literals.

`CopilotIntelligenceRuntime` hardcodes `new
IntelligenceAgentRunner(...)` into its `super()` call
(`runtime.ts:582`), and `runner?` is declared only on
`CopilotSseRuntimeOptions` (`runtime.ts:239`). The type system catches a
`runner:` key on an Intelligence-shaped **object literal** via
excess-property checking — but that is the only barrier. A JS caller, an
`as any`, or a non-literal options object routes through
`CopilotRuntimeShim`'s `hasIntelligenceOptions()` dispatch into the
Intelligence constructor and has `runner` **silently dropped**, with no
diagnostic.

The mirror case is already guarded: `CopilotSseRuntime` throws on
`channels`, and the comment there states the exact reasoning that
applies here — "the type forbids it, but a JS / `as any` caller ...
would otherwise land here and have `channels` silently dropped — fail
loud instead." The Intelligence constructor validates `identifyUser`,
`channels`, `memory`, and `ɵlearning`. Same file, same pattern, one case
missing.

### It also made a shipped skill lie

`packages/runtime/skills/runtime/SKILL.md:87` asserted:

> Passing both `runner` and `intelligence` to `CopilotRuntime` is
rejected at construction.

It was not. And that contradicted the skill's own reference page,
`references/agent-runners.md`, which correctly described the silent
drop. Two files in the same shipped skill said opposite things about the
same behaviour.

## Change

- **Guard** (`runtime.ts:512`) — `CopilotIntelligenceRuntime` now throws
when `runner` is present, mirroring the `channels` guard in
`CopilotSseRuntime`. The message names the exclusivity and points out
that an in-memory/SQLite runner is unnecessary in Intelligence mode,
where durability is managed by the service.
- **`SKILL.md:87` unchanged** — the guard makes it accurate.
- **`references/agent-runners.md` updated** — this is *not* optional.
That page was the accurate one before this change; adding the guard
makes its "the auto-wired Intelligence runner wins regardless of what
you pass" false. Leaving it would fix SKILL.md's lie by creating the
same lie in the reference — rotating the contradiction rather than
resolving it. Its stale `:149-173,285-294` source citation is corrected
to the real line numbers too. Root `skills/` mirror regenerated via
`pnpm sync:plugin-skills`.

## Behavior notes

- Explicit `runner: undefined` still constructs. This matches how the
sibling `identifyUser` / `channels` / `memory` guards treat `undefined`,
and avoids breaking callers that spread an options object.
- The v1 deprecated compat path is unaffected:
`copilot-runtime.ts:492-509` already omits `runner` from its
Intelligence branch, so nothing routes a `runner` into this constructor
from v1.

## Tests

Two tests in `channels-option.test.ts`, alongside the existing `sse
runtime rejects channels` mirror:

- `intelligence runtime rejects a caller-supplied runner` — written
first and confirmed **red** against the unpatched constructor
(`AssertionError: expected [Function] to throw an error`), green after.
- `intelligence runtime tolerates an explicitly undefined runner` — pins
the undefined-tolerance above so the guard cannot over-throw.

## Verification

| Gate | Result |
|---|---|
| `nx test @copilotkit/runtime` | 144 files, **2080 passed, 0 failed** |
| `nx check-types @copilotkit/runtime` | Successfully ran (+22 deps) |
| `oxlint` (changed files) | 0 warnings, 0 errors |
| `oxfmt --check` | no issues in changed files |
| lefthook pre-commit + commit-msg | all green |

Closes OSS-933.
2026-08-25 08:22:06 -05:00
Mike Ryan db88826432 chore: rename Enterprise Intelligence product copy 2026-08-24 09:38:15 -07:00
Ben Taylor 0943c5196e fix(runtime): make published declarations resolvable for consumers (#6674)
Closes the remaining half of OSS-899.

PR #6644 removed the `require("reflect-metadata")` banner from the
published
`.d.cts` files, taking a bare strict-mode `import { CopilotRuntime }`
from 81
errors to 10. This takes it to **1**, and that one is not ours.

## Result

Measured by overlaying the built `dist` onto a real consumer install of
1.69.0
and typechecking a bare import under `strict` + `skipLibCheck: false`:

| entry point | before | after |
| -- | --: | --: |
| `@copilotkit/runtime` | 10 | **1** |
| `/v2` | 1 | **1** |
| `/v2/express` | 1 | **1** |
| `/v2/hono` | 1 | **1** |
| `/v2/node` | 1 | **1** |
| `/langgraph` | 7 | **6** |

The single remaining error on every entry point is the same one, and it
is in a
third-party package — see "Not fixed here" below.

## The gate

`scripts/validate-dts-imports.ts` is the companion to
`validate-dts-ambient.ts`.
That one checks the *shape* of published declarations; this one checks
what they
*reach for*, against a single invariant:

> Every module a published `.d.ts` imports must be resolvable by someone
who
> installed this package and nothing else.

It flags devDependencies, optional peers, dependencies whose types live
in a
devDependency `@types/*`, relative imports of JS-only bundler chunks,
and an
explicit ban on `graphql-yoga`. It started red on 18 violations and is
now clean
on all 175 declaration files. Wired into the existing `check-dts`
target, so it
runs in `check:packages` and `static_quality.yml`.

It caught two problems the typecheck probe missed, because they happened
to
hoist in that particular install: `@whatwg-node/server` and
`@langchain/langgraph-sdk`.

## The fixes

- **`graphql-yoga` (5× TS2416)** — `GraphQLContext` was
`YogaInitialContext & {...}`.
That one reference pulled the Yoga barrel into every consumer program,
and with
it `lru-cache@10`, whose `implements Map` clause is what actually
errors.
Declared locally instead; structurally identical, so a real Yoga context
still
satisfies it. Nothing in this package serves GraphQL any more — every v1
  integration entry point delegates to the v2 Hono endpoint.
- **`@copilotkit/channels` (1× TS7016)** — a devDependency and a pure
re-export of
`channels-core`, so tsdown inlined its prebuilt declarations plus a
rolldown
helper chunk that ships JavaScript only. Types now come from
`channels-core`,
  which is a real dependency and stays external.
- **`cors` / `express` (1× TS7016)** — public declarations use their
types, but both
  `@types` packages were devDependencies. Promoted to dependencies.
- **`@anthropic-ai/sdk` / `groq-sdk` (2× TS2307)** — optional peers
named in exported
signatures. Params and getters now use `SdkClientLike`, a structural
type a real
client satisfies; the SDK types stay at the two call sites that need
them, inside
  function bodies where they are never emitted.
- **`@langchain/langgraph-sdk`** — was deep-importing
`dist/types.messages`, an
internal file of an optional peer. Now derived from the base class
signature in
  `@ag-ui/langgraph`, a real dependency.
- **`@whatwg-node/server`** — an `export type {}` workaround for
microsoft/TypeScript#42873 whose own comment said it was waiting on
TypeScript
  5.5. We are on 5.9.2 and it typechecks without it.

## Not fixed here

**1× TS2694** — `@copilotkit/license-verifier@0.5.0` references zod's
`core`
namespace, which only exists in zod v4; this package pins `zod ^3.23.3`.
It is an
external package (0.5.0 is the latest published), so the fix is either a
license-verifier release or migrating this package to zod v4. Both are
larger than
this PR and deserve their own ticket.

Also unchanged: the 6 remaining `/langgraph` errors, all inside
`@ag-ui/langgraph`,
`@langchain/core`, and `@langchain/langgraph-sdk`. The `TS2416` on `run`
is present
identically in pristine 1.69.0 — it is downstream of
`@ag-ui/langgraph`'s own
unresolvable deep imports, not something this branch introduced.

## Reviewer note

The `SdkClientLike` swap narrows `adapter.anthropic` and `adapter.groq`
for anyone
reaching past `baseURL` and `apiKey`. Both adapters are v1-deprecated,
and the
alternative is a type error for every consumer who does not install
those optional
peers — but it is a public-surface change and worth a second opinion.

## Verification

- `nx test runtime` — 2078 tests, 144 files, all passing
- `nx build runtime` + `npm run check-dts` — both validators clean on
175 files
- `tsc --noEmit` on the package — clean

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-24 11:21:34 -05:00
Benjamin Taylor cbe6a81ff4 fix(runtime): keep optional peer SDK types off the published surface
@anthropic-ai/sdk and groq-sdk are optional peers, so a consumer who never uses
those adapters does not install them -- yet both were named in exported
signatures, which is a TS2307 on a bare `import { CopilotRuntime }`. The
LangGraph agent had a third case, and a worse one: it deep-imported
@langchain/langgraph-sdk/dist/types.messages, an internal file of an optional
peer.

The adapter params and getters now use SdkClientLike, a structural type a real
Anthropic or Groq instance satisfies. The SDK types stay for the two call sites
that need them, inside function bodies where they are never emitted. The
LangGraph message type is derived from the base class signature in
@ag-ui/langgraph, which is a real dependency.

Narrows adapter.anthropic and adapter.groq for anyone reaching past baseURL and
apiKey. Both adapters are v1-deprecated and the alternative is a type error for
every consumer.
2026-08-24 10:39:37 -05:00
Benjamin Taylor 1d9f19713a fix(runtime): ship the @types packages our public declarations depend on
dist/v2/runtime/endpoints/express.d.cts imports types from `cors` and `express`.
Neither ships its own declarations, and both @types packages were devDependencies,
so whether a consumer resolved them came down to whether something else in their
tree happened to hoist them.

Moving them to dependencies makes the published types self-contained.
2026-08-24 10:38:17 -05:00
Benjamin Taylor 3755a227d5 fix(runtime): drop the obsolete @whatwg-node/server type workaround
`export type {} from "@whatwg-node/server"` worked around microsoft/TypeScript#42873
and its own comment says it was waiting on the TypeScript 5.5 stable release.
The repo is on 5.9.2 and typechecks without it.

It was reaching a devDependency, so it emitted an import of a module consumers
never install.
2026-08-24 10:37:51 -05:00
Benjamin Taylor d81e7db63e fix(runtime): take channel types from channels-core, not the channels shim
@copilotkit/channels is a devDependency and a pure re-export of
@copilotkit/channels-core, so tsdown treated it as bundleable and inlined its
prebuilt declarations into dist/channels/dist/index.d.cts -- along with a
rolldown helper chunk that ships JavaScript only. Consumers got a TS7016 for a
file they cannot see.

channels-core is a real dependency and stays external, so importing the types
from there drops the inlined copy entirely.
2026-08-24 10:37:48 -05:00
Benjamin Taylor 2fa1bea289 fix(runtime): stop shipping graphql-yoga types to consumers
GraphQLContext was defined as `YogaInitialContext & {...}`. That single type
reference pulled the whole graphql-yoga barrel into every consumer's program,
and with it lru-cache@10, whose `implements Map` clause costs five TS2416
errors under strict + skipLibCheck: false.

Nothing in this package serves GraphQL any more -- every v1 integration entry
point delegates to the v2 Hono endpoint -- so the type is declared locally
instead. It is structurally identical, so a real Yoga context still satisfies it.
2026-08-24 10:36:46 -05:00
Benjamin Taylor 996ac76a24 test(runtime): gate published declarations on consumer-resolvable imports
OSS-899 shipped 81 strict-mode errors to consumers because nothing checked what
the published .d.cts files reach for. validate-dts-ambient.ts checks their shape;
this checks their imports against the one thing that matters -- whether someone
who installed this package and nothing else can resolve them.

Flags devDependencies, optional peers, dependencies whose types live in a
devDependency @types package, relative imports of JS-only bundler chunks, and an
explicit ban on graphql-yoga, whose types drag lru-cache@10 into every consumer
program. Currently red on 18 real violations; the fixes follow.
2026-08-24 10:27:25 -05:00
Benjamin Taylor 59b0476e67 docs(integrations): wire quickstart runtimes to Intelligence (closes OSS-932)
Twelve quickstarts provisioned a license key in step 1 and then showed a
runtime constructed with `runner: new InMemoryAgentRunner()` — an option
that is mutually exclusive with `intelligence`, so the key was never read.
Threads showed "locked" and nothing indicated a choice had been made.

Each of those pages now constructs the runtime with `intelligence` and
`identifyUser`, names `INTELLIGENCE_API_KEY` where the route reads it, and
links /premium/connect-your-runtime — which had no inbound link from any
quickstart. The in-memory runner stays available as a labelled opt-out;
it was already the default, so passing it explicitly only added the steer.

Also adds the required `name` field to the `identifyUser` snippets in
connect-your-runtime.mdx and the runtime skill's agent-runners reference.
Both omitted it, so copying either was a type error.

Scope is every page that provisions a key and then shows a runtime that
cannot consume it. Pages that legitimately document the in-memory runner
(backend/agent-runner, deploy/agentcore) are unchanged.

Verified: all 15 doctest `component` snippets typecheck against the pinned
@copilotkit/runtime@1.68.3, and the gate goes red when `name` is removed.
2026-08-24 08:48:59 -05:00
Benjamin Taylor 4a50c4c97c fix(runtime): reject runner passed alongside intelligence (closes OSS-933)
`CopilotIntelligenceRuntime` hardcodes `IntelligenceAgentRunner` into its
`super()` call, so a caller-supplied `runner` could never be honored. The type
forbids it — `runner` is declared only on `CopilotSseRuntimeOptions` — but that
is an excess-property check: a JS, `as any`, or non-literal caller passing
`{ intelligence, runner }` reached the constructor and had `runner` silently
dropped with no diagnostic.

Add the runtime guard, mirroring the `channels` guard already in
`CopilotSseRuntime` for exactly this reason. Explicit `runner: undefined` still
constructs, matching how the sibling `identifyUser` / `channels` / `memory`
guards treat undefined.

This also resolves a contradiction inside the shipped runtime skill:
`SKILL.md:87` already asserted the rejection happens at construction, while
`references/agent-runners.md` correctly described the silent drop. The guard
makes SKILL.md true; agent-runners.md is updated to describe the throw and to
cite line numbers that match the current file.
2026-08-24 08:31:33 -05:00
Atai Barkai e1631bb308 fix(runtime): gate v1 layout after dual-format builds 2026-08-21 16:51:17 -07:00
Atai Barkai 6058316e8c fix(deprecation): validate v1 folder transition 2026-08-21 16:51:17 -07:00
Atai Barkai e499c65dce refactor(deprecation): isolate v1 under deprecated source boundaries 2026-08-21 16:51:17 -07:00
Atai Barkai 7ee91c8d28 fix(deprecation): link related v2 migration concepts 2026-08-21 16:50:46 -07:00
Atai Barkai c40d1b15b4 chore(deprecation): remove redundant v1 source paths 2026-08-21 16:50:45 -07:00
Atai Barkai 7aa6639687 chore(deprecation): keep v1 notice diff focused 2026-08-21 16:50:45 -07:00
Atai Barkai be7427eab5 chore(deprecation): direct every v1 export to v2 2026-08-21 16:50:45 -07:00
Atai Barkai 0c0ddfe9f9 fix(deprecation): show v2 usage in IDE warnings 2026-08-21 16:50:45 -07:00
Atai Barkai d7ccfd3977 fix(deprecation): warn v1 users to use v2 in IDEs 2026-08-21 16:50:45 -07:00
Atai Barkai 06a461ee95 fix(deprecation): direct v1 users to v2 everywhere 2026-08-21 16:50:45 -07:00
Atai Barkai 19c65b23cb fix(deprecation): use file-specific v2 paths 2026-08-21 16:50:45 -07:00
Atai Barkai 08b89de667 chore: add v1 SDK deprecation pilot 2026-08-21 16:50:45 -07:00
MikeRyanDev 71977ddfce chore: release monorepo v1.69.0 2026-08-21 18:09:45 +00:00
Mike Ryan 6b9aadf025 fix(runtime): stop emitting a require() statement in published .d.cts (#6644)
Fixes the part of OSS-899 that is hard to defend: every `.d.cts` file we
publish from `@copilotkit/runtime` starts with a `require()` call.

## The bug

A consumer whose only source file is `import { CopilotRuntime } from
"@copilotkit/runtime";`, compiled with `strict` and `skipLibCheck:
false`, gets **81 errors** on a bare install of 1.68.3. **71 of them are
`TS1036` "Statements are not allowed in ambient contexts"**, raised
inside our own shipped declarations.

Cause is in `packages/runtime/tsdown.config.ts`. The banner that
guarantees `reflect-metadata` loads before `type-graphql` was returned
as a **string**. tsdown's `resolveChunkAddon` routes an *object* return
by chunk kind (`js` / `dts` / `css`) but applies a *string* return to
**every** emitted chunk — declarations included. So all 87 published
`.d.cts` files began:

```ts
require("reflect-metadata");
import { CopilotRuntimeLogger, ... } from "./lib/logger.cjs";
```

A `require()` call is a statement, and a `.d.ts` is an ambient context.
One error per file.

Two reasons this went unnoticed for so long:

- Every scaffolder sets `skipLibCheck: true`. Verified in genuine `ng
new` and `create-next-app` output. A developer who scaffolds normally
never sees it.
- The `.d.mts` flavour got `import "reflect-metadata";`, which is a
legal side-effect import in a declaration file. **ESM-resolving
consumers saw zero `TS1036`.** Only CJS resolution is affected.

## The fix

Return an object so tsdown routes by chunk kind — JS keeps its
`reflect-metadata` prologue, declarations get nothing.

The `fileName.includes("_virtual/_rolldown/runtime")` condition is
dropped as well, and that is the more interesting half.
`resolveChunkAddon` reassigns its own closure variable on the first
call:

```js
if (typeof chunkAddon === "function") chunkAddon = chunkAddon({ format, fileName: chunk.fileName });
```

so a function banner is evaluated **once** and its result reused for
every later chunk. The old config's comment ("propagates to all output
files per format") described that as intended behaviour, but it was
really a condition deciding the banner for the entire build based on
whichever chunk happened to be emitted first. Keying on `format` alone —
fixed per build — is order-independent.

The object form is tsdown's declared API, not a workaround:
`ChunkAddonFunction` returns `ChunkAddonObject | string | undefined`
where `ChunkAddonObject` is `{ js?, css?, dts? }`. `tsc --noEmit
--strict` on `tsdown.config.ts` against tsdown's own types is clean —
worth stating because the config is in no tsconfig `include`, so nothing
else typechecks it.

## The guard

`scripts/validate-dts-ambient.ts` parses each built declaration with the
TypeScript compiler API and fails on any top-level node that is not a
declaration, import, or export. Wired as a `check-dts` nx target shaped
exactly like the existing `publint` / `attw` / `compat-check` targets
(`dependsOn: ["build"]`, `inputs` on `dist/**`), and folded into the
`check:packages` script that the `package-quality` CI job already runs.
That job already builds runtime for `publint`, so the added cost is one
177-file parse.

Only `@copilotkit/runtime` opts in, because it is the only offender.
Running the validator itself over the built declarations of all 32
packages: **87 of runtime's 177** bad on the published 1.68.3 artifact,
and **0** in every other package. Others can opt in with the same
one-line script.

## Testing

**1. Reproduce the reported defect on the published package.** Bare `npm
install @copilotkit/runtime@1.68.3 typescript`, `probe.ts` importing
only `CopilotRuntime`, tsconfig with `strict`, `skipLibCheck: false`,
`module`/`moduleResolution` `nodenext`:

```
$ npx tsc --noEmit ; echo exit=$?
exit=1
$ grep -oE 'error TS[0-9]+' tsc.out | sort | uniq -c | sort -rn
  71 error TS1036
   5 error TS2416
   2 error TS7016
   2 error TS2307
   1 error TS2694
```

81 errors, matching the issue. All 71 `TS1036` are at line 1, column 1
of a `.d.cts`.

**2. Confirm the mechanism.** Every published declaration's first line,
before the fix:

```
-- *.d.cts --  total: 87
  87 require("reflect-metadata");
-- *.d.mts --  total: 90
  90 import "reflect-metadata";
```

**3. Same probe across every public subpath, before and after.** Built
`packages/runtime` at 1.68.3 with this change and swapped the result
into the probe's `node_modules`. `total` is all errors; `1036` is the
subset this PR addresses.

| subpath | CJS before | CJS after | ESM before | ESM after |
| --- | --- | --- | --- | --- |
| `@copilotkit/runtime` | 81 (71×1036) | **10** (0) | 10 (0) | 10 (0) |
| `/v2` | 32 (29×1036) | **3** (0) | 3 (0) | 3 (0) |
| `/langgraph` | 15 (4×1036) | **7** (0) | 7 (0) | 7 (0) |
| `/v2/express` | 21 (18×1036) | **3** (0) | 3 (0) | 3 (0) |
| `/v2/hono` | 21 (19×1036) | **2** (0) | 2 (0) | 2 (0) |
| `/v2/node` | 22 (20×1036) | **2** (0) | 2 (0) | 2 (0) |

Zero `TS1036` on every subpath in both module modes, and **after the fix
each subpath's CJS count equals its ESM count** — the CJS-only penalty
is gone and nothing else moved. Every ESM column is untouched, which is
the expected result since `.d.mts` never carried the bad banner.

The errors that remain are the separate items catalogued on OSS-899
(optional-peer SDK types, `@types/cors`, a `lru-cache` variance error
from `graphql-yoga`, a zod namespace skew in
`@copilotkit/license-verifier`) and are not touched here.

**4. `reflect-metadata` still runs first in every JS output.** This is
what the banner exists for, so it is the thing most at risk from the
change:

```
cjs files with require("reflect-metadata") as line 1: 131  / total 131
mjs files with import "reflect-metadata" as line 1: 132  / total 132
```

**5. Nothing but the banner line changed.** Diffed every one of the 87
built `.d.cts` files against the published 1.68.3 artifact from line 2
onward. Exactly one file differs, and it is unrelated source drift — a
JSDoc env-var rename from `6f58b2c6a4` (`COPILOTKIT_API_KEY` →
`INTELLIGENCE_API_KEY`, refs OSS-881) that landed on main after 1.68.3
shipped. Line counts are also identical, so declaration sourcemaps do
not shift.

The `_virtual/_rolldown` reference count in declarations is 2 before and
2 after — that item is deliberately out of scope here.

**6. The guard catches the regression it exists for.** Reverted the
banner to its pre-fix string form, rebuilt, and ran the new target:

```
$ pnpm exec tsx ../../scripts/validate-dts-ambient.ts dist
Found 87 statement(s) in published declarations.
A .d.ts is an ambient context: only declarations, imports, and exports are
allowed. Each of these is a TS1036 error for consumers on skipLibCheck: false.

  dist/agent/converters/aisdk.d.cts:1  require("reflect-metadata");
  ...
exit=1
```

Restored the fix and rebuilt:

```
$ pnpm exec tsx ../../scripts/validate-dts-ambient.ts dist
validate-dts-ambient: dist clean (177 files).
exit=0
```

**7. Validator unit tests, mutation-checked.**
`scripts/__tests__/validate-dts-ambient.test.ts`, 7 tests covering the
exact OSS-899 banner, the legal ESM form, every declaration form a real
`.d.ts` uses, line-number reporting, and ignoring sibling `.cjs`/`.map`
files.

```
 Test Files  1 passed (1)
      Tests  7 passed (7)
```

Then broke the mechanism three ways to confirm the tests are not
self-fulfilling:

| mutation | result |
|---|---|
| allow `ExpressionStatement` in the kind allowlist | 2 failed / 5
passed |
| drop the `line + 1` conversion | 2 failed / 5 passed |
| scan only `.d.ts`, not `.d.mts` / `.d.cts` | 3 failed / 4 passed |
| restored | 7 passed |

**8. Runtime suite and packaging targets, on a clean `pnpm install
--frozen-lockfile` in this worktree.**

```
$ nx run @copilotkit/runtime:test
 Test Files  143 passed (143)
      Tests  2073 passed (2073)

$ nx run-many -t publint,attw,check-dts --projects=@copilotkit/runtime
NX   Successfully ran targets publint, attw, check-dts for project @copilotkit/runtime
```

`attw --profile node16` reports 🟢 from both CJS and ESM; the `node10`
failure is pre-existing and ignored by the profile.

**9. Formatting and types.** `oxfmt --check` clean on all three source
files; `tsc --noEmit --strict` clean on the new script.

## Overlap with #6476

#6476 (`adopt TypeScript 7 and tsdown 0.22`) bumps tsdown to 0.22.14 but
does **not** touch `packages/runtime/tsdown.config.ts`, so it does not
fix this. The two PRs conflict only textually — both add lines to
runtime's `scripts` block and to the root `package.json`. This fix uses
tsdown's documented object-banner form, so it holds whether or not 0.22
changed `resolveChunkAddon`'s memoization.

No changeset: this ships through the normal release scopes.
2026-08-21 10:44:36 -07:00
Benjamin Taylor 8951232a0f fix(runtime): stop emitting a require() statement in published .d.cts
A consumer who imports @copilotkit/runtime and compiles with strict +
skipLibCheck: false gets 81 errors from our published declarations, 71 of
them TS1036 "Statements are not allowed in ambient contexts". Cause: the
tsdown banner that guarantees reflect-metadata loads before type-graphql
was returned as a string, and tsdown applies a string banner to every
emitted chunk -- declarations included. So all 87 published .d.cts files
began with `require("reflect-metadata");`, which is a statement and
illegal in an ambient context.

Returning an object instead lets tsdown route the banner by chunk kind, so
JS keeps its reflect-metadata prologue and declarations get nothing. The
fileName condition is gone too: tsdown's resolveChunkAddon reassigns its
own closure variable on the first call, so a function banner is evaluated
once and reused, meaning that condition was really deciding the banner for
the entire build from whichever chunk was emitted first. Keying on format
alone is order-independent.

This was invisible to us because every scaffolder sets skipLibCheck: true,
and because .d.mts got the legal `import "reflect-metadata";` form -- ESM
consumers never saw a single TS1036.

Adds a check-dts target that parses the built declarations and fails on any
top-level statement, wired into the existing package-quality job so the
class cannot come back silently.

Refs OSS-899
2026-08-21 08:24:46 -05:00