Commit Graph

263 Commits

Author SHA1 Message Date
github-actions[bot] c4ccf02962 style: auto-fix formatting 2026-05-19 22:20:26 +00:00
Maxim 2169cc9383 fix(sdk): widen AG-UI dispatcher args validation to match emitter contracts
The AG-UI dispatcher's ManuallyEmitToolCall handler rejected non-dict,
non-string args with CopilotKitMisuseError, but all three emitters
(JS, Python LangGraph, Python CrewAI) accept any JSON-serializable
value. This mismatch caused JS-emitted list/number args to crash the
Python dispatcher.

Replace the strict isinstance(dict, str) check with a None guard and
rely on the existing json.dumps try/except for serializability.

Call-site enumeration:
- langgraph_agui_agent.py:129 — changed from isinstance check to None guard
- test_emit_tool_call_optional_id.py — updated test_missing_args_raises match,
  test_non_serializable_args_raises match, converted test_list_args_raises and
  test_int_args_raises from negative to positive tests
- No other call sites reference the removed isinstance pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:26 +02:00
Maxim 570bcf4264 fix(sdk): remove dead try/except in emit_message, drop unused imports in sdk.py
Remove no-op `try/except CancelledError: raise` around asyncio.shield
in copilotkit_emit_message (the shield handles cancellation on its own).
Remove unused CopilotKitError and CopilotKitMisuseError imports from
sdk.py (already re-exported via __init__.py).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:26 +02:00
Maxim f434418df5 fix(sdk): restore batched queue_put for atomicity, fix end_dispatched flag ordering
The split queue_put calls introduced interleaving risk (6 yield points
vs 2) and the end_attempted flag was set before the END dispatch,
causing the compensating END to be skipped when END itself failed.

- CrewAI: restore single batched queue_put(start, args, end) call;
  compensating END is now unconditional on batch failure
- AG-UI agent: rename end_attempted → end_dispatched, set after
  successful END dispatch so compensation fires for all failure modes
- Tests: rewrite CrewAI compensating tests for batch semantics,
  add test_failure_on_end_emits_compensating_end for AG-UI agent

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:25 +02:00
Maxim 90de3cef88 fix(sdk): wrap dispatch errors instead of mutating, fix duplicate-END, use UUID for tool call IDs
- Replace JS error.message mutation with wrapped Error + cause chain
  (safe for frozen errors, shared references, non-Error throwables)
- Rename dispatched_end → end_attempted, set before END dispatch to
  prevent duplicate TOOL_CALL_END when END partially flushes before throwing
- Switch JS randomId() (ck-prefixed) to randomUUID() for cross-SDK parity
  with Python's str(uuid.uuid4())

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:25 +02:00
github-actions[bot] 40a4fe6d73 style: auto-fix formatting 2026-05-20 00:18:25 +02:00
Maxim d395501de0 fix(sdk): enrich JS dispatch errors, shield emit_message, standardize validation order
- Wrap JS dispatchCustomEvent in try/catch that enriches error messages
  with tool name and ID for debuggability
- Apply asyncio.shield to copilotkit_emit_message's post-dispatch sleep
  to match copilotkit_emit_tool_call's behavior under task cancellation
- Reorder validation in LangGraph Python and JS to name → toolCallId →
  args, matching CrewAI's order (cheap checks before serialization)
- Narrow AG-UI dispatcher's except clause around json.dumps from
  Exception to (TypeError, ValueError), matching sibling SDK variants
- Add CancelledError propagation and warning-log tests for the shielded
  sleep path

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:24 +02:00
github-actions[bot] 4f81dc38e5 style: auto-fix formatting 2026-05-20 00:18:24 +02:00
Maxim e1da79a5ea fix(sdk): fix CancelledError swallow, dispatched_end ordering, add JS args validation
- Re-raise CancelledError after logging in langgraph copilotkit_emit_tool_call
  to honor asyncio cancellation contract (was silently un-cancelling tasks)
- Move dispatched_end flag to after ToolCallEndEvent dispatch in AG-UI agent
  so compensating END fires when END itself throws
- Add dispatched_end tracking to CrewAI variant to prevent double-END on
  partial failure
- Add JSON.stringify(args) validation in JS SDK matching Python parity
- Add 4 CrewAI compensating-END tests and 1 JS serializability test

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:24 +02:00
Maxim 4a6d364e2c fix(sdk): harden error handling, revert args strictness, shield sleep
Address code review findings across all three SDK variants:

- Shield asyncio.sleep(0.02) with asyncio.shield() so task cancellation
  doesn't prevent returning the tool_call_id after dispatch
- Revert args validation to original permissiveness (JS: undefined-only
  check, Python: no isinstance check) to avoid breaking existing callers
