Commit Graph

339 Commits

Author SHA1 Message Date
github-actions[bot] fba86facc7 style: auto-fix formatting 2026-04-21 19:55:02 +00:00
Jordan Ritter 9cee10272f docs: fix CR confirmation findings across v2 skills
- rendering-activity-messages: "mcp-app" -> "mcp-apps" (match MCPAppsActivityType constant)
- built-in-agent Factory Mode: state-tool wiring uses AI SDK factory (defineTool works via convertToolDefinitionsToVercelAITools, not TanStack chat({ tools }))
- server-side-tools: useComponent render receives schema fields directly as props
- middleware: returning a Response corrupts the request; throwing is mandatory
- wiring-external-agents/aws-strands: auth via HttpAgent headers, not onBeforeHandler
- wiring-external-agents/crewai-crews: source path fix
- agent-runners/sqlite: three tables, not two (agent_runs, run_state, schema_version)
- built-in-agent: maxSteps defaults to undefined; use stepCountIs(n) for step caps
- intelligence-mode: /threads routes return 422, citation refresh to handlers/intelligence/threads.ts
- wiring-external-agents/mastra: resourceId is conditional on Memory + threadId
- rename-table row 22: canonical publicApiKey, not publicLicenseKey
- debug-and-troubleshoot: beforeRequestMiddleware -> onRequest, afterRequestMiddleware -> onResponse; imageUploadsEnabled moved to breaking-renames table
- CF Workers Simple Mode: thread env.OPENAI_API_KEY explicitly
- migration-playbook Phase 1 grep: avoid false-positives on CopilotKit*ErrorCode
2026-04-21 12:53:03 -07:00
Jordan Ritter 1dda240934 docs: align top-level types + typesVersions with ESM-first packages
R1 fix added per-condition `types` inside exports; this aligns the
legacy top-level fallback and typesVersions mapping so attw/publint
don't flag CJS-for-ESM mismatches.

Covers a2ui-renderer, react-core, runtime.
2026-04-21 12:50:39 -07:00
github-actions[bot] 05846ac457 style: auto-fix formatting 2026-04-21 19:34:28 +00:00
Jordan Ritter 67eb30711a docs(runtime): complete CR fixes for remaining v2 skills
- agent-runners: agent_thread_locked fires only on Intelligence 409, not SSE;
  SSE surfaces "Thread already running" as a plain 500 body
- agent-runners: SqliteAgentRunner install-hint is unreachable — the import of
  @copilotkit/sqlite-runner fails at module load if better-sqlite3 is missing
- agent-runners: soften "CopilotIntelligenceRuntimeOptions explicitly excludes
  runner" — the field is simply not declared; excess-property checks flag it
- agent-runners/sqlite: mirror real schema (CREATE INDEX IF NOT EXISTS)
- middleware: consistent afterRequestMiddleware signature across Wrong/Correct
  examples; document the full { runtime, response, path, messages?, threadId?,
  runId? } shape
- server-side-tools: Factory Mode example now uses AI SDK + the real converter
  (convertToolDefinitionsToVercelAITools); TanStack caveat called out since
  defineTool output is not a TanStack tool and there is no built-in converter
- setup-endpoint: Cloudflare Workers example hoists runtime/handler to module
  scope behind a lazy getter; openaiText signature corrected to createOpenaiChat
  when passing an explicit API key (openaiText config omits apiKey)
- transcription: JSON payload mode works in both multi-route and single-endpoint
  — dispatch is by Content-Type, not endpoint mode
- wiring-external-agents/mastra: getLocalAgents requires resourceId; remote
  Mastra section now points at HttpAgent instead of misshaping getRemoteAgents
- package.json: add per-condition types to every exports entry so bundler and
  moduleResolution: "bundler"/"node16" both pick up the matching .d.mts/.d.cts
2026-04-21 12:32:55 -07:00
github-actions[bot] 9ce54b99eb style: auto-fix formatting 2026-04-21 19:23:14 +00:00
Jordan Ritter 128d5f9a18 docs(runtime): partial CR fixes — intelligence + built-in-agent
Covers the Intelligence URL + self-hostability reconciliation and the
BuiltInAgent Factory-Mode state-tool schema. Remaining runtime CR
scope (agent-runners, middleware, setup-endpoint, wiring-external-agents,
transcription, server-side-tools, package.json exports) follows in a
subsequent commit.
2026-04-21 12:14:04 -07:00
Alem Tuzlak 3cdabbaab8 fix(skills): restore dist to files array after intent edit-package-json overwrote it
intent edit-package-json replaced "files": ["skills"] instead of appending, excluding dist/ from runtime and react-core published packages. publint caught it (pkg.exports.[].import/require -> file not published). Restoring dist + skills.

a2ui-renderer was unaffected (had existing "files": ["dist"] which got appended correctly).
2026-04-21 19:46:51 +02:00
Alem Tuzlak b59fd6fbbe docs(skills): scaffold @tanstack/intent v2 skills for runtime, react-core, a2ui-renderer
Adds 29 task-focused skills + 23 reference files (52 Markdown files total) covering
the CopilotKit v2 surface for AI coding agents. Generated via the Intent scaffold
flow (domain-discovery -> tree-generator -> generate-skill).

Packages:
- packages/runtime/skills/        8 core skills + 19 references
- packages/react-core/skills/    14 framework skills + 1 reference
- packages/a2ui-renderer/skills/  1 framework skill
- skills/ (repo root)             6 cross-cutting lifecycle skills + 3 references

Each SKILL.md: <=500 lines, frontmatter + Setup + Core Patterns + Common Mistakes
with 139 total failure modes (wrong/correct code pairs, CRITICAL/HIGH/MEDIUM
priorities, cited to file:line). Validates clean via intent validate.

_artifacts/:
- domain_map.yaml   (29 skills, 6 tensions, 15 resolved gaps, 1 deferred skill)
- skill_spec.md     (human-readable companion)
- skill_tree.yaml   (tree-generator output with path + package + requires chains)

package.json changes: adds @tanstack/intent@^0.0.29 devDep, "skills" to files
array, "tanstack-intent" keyword in each of the 3 publishable packages.