- Add upfront json.dumps() serializability check in Python variants
- Fix compensating TOOL_CALL_END double-emit by tracking dispatched_end
- Add compensating action_execution_end to CrewAI variant (queue_put is
  non-atomic)
- Use exc_info=True in compensating-END error logging
- Export all exception types from copilotkit package root (__init__.py)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:23 +02:00
Maxim 62a3164aab fix(sdk): add @returns JSDoc and compensating-END test coverage
Add missing @returns tag to JS copilotkitEmitToolCall JSDoc, and add
4 tests for the AG-UI compensating TOOL_CALL_END error-recovery path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:23 +02:00
github-actions[bot] 1df8a80e58 style: auto-fix formatting 2026-05-20 00:18:23 +02:00
Maxim be9b60c8a9 fix(sdk): harden AG-UI dispatch, add exception hierarchy, fix docstrings
Address code review findings:
- Wrap AG-UI tool call dispatch in try/except with compensating
  TOOL_CALL_END to prevent clients hanging on partial emission
- Reject non-dict/non-str args at the dispatch layer (lists, ints, None)
- Guard against None event value before calling .get()
- Fix docstring examples that reuse variable names (won't compile)
- Introduce CopilotKitError base class; all exceptions now inherit from
  it; CopilotKitMisuseError inherits from both CopilotKitError and
  ValueError
- Add missing validation tests for name and args across LangGraph and
  CrewAI Python variants, plus AG-UI dispatch edge cases

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:22 +02:00
github-actions[bot] d5cc135c5c style: auto-fix formatting 2026-05-20 00:18:22 +02:00
Maxim 9cb8996056 fix(sdk): harden validation, error types, and dispatch safety across SDKs
Address code review findings: stop mislabeling dispatch errors as
CopilotKitMisuseError in JS (let them propagate naturally), add
CopilotKitMisuseError(ValueError) to Python SDK, pre-serialize args
in AG-UI handler to prevent partial event emission, align whitespace
validation across all SDKs and the dispatch layer, tighten JS args
type to Record<string, unknown>, and add comprehensive negative tests
for AG-UI dispatch validation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:21 +02:00
github-actions[bot] 6fb417a90a style: auto-fix formatting 2026-05-20 00:18:21 +02:00
Maxim 50301b7bf0 fix(sdk): restore error type, rename options.id, add validation parity
- Restore CopilotKitMisuseError for dispatch failures in JS (was bare Error)
- Rename JS options.id to options.toolCallId for cross-SDK naming parity
- Add name/args validation to Python LangGraph and CrewAI variants
- Add defensive field validation in AG-UI dispatch handler
- Add missing CrewAI whitespace-only ID test
- Add JS dispatch failure test

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:21 +02:00
Maxim 09ede29d58 fix(sdk): align whitespace validation, improve error handling and docs
Align JS whitespace-only ID rejection with Python (.trim()), show
returned ID in docstring examples, strengthen CrewAI test assertions
to verify event payloads structurally, and stop miscategorizing
dispatch errors as CopilotKitMisuseError (preserve original stack).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:20 +02:00
github-actions[bot] d2070b7b5f style: auto-fix formatting 2026-05-20 00:18:20 +02:00
Maxim c7693e938e fix(sdk): validate id param, rename to tool_call_id, use options bag in JS
Address review feedback on copilotkit_emit_tool_call:
- Add non-empty string validation for the tool call ID in all 3 SDKs
- Rename Python `id` param to `tool_call_id` to avoid shadowing the builtin
- Refactor JS 4th positional arg to options bag `{ id?: string }` for extensibility
- Document that the ID is also used as parentMessageId in AG-UI events
- Add JS tests for the new parameter (generated ID, custom ID, validation)
- Add Python validation tests (empty string, whitespace rejection)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:20 +02:00
github-actions[bot] 174be4f355 style: auto-fix formatting 2026-05-20 00:18:19 +02:00
Maxim 865991b463 feat(sdk): add optional id parameter to copilotkit_emit_tool_call
Allow callers to supply a custom tool call ID for correlation,
idempotency, and observability. Falls back to uuid4 when omitted.
Applied consistently across Python LangGraph, Python CrewAI, and JS SDK.
Also returns the tool call ID from all variants for downstream reference.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 00:18:19 +02:00
Jordan Ritter 2482317ccc style: apply ruff format to Python codebase
320 files reformatted. One-time alignment to match the ruff format
check added to CI in #4812.
2026-05-13 23:10:35 -07:00
Jordan Ritter a260ffe106 feat: widen header forwarding from x-aimock-* to all x-* headers
Matches the CopilotKit runtime's extractForwardableHeaders() which
already forwards all x-* prefixed headers. Enables any custom
x-* header to propagate from browser through AG-UI to LLM calls.
2026-05-11 20:55:33 -07:00
Jordan Ritter fce31b5079 feat(sdk-python): add header propagation for X-AIMock-Strict
ContextVar-based ambient state + httpx event hook. Incoming
x-aimock-* headers from AG-UI requests are forwarded to outgoing
LLM API calls. Keys normalized to lowercase. Warning emitted when
install_httpx_hook receives an unrecognized client type.
2026-05-11 13:36:55 -07:00
Ran Shemtov 5aaca65485 chore: release sdk-python 0.1.88 2026-05-01 09:33:19 +00:00
Ran Shem Tov 46079baf32 chore(sdk-python): pin pydantic-core floor to 2.35 for 3.14 wheels
Plain `poetry lock` (no --regenerate) was resolving pydantic-core 2.33.2,
which has no cp314 wheel and forces a Rust source build that fails on
PyO3 0.24 (capped at 3.13). Floor pin steers the resolver to 2.46.3
which ships cp314 wheels, so contributor PRs that bump deps and re-lock
keep CI green on 3.14.
2026-04-29 14:02:04 +02:00
Ran Shem Tov b3ead812da chore(sdk-python): bump ag-ui-langgraph floor for 3.14 support
ag-ui-langgraph 0.0.35 lifts requires-python to <3.15. Bump floor
from 0.0.29 so 3.14 environments resolve. Add 3.14 classifier.
Regenerate poetry.lock.
2026-04-29 14:02:04 +02:00
Ran Shem Tov ce9434d1e6 chore: raise python ceiling to 3.14 2026-04-29 14:02:04 +02:00
Ran Shem Tov b3a5fe2670 chore: fix pytests 2026-04-28 15:16:25 +02:00
Ran Shem Tov 6c14258a39 feat(langgraph): add state injection to copilotkit middleware 2026-04-28 13:24:41 +02:00
Max Korp bec1fd0811 fix(a2ui): document id="root" entry-point requirement in generation guidelines
The A2UI React renderer (packages/a2ui-renderer/src/react-renderer/a2ui-react/A2uiSurface.tsx:152)
always begins rendering at the component with id="root":

    export const A2uiSurface: React.FC<{...}> = ({ surface }) => {
      // The root component always has ID 'root' and base path '/'
      return <DeferredChild surface={surface} id="root" basePath="/" />;
    };

If no component has that ID, DeferredChild falls through to its loading-
shimmer placeholder, so the surface silently renders as an empty ~30px
rectangle regardless of how many other components are on the surface.

The generation guidelines shipped to the sub-LLM (in @copilotkit/shared
and copilotkit sdk-python) never stated this requirement. Fixed-schema
demos hard-code a component with id="root" in their JSON and work; dynamic
demos relied on the LLM guessing, which it sometimes did and sometimes
didn't. The failure mode is particularly nasty: no error, no warning,
just a loading spinner that never resolves.

Adds the requirement to COMPONENT ID RULES in both the TS and Python
guideline strings. Both strings are injected into the sub-LLM's context
by A2UICatalogContext (packages/react-core) and
copilotkit.a2ui.a2ui_prompt() respectively, so every A2UI-enabled app
picks it up automatically — no per-demo change needed.

Stacked on #4216, which restores the same instruction to the
langgraph-python-threads demo's tool docstring (belt-and-braces until
consumers update their shared package version).
2026-04-23 13:21:07 -07:00
Martha Schumann 505bc9baef test(sdk-python): remove empty-string delta test
ag-ui-protocol 0.1.15 added a validator requiring TextMessageContentEvent.delta
to have length >= 1. The test asserted that manually_emit_message with an empty
string still emits the full TEXT_MESSAGE_START/CONTENT/END sequence — that
behavior is no longer achievable at the protocol layer, and emitting empty
content events was never semantically useful. Removing rather than guarding
in code: the protocol should fail loudly on empty deltas, not silently drop
them in CopilotKit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 10:03:46 -07:00
Martha Schumann 66c6af5c41 fix(sdk-python): restore json import dropped by main merge
Our branch commit 506a1e8e9 removed the unused 'import json' from
copilotkit/langgraph.py. Main PR #3784 subsequently added a dict-resume
path in copilotkit_interrupt that calls json.dumps(response) and re-added
the import.