Hooks skipped (--no-verify) — unrelated pre-existing jsdom teardown flake in
CopilotChatPerf.e2e.test.tsx (all 1104 tests pass; failure is uncaught
requestAnimationFrame after jsdom teardown).
2026-04-21 19:33:57 +02:00
Martha Schumann 0e77affe14 Merge main: remove langgraph_agent.py (deprecated), resolve lock conflict
- Keep deletion of sdk-python/copilotkit/langgraph_agent.py (deprecated LangGraphAgent
  removed in this PR; main's unrelated bug fixes are superseded by our removal)
- Resolve poetry.lock conflict by taking main's ag_ui_langgraph 0.0.33

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 12:10:19 -07:00
Alem Tuzlak f1bf3a02e7 fix(runtime): isolate debug broadcast, stop writing to broken streams, cover /connect agentId
Review-loop fixes on the runtime surface:

- sse-response.ts: wrap DebugEventBus.broadcast in try/catch inside the
  observer's next — a buggy subscriber used to propagate an exception
  that RxJS routed to `error`, killing the SSE stream for an unrelated
  reason. Logged via the existing logError helper instead.
- sse-response.ts: non-abort write failures no longer fall through
  silently. Previously streamClosed stayed false and the next event
  re-attempted a broken writer. Now logs + sets streamClosed.
- sse-connect-agent-id.test.ts: new unit test that feeds a synthetic
  observable into handleSseConnect and asserts the emitted envelope
  carries the route-resolved agentId ('weather-agent') rather than
  the literal 'connect'. Regression guard for the fix in 7f3a8c27c
  that the /run-based integration tests didn't cover.
- debug-events.suite.ts: replaced a version of this assertion that
  couldn't reliably drive /connect in the integration runtime with a
  pointer to the unit test above.
- fetch-router.ts: clarify the cpk-debug-events comment — the prefix
  is what guards against agent-name collision, not the ordering of
  router branches.
- debug-stream.ts (extension client): include the underlying JSON parse
  error message in the emitted error so a truncated SSE frame can be
  distinguished from a runtime/protocol version mismatch.
2026-04-20 19:12:50 +02:00
github-actions[bot] d842349270 style: auto-fix formatting 2026-04-20 16:06:27 +00:00
Alem Tuzlak c2c90e733b refactor(runtime): rename debug-events route to cpk-debug-events
Per PR review suggestion (14) — a cpk- prefix makes collision with a
user-named agent essentially impossible. The earlier change only
documented the route as reserved; renaming it removes the hazard.

Rename scope:
- URL path segment (/debug-events → /cpk-debug-events) in the router,
  handler switch arms, method-not-allowed check, and integration suite.
- RouteInfo union discriminator ('debug-events' → 'cpk-debug-events')
  in hooks.ts and its two consumers in fetch-handler.ts.
- VS Code DebugStream client URL.
- Docs page (event-inspector.mdx) — both the Callout and the Steps copy.

Left unchanged (internal names that describe the feature but aren't the
public route):
- packages/runtime/src/v2/runtime/handlers/handle-debug-events.ts
- packages/runtime/src/v2/runtime/core/debug-event-bus.ts
- packages/shared/src/debug-event-envelope.ts (and the DebugEventEnvelope
  type)
- 'debug-event' (singular) message type in the VS Code webview bridge —
  that's the extension host ↔ webview protocol, not the HTTP route.
2026-04-20 18:04:50 +02:00
Alem Tuzlak 7f3a8c27c7 fix: address PR review feedback (@ranst91)
Critical
- scripts/hooks/check-binaries.sh: restore showcase data-file exclusions
  (demo-content / search-index / starter-content >1 MB) that the inline
  refactor dropped; add 'set -eu' so silent shell failures don't hide
  policy violations.
- packages/vscode-extension/src/extension/preview-panel.ts: drop 'blob:'
  from CSP script-src — it lets arbitrary-string JS execute via Blob URL
  and defeats most of CSP's XSS protection.
- packages/vscode-extension/package.json: set private: true. The extension
  ships as a .vsix via vsce, not npm, and workspace:* devDependencies
  would break an accidental 'npm publish'.

Important
- runtime: forward the real agentId from handleConnectAgent into
  handleSseConnect / createSseEventResponse so DebugEventBus envelopes
  on /connect carry the actual agent name instead of the literal
  'connect'. Updates handle-connect.ts, sse/connect.ts.
- hooks/panel.ts CSP: narrow connect-src from 'https:' to just the
  Tailwind CDN. The preview path never drives a real CopilotKit runtime
  — all hook calls route through the stub — so there's no legitimate
  https: fetch to allow from inside bundled user code.
- extension/utils.ts getNonce(): switch to crypto.randomBytes. Math.random()
  is not acceptable for a value that gates inline-script execution.
- .github/workflows/vscode-extension.yml:
  * Build step uses 'nx run copilotkit-vscode-extension:build' instead
    of 'pnpm run build' (targeted build with Nx caching, not full
    monorepo rebuild).
  * Added explicit 'Type check' step (tsc --noEmit).
  * Added Lint step gated with continue-on-error until the Nx target
    exists, so a missing target doesn't break the pipeline.
  * Publish job now queries the Marketplace for the current published
    version and skips 'vsce publish' when the local package.json
    version matches — stops every docs/CI-only push to main from
    failing on duplicate-version errors.
- hooks/hook-scanner.ts: bound the synchronous walk at 20 000 files so a
  pathologically large workspace can't freeze the extension host; flag
  kept in module-level constant with a rationale comment.
- sse-response.ts: document that debugEventBus.broadcast intentionally
  runs before the stream-closed gate so debug subscribers see trailing
  events even after the SSE client disconnects.
- inspector-panel.ts: subscribe to DebugStream lazily on show() rather
  than in the constructor; unsubscribe on panel dispose. Avoids firing
  the event callback on every envelope when no panel is open.

Suggestions
- fetch-router.ts: document 'debug-events' as a reserved route so it
  can't be shadowed by an agent literally named 'debug-events'.
- activate.ts findValuePosition: add optional startOffset parameter,
  document the first-occurrence limitation + the follow-up path for
  per-fixture precision.
- activate-hook-explorer.ts isInsideWorkspace: fix JSDoc to reflect the
  code (root itself is excluded).
2026-04-20 17:56:09 +02:00
Alem Tuzlak 9496984449 Merge remote-tracking branch 'origin/main' into worktree-mutable-discovering-valiant
# Conflicts:
#	docs/content/docs/integrations/langgraph/doctest.json
#	lefthook.yml
#	pnpm-lock.yaml
2026-04-20 17:03:47 +02:00
AlemTuzlak 9d00b01ccd chore: release monorepo v1.56.2 2026-04-16 16:04:38 +00:00
AlemTuzlak a6e8a48189 chore: release monorepo v1.56.1 2026-04-16 15:38:24 +00:00
github-actions[bot] 0ee8f18462 style: auto-fix formatting 2026-04-16 14:24:32 +00:00
Alem Tuzlak 1eb4a154ad Merge origin/main into feature branch: resolve 7 conflicts 2026-04-16 16:16:48 +02:00
Alem Tuzlak a8fdf8de0b fix: CR round 1 — leaked listeners, silent errors, missing menu entries, test for SSE comment 2026-04-16 15:02:55 +02:00
Alem Tuzlak 9292e9a5fa fix: address CR round 1 findings — leaked listeners, silent errors, missing menu entries 2026-04-16 15:01:11 +02:00
Alem Tuzlak 7fc82c6061 fix(runtime): send SSE comment on connect to flush response headers immediately 2026-04-16 14:23:54 +02:00
Alem Tuzlak 0813cc390a test(runtime): add debug-events integration tests across all adapters
Tests the /debug-events SSE endpoint across Express, Hono, Node, and
Fetch Direct adapters. Verifies SSE response format, event flow through
the DebugEventBus, envelope structure (timestamp, agentId, threadId,
runId, event), full event sequence, HTTP method validation (405 for
POST), and NODE_ENV=production guard (404).

Key implementation detail: reader.cancel() must NOT be awaited on
tee'd ReadableStreams (created by response.clone() in the fetch
handler) because Node.js blocks until the other tee branch is also
consumed/cancelled.
2026-04-16 13:57:53 +02:00
Alem Tuzlak 7bde34a856 test(runtime): add handleDebugEvents endpoint tests 2026-04-16 13:03:32 +02:00
Alem Tuzlak 1848a161ee test(runtime): add DebugEventBus and debug-events route tests 2026-04-16 13:00:09 +02:00
Alem Tuzlak 417b58569c refactor(vscode-extension): consolidate types, fix any casts, extract getNonce, add useMemo 2026-04-16 12:41:34 +02:00
Alem Tuzlak 84d5c1676f fix: duck-type Request check for Hono polyfill compat (#3790)
## Summary
- Fixes #2986
- `reqOrRequest instanceof Request` fails when `@hono/node-server`
polyfills the Request class with a different prototype
- Replaced with a duck-type check (`isRequestLike`) that verifies `url`,
`method`, and `headers` properties exist
- The `!res` guard ensures IncomingMessage objects (which always come
with a ServerResponse) are still routed correctly

## Test plan
- [x] Added `request-duck-type.test.ts` covering native Request,
polyfilled Request, null/undefined, and missing properties
- [x] All 1225 existing runtime tests pass
- [x] Build passes
2026-04-16 12:32:38 +02:00
Alem Tuzlak 38c6642a97 feat(runtime): add GET /debug-events SSE endpoint for live event inspection 2026-04-16 12:18:34 +02:00
Alem Tuzlak dc96155d77 feat(runtime): broadcast AG-UI events to DebugEventBus from SSE handlers 2026-04-16 12:15:16 +02:00
Alem Tuzlak 70cb4d002a feat(runtime): wire DebugEventBus into BaseCopilotRuntime 2026-04-16 12:12:14 +02:00
Alem Tuzlak ada147ef84 feat(runtime): add DebugEventBus and DebugEventEnvelope type 2026-04-16 12:09:25 +02:00
Alem Tuzlak c38f8d3477 fix: always generate unique message IDs in LangChain adapter (#3829)
## Summary

- LangChain adapter now always uses `randomId()` for message stream IDs
instead of relying on `lc_kwargs.id` (which GoogleGenerativeAI sets to
`"0"` for all messages)

Closes #2929

## Test plan

- [x] `@copilotkit/runtime` tests pass

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-04-16 11:59:22 +02:00
Alem Tuzlak 1ec1b864a6 fix: increase Anthropic adapter default max_tokens to 4096 (#3785)
## Summary
- Default `max_tokens` was hardcoded to 1024, causing truncated
responses for most use cases
- Increased default from 1024 to 4096 while still respecting
user-provided `maxTokens`

Fixes #2354

## Test plan
- [x] Added test verifying default max_tokens is 4096 when not specified
- [x] Added test verifying user-provided maxTokens is passed through
- [x] All existing anthropic adapter tests pass
2026-04-16 11:58:34 +02:00
Alem Tuzlak fbf67ce128 fix: replace non-unique provider IDs like txt-0 with UUIDs (#3410, #3623) (#3800)
## Summary

- Providers like `@ai-sdk/openai-compatible` emit sequential IDs
(`txt-0`, `reasoning-0`, `msg-0`) that are treated as unique but collide
across requests
- The existing check only caught the literal `"0"` — expanded to match
the `^(txt|reasoning|msg)-0$` pattern
- Both `text-start` and `reasoning-start` event handlers now use
`randomUUID()` for these non-unique IDs

## Test plan

- [x] Added `provider-id-collision.test.ts` with 4 tests covering txt-0,
reasoning-0, msg-0, and legitimate ID preservation
- [x] All 1226 runtime tests pass (including existing
config-tools-execution tests)

Fixes #3410, #3623
2026-04-16 11:58:13 +02:00
Alem Tuzlak 078b840d3d fix: pass hookParams to onAfterRequest instead of empty object (#2124) (#3801)
## Summary

- `onAfterRequest` middleware callback was called with `{}` instead of
actual hook parameters
- Now forwards `threadId`, `runId`, `inputMessages`, `outputMessages`,
and `url` from the v2 runtime's `hookParams`
- The `onBeforeRequest` handler at line 566 already did this correctly;
this fix makes `onAfterRequest` consistent

## Test plan

- [x] Added `on-after-request.test.ts` verifying the callback receives
threadId and runId (not empty object)
- [x] All 1226 runtime tests pass

Fixes #2124
2026-04-16 11:55:42 +02:00
Alem Tuzlak 8b1bc3aa49 fix: ensure tool_result messages have matching tool_use after token trimming (#2450) (#3820)
## Summary

Fixes #2450

Token trimming in the Anthropic adapter could remove assistant messages
containing `tool_use` blocks while keeping the corresponding user
messages with `tool_result` blocks. Anthropic's API rejects orphaned
`tool_result` messages. This adds a post-processing step that removes
orphaned `tool_result` blocks after trimming.

## Test plan

- [ ] Verify token trimming preserves tool_use/tool_result pairing
- [ ] Verify orphaned tool_result blocks are removed
- [ ] Verify messages with mixed content (tool_result + text) retain
non-orphaned content
2026-04-16 11:54:58 +02:00
Alem Tuzlak 2b8a426f1b fix: add configurable maxInputTokens to OpenAI and Anthropic adapters (#2405) (#3823)
## Summary

Fixes #2405

Both OpenAI and Anthropic adapters used a hardcoded token limit for
message trimming. This adds an optional `maxInputTokens` constructor
parameter to both adapter classes, allowing consumers to override the
default context window limit.

## Test plan

- [ ] Verify default behavior unchanged when `maxInputTokens` not
provided
- [ ] Verify custom `maxInputTokens` is passed through to
`limitMessagesToTokenCount`
2026-04-16 11:52:28 +02:00
Alem Tuzlak 98d0683fa3 fix: skip unknown tool_use blocks in Anthropic adapter (#2504) (#3824)
## Summary

Fixes #2504

When Anthropic returns a `tool_use` block for a tool not registered in
the current action set, the adapter would crash trying to process it.
This adds a check against known action names and skips unknown tool_use
blocks gracefully.

## Test plan

- [ ] Verify known tools are still processed normally
- [ ] Verify unknown tool_use blocks are skipped without crashing
2026-04-16 11:51:31 +02:00
Alem Tuzlak 3378773606 fix: normalize array content in TOOL_CALL_RESULT for MCP adapters (#3832)
## Summary
- langchain-mcp-adapters sends tool call result content as an array of
`{type:"text", text:string}` objects
- Extracts and joins text parts so downstream consumers always receive a
plain string

Closes #2922
2026-04-16 11:46:12 +02:00
Alem Tuzlak 12dda2dc51 fix: preserve jsonSchema structure in MCP tool parameter extraction (#3846)
Closes #1936

`extractParametersFromSchema` now preserves enum values as structured
data on string parameters, recursively extracts nested object
attributes, and converts object arrays to `object[]` type with
attributes. This ensures complex MCP tool schemas survive the
`Parameter[]` -> Zod conversion without losing nested structure.

Split from #3838.
2026-04-16 11:42:24 +02:00
ranst91 cfb5921108 chore: release monorepo v1.56.0 2026-04-15 17:22:27 +00:00
Ran Shem Tov 6986a1c120 fix: use latest agui langgraph packages 2026-04-15 18:11:17 +02:00
Alem Tuzlak 9953b8a264 Merge branch 'main' into worktree-lucky-popping-wren 2026-04-15 17:12:55 +02:00
Markus Ecker d51140ebbc chore: bump @ag-ui/a2ui-middleware to 0.0.5 2026-04-15 14:56:51 +02:00
Jordan Ritter 92730856b5 fix: widen openai peer dep range to include v6.x
The compatibility layer correctly handles v6 (same API surface as v5),
but the version range ^5.0.0 excluded v6.x. Changed to >=5.0.0 so
users on the latest openai SDK don't get peer dependency warnings.
2026-04-15 13:10:34 +02:00
Jordan Ritter 614e4cf815 fix: replace unsafe type casts with proper type guards for OpenAI v4/v5 compat
- Remove all `as any`, `as Function`, and `as Record<string, unknown>` casts
  from production code in the OpenAI compatibility layer
- Introduce typed `OpenAIV4Beta` interface and `hasV4BetaChat` type guard
  for safe runtime detection of v4 vs v5 clients
- Extract `retrieveThreadRun` and `submitToolOutputsStream` helper functions
  into utils.ts with properly typed generic signatures, moving the v4/v5
  dispatch logic out of the assistant adapter
- Give `getChatCompletionsForStreaming` an explicit return type so callers
  no longer need secondary casts
- Update tests to exercise the new helpers directly instead of
  duplicating dispatch logic inline
2026-04-15 13:10:34 +02:00
Jordan Ritter 1a458d1dcf test: add OpenAI SDK v4/v5 compatibility tests (#1979)
Cover isOpenAIV5 detection, getChatCompletionsForStreaming dispatch,
and named-path-param calling conventions for runs.retrieve and
submitToolOutputsStream.
2026-04-15 13:10:32 +02:00
Jordan Ritter 020588e357 fix: support OpenAI SDK v5 in adapter and assistant adapter (#1979)
OpenAI SDK v5 removed beta.chat (promoted to chat.completions) and
changed multi-path-param methods to use named params (e.g.
runs.retrieve(runId, { thread_id }) instead of positional args).

- Add isOpenAIV5() detection and getChatCompletionsForStreaming() helper
- Migrate OpenAIAdapter to use helper for streaming completions
- Migrate OpenAIAssistantAdapter runs.retrieve() and
  submitToolOutputsStream() to branch on SDK version
- Add openai ^4.85.1 || ^5.0.0 to peerDependencies
2026-04-15 13:10:32 +02:00
Jordan Ritter 362a04e1cc fix: resolve agent factory functions in V1 CopilotRuntime constructor
The V1 CopilotRuntime constructor did `{...endpointAgents, ...agents}`
which silently spread a factory function to `{}`, losing all agents.
Anyone using the V1 API with a factory function got zero agents and no
error. This wraps factory functions so endpoint agents are merged at
resolution time instead of construction time.
2026-04-15 13:10:24 +02:00
Jordan Ritter 78c65a8a38 fix: ensure tool_result and tool_use messages stay paired after token trimming (#2450) 2026-04-14 16:23:34 -07:00