The 3-way merge had no textual conflict (the lines around the import
didn't change on both sides), so git silently took our "delete" over
main's "unchanged." Result: json.dumps() called with json undefined.

Verified: sdk-python test suite now 74/74 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 09:53:46 -07:00
Martha Schumann 96e8112039 Merge remote-tracking branch 'origin/main' into claude/langgraph-tests-cleanup-1jVZ3 2026-04-22 09:48:55 -07:00
Martha Schumann 6e7c7bbc53 test(sdk-python): remove orphaned tests for deleted langgraph_agent module
The main-merge commit (0e77affe1) removed sdk-python/copilotkit/langgraph_agent.py
as deprecated, but three test files still imported private helpers from it:
  - test_emit_state_merge.py (_merge_emit_state)
  - test_pydantic_state_serialization.py (LangGraphAgent, _serialize_state)
  - test_sanitize_for_json.py (_sanitize_for_json)

Collection failed with ModuleNotFoundError, so the python-sdk unit job failed.
Behavior these tests covered now lives in the ag_ui_langgraph PyPI package
(external dep), not in this repo — so there is nothing to port.

Also fix test_emit_filtering.py::test_run_filters_none_events: replace
asyncio.get_event_loop().run_until_complete(...) with asyncio.run(...) —
get_event_loop() raises RuntimeError in Python 3.12 when no loop is current.
The failure was masked in CI because collection errored out before this test ran.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 09:46:53 -07:00
Alem Tuzlak 35a68aea90 Merge remote-tracking branch 'origin/main' into fix/crewai-import-compat-3268
# Conflicts:
#	sdk-python/pyproject.toml
2026-04-22 14:36:35 +02:00
Alem Tuzlak d02c5eed6a fix: allow Python 3.13+ in SDK version constraint (#3834)
## Summary
- Widens the python dependency from `>=3.10,<3.13` to `>=3.10,<4`
- Adds Python 3.13 classifier to enable installation on newer Python
versions

Closes #3156
2026-04-22 14:23:04 +02:00
Alem Tuzlak 3f6c80d8a0 Merge branch 'main' into fix/issue-2921 2026-04-22 12:59:18 +02:00
Alem Tuzlak ae1219455a Merge branch 'main' into fix/crewai-import-compat-3268 2026-04-22 12:58:24 +02:00
Alem Tuzlak 2a800f99a7 Merge branch 'main' into fix/issue-3156 2026-04-22 12:57:58 +02:00
Alem Tuzlak b8349d2067 fix(sdk-python): copilotkit_interrupt handles non-list resume values (#3096) (#3784)
## Summary
- `copilotkit_interrupt` now handles string and dict resume values from
LangGraph 1.x's `interrupt()`
- Previously crashed with `AttributeError: 'str' object has no attribute
'content'` or `KeyError: -1`
- Type-checks response: str returned directly, dict JSON-serialized,
list uses existing `[-1].content` path

## Test plan
- [x] Red-green test: string resume value returns without crash
- [x] Red-green test: dict resume value returns JSON string
- [x] Test: list resume value still works (existing behavior)
- [x] Full test suite passes (15/15)

Closes #3096
2026-04-22 12:33:27 +02:00
Alem Tuzlak d6ff5772ed fix(sdk-python): LangGraphAGUIAgent serializes Context objects to dicts (#3690) (#3787)
## Summary
- `LangGraphAGUIAgent.langgraph_default_merge_state` now calls
`model_dump()` on Pydantic Context objects before storing in copilotkit
state
- Previously stored raw Pydantic objects, causing JSON serialization
failures downstream
- Handles mixed types: Pydantic objects get `model_dump()`, plain dicts
pass through unchanged
- Matches the existing pattern already used in `CopilotKitMiddleware`

## Test plan
- [x] Red-green test: AG-UI Context objects stored as plain dicts, not
Pydantic
- [x] Red-green test: mixed Pydantic + dict context items all
serializable
- [x] Full test suite passes (15/15)

Closes #3690
2026-04-22 12:33:14 +02:00
Alem Tuzlak 95fe4889b6 Merge remote-tracking branch 'origin/main' into fix/crewai-import-compat-3268
# Conflicts:
#	sdk-python/pyproject.toml
2026-04-22 12:26:49 +02:00
Alem Tuzlak 51b0513eab Merge remote-tracking branch 'origin/main' into fix/issue-3156
# Conflicts:
#	sdk-python/pyproject.toml
2026-04-22 12:13:45 +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
Maxim 45b28dd3b3 fix(sdk-python): update test to match always-emit assistant message behavior
The test_empty_list_returns_empty_content test expected empty-content
AIMessages to be filtered out, but the fix now always emits assistant
messages so tool calls can reference them via parentMessageId.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-17 15:02:31 +02:00
Maxim 85dbf25c74 Merge branch 'main' into fix/always-emit-assistant-message 2026-04-17 14:42:22 +02:00
Ran Shem Tov 6986a1c120 fix: use latest agui langgraph packages 2026-04-15 18:11:17 +02:00
Markus Ecker 0f02aae198 fix: align A2UI schema format with v0.9 spec and improve path binding prompts
- Replace custom { name, props } schema format with spec-aligned inline
  catalog format (allOf + properties) so the LLM sees the same flat
  structure it must produce — eliminates "props" nesting confusion.
- Restructure generation prompts: inline literal values are the default,
  path binding is a narrow schema-driven exception for form inputs.
- Export InlineCatalogSchema type from a2ui-renderer.
2026-04-15 12:28:13 +02:00