Skip to content

[AI-3379] Python SDK: a connections resource and an optional user_id - #2103

Merged
kanat merged 12 commits into
mainfrom
kanat/ai-3379-python-connections
Nov 20, 2026
Merged

kanat merged 12 commits into
mainfrom
kanat/ai-3379-python-connections

Conversation

@kanat

@kanat kanat commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Why

A backend that connects its users' accounts (Linear, GitHub) had only generated operations in the Python SDK (AI-3375). It had to set X-Stream-User-Id by hand and keep it equal to owner.user_id: the router refuses a user connection whose two values differ (acceleration/internal/api/connections.go:765). The user is now an optional user_id on each call (AI-3387).

The Go reference, #2095, is MERGED. Siblings: #2099 .NET, #2100 Rust, #2101 PHP, #2102 Ruby, #2110 JS.

How it works

api.connections                       (one flat resource, server side only)
├─ create(connector_id, *, label=None, user_id=None)   -> Connection
├─ authorize(id, *, return_url=None, user_id=None)     -> Authorization (launch_url, handoff_token, expires_at)
├─ get(id, *, user_id=None)                            -> Connection
├─ list(*, connector_id=None, user_id=None)            -> every page
└─ delete(id, *, user_id=None)
user_id owner (create) X-Stream-User-Id list
"alice" {type: user, user_id: alice} alice, every call, reads included owner_type=user
None {type: app} none; a client built for a user still names that user owner_type=app
  • A call naming a user replaces whoever the client acts for and the user it was built for (behind the proxy, that user would get a token of their own).
  • Every option is keyword-only, so a user id cannot land in a label's or connector's slot.
  • A device client (user token) naming a user is refused with ValueError before any request, as for_user already was.

What the router answers (connections.go:742-748 mayReach):

  • a call naming a user still reaches the app's connections;
  • a user's list holds only that user's connections.
before (deprecated, still works)               after
api.for_user("u", team="finance")        ->    stream.Client(team="finance")
   .router("clinic")                     ->       .router("clinic", user_id="u")
   .agent("docs")                        ->       .agent("docs", user_id="u")

Changes

Callers found with grep -rn "for_user\|acting_for" over plugins/stream, its README, examples/ and docs/:

Piece Before After
Client.connections none Connections: create, authorize, get, list, delete; Connections, Connection, Authorization exported
Client.agent no user keyword-only user_id=None, last
Client.router no user keyword-only user_id=None, last
Client.for_user public public, DeprecationWarning (attributed to the caller) + docstring pointing at user_id
_backend.py acting_for(backend, user_id) the internal path; dispatch.py:293 and accelerated.py:170 keep using it
plugins/stream/README.md, teams.py docstring for_user user_id= on agent/router
tests/test_teams.py:240,249 (integration) for_user unchanged: deprecated calls still work
CHANGELOG.md, .claude/skills/sdk/SKILL.md one entry, one note

Validation

uv run --no-sync pytest plugins/stream -m "not integration": 673 passed (647 on base), by the round-2 reviewer on d03a0634b. ruff check, ruff format --check and mypy plugins/stream/vision_agents: clean.

Test Defect it catches
test_a_users_connection_names_them_as_owner_and_acting_user owner and header differ, label lost
test_an_app_connection_names_no_user app connection sent with a user, or its header dropped for a client built for a user
test_every_call_sends_the_user_it_names_and_an_app_call_sends_none a call (reads too) without its user; an app call with a header
test_the_user_named_on_the_call_replaces_whoever_the_client_acts_for behind the proxy, a token signed for the client's own user
test_a_call_naming_a_user_reaches_an_app_connection_but_lists_only_theirs wrong owner_type, reach rule broken
test_a_users_connection_is_reached_only_as_them get/authorize/delete with no user or the wrong one
test_authorizing_answers_where_and_how_long_the_consent_runs, test_authorizing_without_a_return_url_sends_none return URL dropped or sent empty; launch URL, token or expiry lost
test_listing_reads_every_page_of_one_connector, test_listing_the_apps_asks_for_the_apps_of_every_connector one page only; connector or limit dropped
test_a_page_marked_more_without_a_cursor_ends_the_list, test_a_page_marked_last_ends_the_list_whatever_cursor_it_carries a loop on a broken page
test_deleting_a_connection_removes_it delete not sent, or force sent
test_a_connection_with_no_id_is_refused_before_the_router empty id sent as a bare collection path
test_every_option_is_named_never_positional a user id accepted in the label, return URL or connector slot, on connections, agent, router
test_a_refusal_is_the_routers_error a refusal returned as success
test_an_agent_for_a_user_names_them_on_every_request, test_a_router_for_a_user_names_them_whoever_the_client_acts_for user_id not sent as X-Stream-User-Id
test_an_agent_without_a_user_sends_what_it_sent_before, test_a_router_without_a_user_opens_as_it_did_before backward compatibility: paths, bodies and X- headers equal those probed on base fa2a6a66d
test_an_agent_without_a_user_keeps_the_user_the_client_was_built_for, test_agent_and_router_without_a_user_keep_the_proxy_token_user_of_the_client agent()/router() with no user drop the client's own user
test_a_device_cannot_name_a_user a device acting for another user, incl. user_id=""
test_a_user_named_on_the_call_is_what_for_user_was the replacement signs other claims than for_user; wrong warning, stacklevel

Mutations: the author's 37 killed (every condition, constant, user hand-off, the deprecation warning and each keyword-only *). Round 2 reran the reviewer's 10: 8 killed, 2 equivalent (mutate_r1.py, delta-2.md).

Live on the staging router, test user, connector linear: create (owner user, pending), authorize (https launch URL, handoff token, 10 minute expiry), get, get as another user is 404, list holds it and the app list does not, delete; list after delete is 0.

Review rounds

Round Verdict Findings Sha
1 not a GO (two Should fix) R1.1 a no-user call cleared the client's own user, R1.2 three surviving mutants: fixed; N2 cursor type, N3 README wording: fixed; N1 stale for_user(team=) line in the sdk skill: ticket 9f8751678
2 GO no new findings d03a0634b
4 GO base merge of #2122 resolved in __init__.py (main's import without ensure_agent + Connections); patch unchanged; ruff, mypy, 674 tests pass (review) 452a64e77

Head 359f79d31 adds main merges and restores main's CHANGELOG lines on top of the GO sha.

🤖 Generated with Claude Code

Client.connections creates, authorizes, reads, lists and deletes connections, each call
naming the user as user_id (owner.user_id and X-Stream-User-Id; none is the app's).
Client.agent and Client.router take user_id as their last keyword argument; Client.for_user
is deprecated with a DeprecationWarning and keeps working (AI-3387).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nector_id

A user id passed in a label's or connector's slot would silently do the wrong thing
(w55 R1.1). user_id on agent and router is keyword-only and None by default too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The Python SDK adds Client.connections methods for managing app- or user-owned connector connections. Client.agent and Client.router accept a per-call user_id. Client.for_user remains available and emits a deprecation warning. Tests cover connection ownership, authorization, listing, and deletion, along with user-scoped agent and router requests. Documentation and the changelog describe the new API and deprecation.

Merge Risk: Moderate · up to 09949

The new connections API and per-call user_id mostly work as described. Device clients naming a user are not rejected before the request, though. No-user connection calls can still carry a configured user's header, and listing can loop without bound if a server repeats a cursor. Fix these before merge. The remaining items are smaller gaps in tests and documentation.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between fa2a6a6 and 318a54b.

Files selected for processing: 12

  • .claude/skills/sdk/SKILL.md
  • CHANGELOG.md
  • plugins/stream/README.md
  • plugins/stream/tests/test_backend.py
  • plugins/stream/tests/test_client.py
  • plugins/stream/tests/test_connections.py
  • plugins/stream/tests/test_router.py
  • plugins/stream/vision_agents/plugins/stream/__init__.py
  • plugins/stream/vision_agents/plugins/stream/_backend.py
  • plugins/stream/vision_agents/plugins/stream/client.py
  • plugins/stream/vision_agents/plugins/stream/connections.py
  • plugins/stream/vision_agents/plugins/stream/teams.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review.


listed = await api.connections.list()

assert [c.id for c in listed] == [row["id"] for row in first]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Data Integrity & Integration · Quick win

Reject incomplete pagination instead of accepting partial success.

The fixture stores three connections but returns two with has_more=True and no cursor. This assertion accepts the missing third connection as a successful list. Require an explicit pagination error and update Connections.list accordingly. Keep the separate final-page test unchanged.

As per path instructions, flag “hidden or reclassified failures” and “tests that would still pass on a broken implementation.”

Source: Path instructions

Comment on lines +53 to +54
self, connector: str, *, label: str = "", user_id: str = ""
) -> Connection:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Pass connector inputs and auth_scheme through create.

ConnectionRequest accepts inputs and auth_scheme, but Connections.create cannot set either. A connector that requires an input without a default, or that offers more than one auth scheme, cannot be created through this wrapper. Add optional keyword arguments for these fields and pass them to ConnectionRequest, or document that create supports only connectors with defaults and a single scheme.

def _client(self, user_id: str) -> AuthenticatedClient:
"""The generated client acting for ``user_id``, or for nobody when it is empty,
whoever this client acts for otherwise."""
return acting_for(self._backend, user_id).client()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Reject device calls that name a user before creating the request.

With a key-plus-token device client, connections.get("connection-1", user_id="bob") reaches this line without a server_side check. acting_for retains the device token and adds Bob's header. The call does not raise the required ValueError before the request.

Check self._backend.server_side before selecting a named user. Keep secret-backed and customer-backed calls working.


Minor · Stability & Availability · Quick win

Close the generated client after each request in Connections.

Each Connections operation builds a new AuthenticatedClient through _client. Its httpx.AsyncClient is never closed, so connections are not pooled across calls. The sockets are released only when the client is garbage collected. Enter the client as an async context manager at each call site, for example async with self._client(user_id) as client:, and pass client to the generated call. The per-call construction stays, because Backend.client() builds each client on purpose to keep tokens fresh.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 9f87516 merged onto main fa2a6a6. CI: all green. pytest plugins/stream -m "not integration": 671 passed; ruff, mypy clean. Live staging create/authorize/get/list/delete as a test user: as described, nothing left. Mutations: the author's 37 all killed on the merged tree; 10 more of mine, 3 real survivors (R1.2).

[Question] Q1 (merge order): the Go shape this follows (#2095) is still open and not on main, and the sdk skill on main has no Go connections note. AGENTS.md says Go goes first: merge this after #2095.

[Nit] N1 .claude/skills/sdk/SKILL.md:782 still says "A user's team is team= on for_user". Stale now that for_user is deprecated; the appended note is the only line this PR may touch, so a follow-up.

Author questions: the Daniil rewrite is decided, no finding. Backward compatibility in API-key mode is in scope: R1.2 (M1).

Checked and sound: agent()/router() without a user return the client's own backend unchanged, so no existing call changes; for_user still works and warns; dispatch and Accelerated keep Backend.acting_for; no all-users list (no user always sends owner_type=app); every page read with stops on has_more/next_cursor; empty id refused; no force.

Verdict: request changes, for R1.1 and R1.2.

def _client(self, user_id: Optional[str]) -> AuthenticatedClient:
"""The generated client acting for ``user_id``, or for nobody without one,
whoever this client acts for otherwise."""
return acting_for(self._backend, user_id or "").client()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 A call with no user drops the client's own user_id (and user), not only the acting-for user: acting_for(self._backend, "") sets user_id="". The Go shape (#2095, connections.go api()) only sets backend.ActingFor = userID, and Ruby (#2102), .NET and Rust keep the client's own user the same way.

Probe: Client(url, api_key="key", api_secret="secret", user_id="jean", authenticate=False), then get(alice's, user_id="alice"), get(app's, user_id=""), get(app's) send X-Stream-User-Id ['alice', None, None]; the wave rule wants ['alice', 'jean', 'jean'].

Fix: with no user, replace(self._backend, acting_for="").client(); a named user stays as now. Checked in a scratch copy: the probe passes, and test_an_app_connection_names_no_user plus the no-user half of test_the_user_named_on_the_call_replaces_whoever_the_client_acts_for then need to expect jean (header, or user_id on the token behind the proxy). Reword to match: the class docstring (:33-37), _client's docstring, README "without one it is the app's own connection", the sdk skill note ("none is the app's connection with no header") and the PR body ("The copy drops the user the backend was built for").

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eac81b7: a call naming no user now acts as the client is (replace(backend, acting_for="")), so a client built for jean still sends jean. Tests: test_an_app_connection_names_no_user and test_the_user_named_on_the_call_replaces_whoever_the_client_acts_for now expect jean (header, token user_id). Reverting to acting_for(backend, "") fails both and your P1 probe. Docstring, README, SKILL note and PR body reworded.

ValueError: A ``user_id`` on a client that is not server side.
"""
return Agent(self.backend, name)
return Agent(self._acting(user_id, "an agent"), name)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 (surviving mutants, 1 of 3) Mutant M1 survives: the no-user path changed to acting_for(self.backend, self.backend.acting_for) drops a server client's own user_id, and every test still passes. The backward-compatibility test covers customer-id mode only. Row to add to TestActingForAUser: Client(url=router.url, api_key="key", api_secret="secret", user_id="jean", authenticate=False).agent("docs"), then sessions.create + get + close: every router.headers entry has X-Stream-User-Id: jean and X-Api-Key: key, which is what main sends (return Agent(self.backend, name)). Also, with authenticate=True, the Authorization claims of router("clinic") and agent("docs") carry user_id: jean. Checked: it fails under M1 and passes on head.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in efec1a4: TestActingForAUser::test_an_agent_without_a_user_keeps_the_user_the_client_was_built_for (row P2) and TestTeamsAndCategories::test_agent_and_router_without_a_user_keep_the_proxy_token_user_of_the_client (row P3). Your mutate_r1.py: M1 and M2 killed.

"agent(name, user_id=...) or router(config, user_id=...), on a client built "
"with team= and usage_categories=",
DeprecationWarning,
stacklevel=2,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 (2 of 3) Mutant M3 survives: stacklevel=2 to 1. With 1 the warning is attributed to client.py, and Python's default filter shows a DeprecationWarning only when it is attributed to __main__, so a script calling for_user sees nothing. Row for test_for_user_keeps_the_apps_credential_and_names_the_user: with pytest.warns(DeprecationWarning, match="user_id") as caught: then assert caught[0].filename == __file__. Checked: it fails under M3 and passes on head.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in efec1a4: test_for_user_keeps_the_apps_credential_and_names_the_user now asserts caught[0].filename == __file__. M3 killed (and M4).


def _acting(self, user_id: Optional[str], what: str) -> Backend:
"""This client's backend, or a copy of it acting for ``user_id`` when one is named."""
if not user_id:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.2 (3 of 3) Mutant M9 survives: if not user_id to if user_id is None. An empty user_id then goes down the acting path, and a device raises. Row for test_a_device_cannot_name_a_user: device.router("clinic", user_id="").backend is device.backend and device.agent("docs", user_id="")._backend is device.backend. Checked: it fails under M9 and passes on head.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in efec1a4: test_a_device_cannot_name_a_user now asserts device.router("clinic", user_id="").backend is device.backend and the same for agent. M9 killed.

owner = ConnectionOwnerType.CONNECTION_OWNER_TYPE_USER
client = self._client(user_id)
connections: List[Connection] = []
cursor: Any = UNSET

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] N2 cursor: Any: AGENTS.md says to avoid Any. Union[str, Unset] says what it holds.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eac81b7: cursor: Union[str, Unset]; mypy clean.

Comment thread plugins/stream/README.md Outdated
## A user's own accounts

`api.connections` holds the accounts the app and its users have at connectors, such as a
user's Linear, which an agent's tools reach that account through. Server side only. Each

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] N3 "such as a user's Linear, which an agent's tools reach that account through" does not read. Suggest: "such as a user's Linear, through which an agent's tools reach that account".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eac81b7: reworded to "through which an agent's tools reach that account" (README and the class docstring).

kanat and others added 4 commits November 19, 2026 13:05
…was built for (R1.1), cursor typed (N2), README sentence (N3)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… empty user, and the for_user warning's stacklevel (R1.2)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delta review, round 2. Verdict: GO. Reviewed d03a063 (it contains origin/main 9361ea4; the merge has an empty --remerge-diff).

Prior findings

  • R1.1 fixed. connections.py _client now uses replace(self._backend, acting_for="") when no user is named, so a client built for a user keeps that user. I broke it three ways: back to acting_for(backend, ""), to self._backend.client() (keeps an acting_for of "bob"), and a named user that keeps the built user. The first two fail test_an_app_connection_names_no_user. The third fails test_the_user_named_on_the_call_replaces_whoever_the_client_acts_for.
  • R1.2 fixed. My round-1 mutants M1, M2 (agent()/router() drop the client's user), M3 (stacklevel) and M9 (if not user_id vs is None) are now killed by the new tests. M4 (PendingDeprecationWarning) is killed too. On head, mutate_r1.py kills 8 of 10. M8 and M10 survive as equivalent mutants, as ruled in round 1. The round-1 probe rows P1-P6 pass on head.
  • N2 fixed: cursor: Union[str, Unset], mypy clean. N3 fixed: README and class docstring reworded. The SKILL note and PR body were reworded to match the new behaviour.
  • N1 stays a ticket (unchanged SKILL line 782).

Checks: pytest plugins/stream -m "not integration" 673 passed. ruff check, ruff format --check and mypy plugins/stream/vision_agents are clean. CI at the time of review: all green except unit / Test "not integration", still pending.

No new findings.

@kanat
kanat marked this pull request as ready for review November 19, 2026 12:14
kanat added a commit that referenced this pull request Nov 19, 2026
## Why

A backend that connects its users' accounts (Linear, GitHub) has only
the generated operations in the Go SDK. It sets `X-Stream-User-Id` by
hand and must keep it equal to `owner.user_id`: the router refuses a
user connection whose two values differ
(`acceleration/internal/api/connections.go:765`).

This is the first of the seven server SDKs (AI-3375). Its shape was
decided in #video-ai on 2026-11-19:
- flat `api.Connections()`, with no `agents.` level;
- the user is a per-call parameter, as Chat's server SDKs pass
`user_id`;
- no per-user client.

The other six copy it, and merge after this PR:
- JavaScript [#2110](#2110)
- Python [#2103](#2103)
- Ruby [#2102](#2102)
- PHP [#2101](#2101)
- .NET [#2099](#2099)
- Rust [#2100](#2100)

## How it works

```
api.Connections()
├─ Create(ctx, ConnectionRequest{Connector, Label, UserID})
│    UserID set   -> owner {type: user, user_id: UserID} + X-Stream-User-Id: UserID
│    UserID empty -> owner {type: app}                   + no X-Stream-User-Id
├─ Authorize(ctx, id, AuthorizeOptions{ReturnURL, UserID}) -> launch URL, handoff token, expiry
├─ Get(ctx, id, ConnectionOptions{UserID})
├─ List(ctx, ConnectionFilter{Connector, UserID})   owner_type user|app, reads every page
└─ Delete(ctx, id, ConnectionOptions{UserID})
```

```go
conn, err := api.Connections().Create(ctx, client.ConnectionRequest{Connector: "linear", UserID: "alice"})
auth, err := api.Connections().Authorize(ctx, conn.ID, client.AuthorizeOptions{ReturnURL: returnURL, UserID: "alice"})
conn, err = api.Connections().Get(ctx, conn.ID, client.ConnectionOptions{UserID: "alice"})
```

The user is always the `UserID` of the call's options struct. No two
strings sit side by side, so a call cannot swap them.

| Call | `X-Stream-User-Id` | What the router answers |
| --- | --- | --- |
| `UserID: "alice"` | `alice`, also on reads | alice's connection; an
app connection is reached too (`mayReach`, `connections.go:742-745`) |
| `UserID` empty | none: only the acting-for user is cleared, and a
client's own `UserID` stays | the app's connections |
| `List` with `UserID` | `alice` | only alice's connections |

A per-call copy of the client's `stream.Backend` gets `ActingFor =
userID` (`client/connections.go:187-191`). Results are the generated
`acceleration.Connection` and `acceleration.Authorization`. Refusals are
`*stream.RouterError`.

The change is additive only, per Chat's "deprecate, never break" rule.
Go had no public acting-for helper, so nothing is deprecated here; the
other SDKs deprecate theirs (AI-3387).

## Changes

- `sdks/go/client/connections.go`: the resource.
- `client/client_test.go`: the stand-in router now records each
request's headers. It serves the connection routes with the router's own
owner rules (`ownerOf`, `mayReach`).
- `sdks/go/README.md`: new section "A user's own accounts".
- `CHANGELOG.md`: one entry.
- `.claude/skills/sdk/SKILL.md`: a note for the other SDKs. In each, the
user is an optional named parameter (`userId` / `user_id`) and the
optional parts are an options object. Also, "connections" leaves the
sdk-go known-gaps list.

## Validation

`go test -race ./client/... && go test . && go vet ./... && go vet -tags
e2e .` in `sdks/go`: pass. CI: green on `92148e5fe`.

| Test | Defect it catches |
| --- | --- |
| `TestAUsersConnectionNamesThemAsOwnerAndActingUser` | owner and header
differ, or one has no user |
| `TestAnAppConnectionNamesNoUser` | an app connection sent with a
`user_id`, or with the client's acting user |
| `TestACallNamingAUserReachesAnAppConnectionButListsOnlyTheUsers` |
docs and code disagree on reach |
| `TestEveryCallSendsTheUserItNamesAsTheActingUser` | owner and header
differ on any call, reads included; an app call sends a header |
| `TestAuthorizingAnswersWhereAndHowLongTheConsentRuns` | return URL or
user dropped; launch URL, token or expiry lost |
| `TestAUsersConnectionIsReachedOnlyAsThem` | get, authorize or delete
sent with no user or the wrong one |
| `TestListingReadsTheOwnersConnectionsEveryPage` | only one page read,
wrong `owner_type`, connector dropped |
| `TestDeletingAConnectionRemovesIt` | delete not sent, sent as someone
else, or `force` sent |
| `TestAConnectionWithNoIDIsRefusedBeforeTheRouter` | an empty id sent
as `/v1/agents/connections/` |
| `TestAConnectionRefusalIsTheRoutersError` | a refusal or a cancelled
request returned as success |

Mutations: 30 of 30 killed (`mutate.py`). They cover every condition,
branch and constant in `connections.go`, including the user dropped from
each of the five calls.

Review rounds:
- Round 1 NO-GO, fixed:
  - `ForUser` kept the parent client's team;
  - the docs disagreed with the router on reach.
- The team then dropped `ForUser` for a per-call user (R2.1, `UserID`
naming R2.2).
- Round 3 GO; its two nits (`Get` and `Delete` took a bare `userID`
string) are fixed by `ConnectionOptions`.
- Follow-up: AI-3385 (the user's email for connectors that check it).

Live run on the staging router with the final signatures, as user
`e2e-ai3376` and connector `linear`. The id is shortened to a prefix.
The deferred delete found nothing, so nothing was left behind.

```
create: id=afa8b1… connector=linear owner=user/e2e-ai3376 status=pending
authorize: kind=consent launch_url_https=true handoff_token_set=true expires_in_10m=true
get: status=pending
get as another user: refused=true
list: count=1 contains=true
list app: contains=false
delete: ok; get after delete: refused=true
list after delete: count=0
delete (deferred): no such connection
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat and others added 2 commits November 19, 2026 16:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Nitpick comments: 1

plugins/stream/tests/test_connections.py: 1

4-4: Trivial · Maintainability & Code Quality · Quick win

Use explicit types for the fixture records.

The request recorder gives body, headers and query the same Any value type. A typed request record would let the type checker catch incorrect field access in the assertions. As per coding guidelines, “Avoid using Any type.”

Source: Coding guidelines

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 318a54b and 359f79d.

Files selected for processing: 11

  • .claude/skills/sdk/SKILL.md
  • CHANGELOG.md
  • plugins/stream/README.md
  • plugins/stream/tests/test_backend.py
  • plugins/stream/tests/test_client.py
  • plugins/stream/tests/test_connections.py
  • plugins/stream/tests/test_router.py
  • plugins/stream/vision_agents/plugins/stream/__init__.py
  • plugins/stream/vision_agents/plugins/stream/_backend.py
  • plugins/stream/vision_agents/plugins/stream/client.py
  • plugins/stream/vision_agents/plugins/stream/connections.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.

Comment thread CHANGELOG.md

### The Python SDK connects a user's own accounts

`api.connections` creates, authorizes, reads, lists and deletes connections, each call naming the user as `user_id` (the owner and `X-Stream-User-Id`; none is the app's). `api.agent(name, user_id=...)` and `api.router(config, user_id=...)` run work for a user on the app's credential; `api.for_user` is deprecated and still works.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Data Integrity & Integration · Quick win

Separate app ownership from request identity.

Omitting user_id selects app ownership on creation and app scope on listing. It does not necessarily clear the client's identity. The tests expect a client built for Jean to retain Jean in the header or token, depending on authentication. State that distinction so readers do not treat omission as a way to send an unscoped request.


Minor · Maintainability & Code Quality · Quick win

Add this PR's number to the changelog entry.

The entry does not identify the PR that introduced the Python API. As per path instructions, “Reference PR numbers inline (e.g. (#374)).”

Source: Path instructions

Comment thread plugins/stream/README.md
Comment on lines +443 to +444
# Open consent.launch_url in a popup from that origin, post it consent.handoff_token,
# and finish before consent.expires_at.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Document the handoff as a reply to the launch page's request.

The README says to open consent.launch_url, then post consent.handoff_token. The authorization contract says the launch page asks the opener for that token. The README does not state this order. An opener that posts before the launch page requests the token can miss the handoff, because postMessage does not queue messages for a window that has no listener yet.

State that the opener must wait for the launch page's request, then post consent.handoff_token in reply to it. Keep the expiry instruction.

Comment thread plugins/stream/README.md

connection = await api.connections.get(connection.id, user_id="alice")
mine = await api.connections.list(connector_id="linear", user_id="alice") # every page
await api.connections.delete(connection.id, user_id="alice")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Separate deletion from the connection example.

If a reader runs this block, the popup instructions do not pause execution. The code deletes the connection before consent can finish. Move deletion to a separate example for disconnecting an account.

Comment on lines +315 to +318
with pytest.raises(stream.RouterError):
await api.connections.authorize(alices["id"], user_id=user)
with pytest.raises(stream.RouterError):
await api.connections.delete(alices["id"], user_id=user)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Data Integrity & Integration · Quick win

Assert 404 for denied authorization and deletion.

The fixture returns 404 when Bob cannot reach Alice's connection. These assertions would also pass if either SDK method exposed the refusal as a 500 RouterError. Check status == 404 for both methods, as this test already does for get. As per path instructions, flag “tests that would still pass on a broken implementation.”

Source: Path instructions

wanted = [router.add("linear", user_id="alice") for _ in range(5)]
router.add("linear")

listed = await api.connections.list(connector_id="linear", user_id="alice")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Quick win

Stop the Connections.list loop when the server repeats a cursor.

Connections.list exits only when has_more is false or next_cursor is empty. If the server returns a next_cursor that it already returned, the loop requests the same page again and never ends. Each pass also appends to connections, so memory grows without bound. The SDK must bound reads even when the server is broken. Use the same seen-cursor guard that config.py uses.

The current test only covers advancing cursors. Add a case where the server repeats cursor "2", and assert that list returns instead of looping.

Suggested fix

         connections: List[Connection] = []
         cursor: Union[str, Unset] = UNSET
+        seen: set[Union[str, Unset]] = set()
         while True:
@@
-            if not page.has_more or not page.next_cursor:
+            if not page.has_more or not page.next_cursor or page.next_cursor in seen:
                 return connections
+            seen.add(page.next_cursor)
             cursor = page.next_cursor

# or read the wrong connection.
calls = [
lambda: api.connections.create("linear", "alice"),
lambda: api.connections.authorize("c-1", "https://app.example", "alice"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Test a single extra positional argument to authorize.

This call supplies two optional positional arguments. It still raises TypeError if return_url accidentally becomes positional and only user_id remains keyword-only. Add authorize("c-1", "alice") to check the binding this test is meant to prevent. As per path instructions, flag “tests that would still pass on a broken implementation.”

Source: Path instructions

It keeps the app's credential and drops the user the backend was built for: behind the
proxy that user would be signed a token of their own instead.
"""
return replace(backend, user_id="", user={}, acting_for=user_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Data Integrity & Integration · Quick win

Clear a supplied user token when selecting app authentication.

If a backend has both api_secret and an Alice user token, _acting("bob") accepts it as server-side. This copy retains Alice's token. _proxy_token() then returns that token instead of an app token, despite the Bob header.

Clear token when creating the server-scoped copy. Keep secret-only and customer-backed calls working.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GO at 452a64e.

Delta round 4: d03a0634b..452a64e77, the merge of main ba565cd22 (#2122, which removed ensure_agent).

  • Conflict: git show --remerge-diff 452a64e77 shows one, in plugins/stream/vision_agents/plugins/stream/__init__.py. It is resolved right: main's from .config import define_agent, define_skills, sync_agent (no ensure_agent) plus this PR's from .connections import Connections. __all__ merged cleanly.
  • The PR's own patch is unchanged since the last GO (delta-kind.sh d03a0634b 452a64e77 origin/main: "patch unchanged", trivial).
  • No main change reverted: git diff origin/main 452a64e77 is 12 files, all this PR's own; the CHANGELOG diff against main is only the PR's Python entry.
  • Nothing in the PR uses what #2122 removed: git grep ensure_agent outside CHANGELOG finds nothing, and the only CHANGELOG hits are main's historical lines.
  • Checks on the head in a clean worktree: ruff check, ruff format --check, dev.py mypy and dev.py mypy-plugins pass; pytest plugins/stream -m "not integration": 674 passed, 9 deselected.
  • CI at review time: unit and lint jobs pass; go and CodeRabbit still pending.

Prior findings: R1.1 fixed, R1.2 fixed, N2 fixed, N3 fixed (all at d03a0634b, confirmed in rounds 2 and 4). N1 stays a ticket. No new findings.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Clear the client's user identity for app-owned connection calls. · connections.py:170

plugins/stream/vision_agents/plugins/stream/connections.py:170
Major · Data Integrity & Integration · Quick win

Clear the client's user identity for app-owned connection calls.

If the client has user_id="jean" and authenticate=False, this replacement retains user_id. Backend._credentials() then adds X-Stream-User-Id: jean, although create() selects app ownership. This violates the required owner/header consistency.

For the no-user path, clear user_id, user, and acting_for. Keep the app credential and billing categories. Update the README statement that preserves the client's user identity.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 359f79d and 452a64e.

Files selected for processing: 7

  • plugins/stream/README.md
  • plugins/stream/tests/test_backend.py
  • plugins/stream/tests/test_client.py
  • plugins/stream/tests/test_router.py
  • plugins/stream/vision_agents/plugins/stream/__init__.py
  • plugins/stream/vision_agents/plugins/stream/_backend.py
  • plugins/stream/vision_agents/plugins/stream/client.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 20, 2026
…2128)

## Why

The other server SDKs are adding a per-call user. JavaScript, Python,
Ruby and PHP deprecate their per-user helper in open PRs (#2110, #2103,
#2102, #2101); .NET (#2099) and Rust (#2100) add the per-call user and
have no public helper to deprecate. Go still recommends
`Backend.ActingFor`, a field that fixes one user for every request a
backend makes. `client.Connections()` (#2095) already takes the user as
`UserID` per call. This deprecates `ActingFor` and moves the two
examples off it. It keeps working: only a `Deprecated:` paragraph is
added. The note names what exists today: `UserID` on
`client.Connections()` calls, `XStreamUserId` on
`CreateScheduledTaskParams`, a per-call `acceleration.RequestEditorFn`;
`client.Agent(...)` calls take no per-call user yet, so `ActingFor`
stays their way.

## How it works

```
before   example ──> Backend{ActingFor: user} ──> X-Stream-User-Id
after    example ──> per-call user ───────────────> X-Stream-User-Id
                     (UserID of the call, or the header on the call)

SDK itself (Dispatch.Answer, Connections.api)
         ──> still sets ActingFor on a copy of the backend, each line with
             //nolint:staticcheck // SA1019 (golangci-lint's form, as acceleration/cmd/usage)
```

No public API is added: every call site the examples needed already had
a per-call user. The SDK's own two writes send exactly what they sent on
base.

| Call site | Now | Request change |
| --- | --- | --- |
| `crew_assistant` create | `Backend{}`;
`CreateScheduledTaskParams.XStreamUserId` (already set) | none |
| `crew_assistant` run, delete | `Backend{}`; a backend reaches a task
of its customer without naming the user (`session.Owner.Reaches`, server
kind) | `X-Stream-User-Id` no longer sent on run and delete |
| `swift_assistant` list Gmail | `client.Connections().List(ctx,
ConnectionFilter{UserID, Connector})` | adds `limit=200` and follows
every page (the old call read the first 25) |
| `swift_assistant` proxy POST | `Backend{}.Resolve()`, then
`credentials.Set(stream.UserHeader, user)` on the raw request; kept raw
so the 1 MiB read cap stays | none |

Other readers of `ActingFor` (grep over `sdks/go`, `examples`, `tui`,
`.claude/skills`, READMEs): `stream/backend.go` (`Credentials`, the
field), `agents/dispatch.go`, `client/connections.go` (both write it,
with a nolint), `client/connections_test.go` (reads it, with a nolint),
`.claude/skills/sdk/SKILL.md:447` (a note about every SDK, left as
written, with one line appended). The Go README and `sdk-go` skill never
recommended it.

## Validation

- `cd sdks/go`, `GOWORK=off`: `gofmt -l`, `go mod tidy -diff`, `go vet
./...`, `go vet -tags e2e .`, `go test -race ./...` all pass. Each
touched example: `go build ./... && go vet ./...` pass; `crew_assistant`
tests pass.
- staticcheck (via `golangci-lint -E staticcheck`): no SA1019 in
`sdks/go`, either example or `tui`; the six findings left are in files
this PR does not touch.
- Backward compatibility:
`TestABackendBuiltWithActingForSendsWhatItAlwaysDid` pins method, path
and headers of three `ActingFor` backends (local router, behind the
proxy, team and categories). The expected values were read off a client
built the same way on the base commit (ab01365). It fails if the
header is dropped, sent only in one mode, or read from another field.
- `TestActingForAUserKeepsTheServersToken`: the user goes in the header,
never into the token, and the token keeps its server claim.
- `Dispatch.Answer` and `Connections` keep their existing header tests
(`TestAMessageWrittenToARunningSession...`, the connections suite); each
fails with its `ActingFor` write removed.
- New example tests (run locally; CI runs neither example's tests):
`TestGmailCallsNameTheUser` (swift: the Gmail list and the proxy POST
name the user) and `TestTheAgentSpeaksFirstInTheUsersConversation`
(crew: the task is created naming the user).
- Examples: a throwaway probe test recorded every request of both
examples on base and on this branch; the diffs are the two rows above
and nothing else. The probe is not committed; the two example tests
above pin the user on those requests.
- Mutants over the changed lines (the two SDK writes dropped; the token
losing its server claim; `Credentials` dropping or mode-limiting the
header; the swift list and proxy and the crew create dropping the user):
all killed.

Not checked: nothing run against a real router, as no request changes
for existing callers.

## Review rounds

| Round | Verdict | Findings | Sha |
| --- | --- | --- | --- |
| 1 | NO-GO | R1.1 exported `Backend.Acting` removed (internal writes
keep `//nolint:staticcheck` with the reason); R1.2 deprecation note
names only what exists; R1.3 four surviving mutants now killed (swift
list/proxy, crew create, token server claim); R1.4 skill note links the
open SDK PRs: fixed. R1.5 example `go.sum`: ticket AI-3399; per-call
user on `client.Agent`: ticket AI-3398 | `8ca1c3635` |
| 2 | NO-GO | R1.1-R1.3 verified, 10/10 mutants killed; R2.1 skill note
claimed .NET and Rust deprecate a helper (they have none public): fixed
| `ecab56d1b` |
| 3 | GO | R2.1 closed; claims checked against each SDK PR's diff
([review](#2128 (review)))
| `0526b858c` |

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GO at 099495e (delta round 5: the merge of main 46f24fc at 02c450e and then of main 36d5e34 (#2128) at this head, on top of 452a64e).

Prior findings

  • R1.1, R1.2, N2, N3: still fixed. Rechecked by mutation on this head: no-user call clearing acting_for (connections.py:170) fails 2 tests; agent() dropping the client's own user (client.py:368) fails 3; stacklevel=1 on for_user (client.py:213) fails test_for_user_keeps_the_apps_credential_and_names_the_user.
  • N1 stays a ticket (SKILL.md still names for_user(team=) in an older paragraph).

Delta

  • The merge conflicts resolve correctly: README keeps the PR's "A user's own accounts" section followed by main's renamed "Tools" section (no duplicate or contradicting text, no link to the old heading); client.py keeps both imports (Connections, Dispatch) and both attributes (connections, tools = FunctionRegistry()).
  • git diff 46f24fc18 HEAD is the PR's 12 files only, so no main change is reverted. CHANGELOG.md and SKILL.md differ from main only by the PR's entry and note (the merge also dropped one stale copy of main's UI paragraph from SKILL.md).
  • The head moved while I reviewed, to a clean merge of main 36d5e34 (#2128, Go only, now the base tip): its remerge diff is one blank line in CHANGELOG.md between the PR's entry and main's; git diff origin/main HEAD is the PR's 12 files only. On this head: ruff check and format, dev.py mypy, dev.py mypy-plugins pass; pytest plugins/stream -m "not integration": 676 passed.
  • CI had just started when read (GitGuardian pass, the rest pending); not waited for.

No new findings.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Reject user-named calls from device clients before the request. · connections.py:169

plugins/stream/vision_agents/plugins/stream/connections.py:169
Minor · Functional Correctness · Quick win

Reject user-named calls from device clients before the request.

acting_for does not raise. _client builds and returns a client for any user_id, so a user-token device client that passes user_id still sends its request. The PR requires a ValueError before any request is made. Every method that uses _client, such as delete at line 161, has the same gap.

Check self._backend.server_side in _client and raise before the user is applied. The property already separates server-side backends from device backends.

Suggested fix

     def _client(self, user_id: Optional[str]) -> AuthenticatedClient:
         """The generated client acting for ``user_id``, replacing whoever this client acts
         for. Without one it acts for nobody extra: the user the client was built for stays."""
         if user_id:
+            if not self._backend.server_side:
+                raise ValueError(
+                    "a device client cannot act for another user; use a server-side client"
+                )
             return acting_for(self._backend, user_id).client()
         return replace(self._backend, acting_for="").client()
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 452a64e and 099495e.

Files selected for processing: 9

  • .claude/skills/sdk/SKILL.md
  • CHANGELOG.md
  • plugins/stream/README.md
  • plugins/stream/tests/test_backend.py
  • plugins/stream/tests/test_client.py
  • plugins/stream/tests/test_router.py
  • plugins/stream/vision_agents/plugins/stream/__init__.py
  • plugins/stream/vision_agents/plugins/stream/_backend.py
  • plugins/stream/vision_agents/plugins/stream/client.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 0 remain after this review.

@kanat
kanat merged commit 367e62e into main Nov 20, 2026
8 checks passed
@kanat
kanat deleted the kanat/ai-3379-python-connections branch November 20, 2026 14:30
kanat added a commit that referenced this pull request Nov 20, 2026
…2102)

## Why

A backend that connects its users' accounts (Linear, GitHub) has only
generated operations in the Ruby SDK (AI-3375). It would set
`X-Stream-User-Id` by hand and keep it equal to `owner.user_id`. The
user is now an optional `user_id:` on each call (AI-3387).

The Go reference,
[#2095](#2095), is MERGED.
Siblings: [#2099](#2099) .NET,
[#2100](#2100) Rust,
[#2101](#2101) PHP,
[#2103](#2103) Python,
[#2110](#2110) JS.

## How it works

```
client.connections                                    (flat, no agents. level)
  .create(connector, label:, user_id:)   POST   /v1/agents/connections
  .authorize(id, return_url:, user_id:)  POST   /v1/agents/connections/{id}/authorizations -> launch_url, handoff_token, expires_at
  .get(id, user_id:)                     GET    /v1/agents/connections/{id}
  .list(connector:, user_id:)            GET    /v1/agents/connections?owner_type=user|app&limit=200 (every page)
  .delete(id, user_id:)                  DELETE /v1/agents/connections/{id}
```

| Call | Owner | `X-Stream-User-Id` |
| --- | --- | --- |
| `user_id: "alice"` | `{type: user, user_id: alice}` | `alice`, on
every call, reads included |
| `user_id` omitted or `""` | `{type: app}` | none from `user_id`; an
empty one drops the `acting_for` user |
| client built with its own `user_id:` | unchanged from base | still
sent (left as base behaves, as in Go) |

What the router answers (`acceleration/internal/api/connections.go`
`mayReach`, `ownerOf`):
- an app's connection is reached by any backend call, whatever `user_id`
it sends;
- a user's connection is reached only naming that user;
- `list` with a user holds only that user's connections.

## Changes

| Piece | Before | After |
| --- | --- | --- |
| `Client#connections` | none | `create` / `authorize` / `get` / `list`
/ `delete`, each with optional `user_id:` |
| `Client#get`, `post`, `put`, `patch`, `delete`, `socket` | the
backend's user only | optional `user_id:` last; `nil` keeps the
backend's user, `""` drops it |
| `Backend#acting_for` | public | still works, `@deprecated`, points at
`user_id:` |
| `Dispatch#answer` | `backend.acting_for` | `backend.acting` (`@api
private`), same requests |
| `Backend#headers` | no argument | optional `acting_for:` keyword |
| `README.md`, `CHANGELOG.md`, `.claude/skills/sdk/SKILL.md` | | a
section, one line, one note for the other SDKs |

Wrappers callers used `acting_for` for: `git grep -n acting_for --
sdks/ruby examples docs '*.md'` finds one caller, `Dispatch#answer`.
README, examples and docs name none. So `user_id:` sits on every request
level (the six `Client` verbs) and on each `connections` method.

## Validation

`docker run --rm -v "$PWD:/repo" -v va-ruby-bundle:/usr/local/bundle -w
/repo/sdks/ruby ruby:4.0 sh -c "bundle install && bundle exec rake"`:
249 runs, 1074 assertions, 0 failures (base: 230). Run on head
`ed95799c9` by the round-2 reviewer. The later commits only merge main
and restore main's CHANGELOG lines.

The stand-in `LocalRouter` records every request's method, path, body
and headers.

| Test | Defect it catches |
| --- | --- |
| `test_a_user_s_connection_names_the_user_as_owner_and_header` | owner
and header differ, or one has no user |
| `test_no_user_is_the_app_s_connection_with_no_header` | an app
connection sent with a user |
| `test_the_user_given_wins_over_whoever_the_client_acts_for` | the
deprecated acting user overrides the parameter |
| `test_authorize_without_a_user_on_an_acting_client_names_nobody` |
authorize keeps the acting user (`.to_s` dropped) |
| `test_list_without_a_user_on_an_acting_client_names_nobody` | list
keeps the acting user |
| `test_delete_without_a_user_on_an_acting_client_names_nobody` | delete
keeps the acting user |
| `test_create_sends_the_connector_given` | connector hard-coded |
| `test_authorize_sends_the_return_url_and_answers_the_consent` | return
URL dropped; launch URL, token or expiry lost |
| `test_get_and_delete_name_the_user_only_when_given` | get/delete
header missing or sent without a user |
| `test_list_reads_every_page_of_the_user_s_connections` | one page
read; header missing on a page |
| `test_list_without_a_user_is_the_app_s_and_names_nobody` | wrong
`owner_type`, or a header on the app list |
| `test_list_stops_on_a_page_that_has_no_more_or_no_cursor` | endless
paging |
| `test_an_empty_id_is_refused_before_sending` | an empty id sent as a
bare collection path |
| `test_another_user_s_connection_is_the_router_s_not_found` | a refusal
returned as success |
| `test_a_user_given_is_named_with_the_client_s_own_credential` | user
sent with the wrong credential, on each verb and the socket |
| `test_an_empty_user_names_nobody_even_on_a_client_acting_for_one` | an
empty `user_id:` keeps the acting user |
| `test_a_user_that_is_not_text_is_sent_as_text` | `headers` fails on a
non-String user |
| `test_a_request_without_a_user_is_the_one_sent_before` | backward
compatibility: every verb, the socket and `Backend#headers` send what
base `fa2a6a66d` sent |
| `test_dispatch_answers_for_the_writer_and_for_nobody_as_before` |
`Dispatch#answer` changes its requests |

Mutations: the author's 35 mutants, all killed (`mut/run-1.log`); the 5
survivors of round 1 are killed by the round-1 fix, 0 of 5 survive in
round 2. Two round-1 mutants are equivalent (reviewer-1.md).

Live on the staging router (`live/run-1.log`): create (pending, user
owner), authorize (launch URL, handoff token, expiry), get, get without
the user and as another user (`connection_not_found`), list (the user's
one, not in the app's list), delete. Nothing left behind.

## Review rounds

| Round | Verdict | Findings | Sha |
| --- | --- | --- | --- |
| 1 | NO-GO | R1.1 (five surviving mutants, tests added), R1.2 (docs on
empty `user_id:` fixed) | `3e01c84b6` |
| 2 | GO | no Blocker, no Should fix; Nit: test count in this body
(updated above) | `ed95799c9` |

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 20, 2026
…Id (#2110)

## Why

A backend that connects its users' accounts (Linear, GitHub) had only
generated operations in the JS SDK (AI-3375, AI-3378). It would set
`X-Stream-User-Id` by hand and keep it equal to `owner.user_id`. The
user is now an optional `userId` on each call, never a client of its own
(AI-3387).

The Go reference,
[#2095](#2095), is MERGED.
Siblings: [#2099](#2099) .NET,
[#2100](#2100) Rust,
[#2101](#2101) PHP,
[#2102](#2102) Ruby,
[#2103](#2103) Python.

## How it works

```
api.connections            (server side only)
├── create(connectorId, { label?, userId? })   POST   /v1/agents/connections
├── authorize(id, { returnUrl?, userId? })     POST   /v1/agents/connections/{id}/authorizations
├── get(id, { userId? })                       GET    /v1/agents/connections/{id}
├── list({ connectorId?, userId? })            GET    /v1/agents/connections   (every page, 200 a page, newest first)
└── delete(id, { userId? })                    DELETE /v1/agents/connections/{id}
```

| `userId` | body / query | header | credential |
| --- | --- | --- | --- |
| given | `owner: {type: user, user_id}`, `owner_type=user` |
`X-Stream-User-Id` on every call, reads included | the app's server
token |
| left out or `""` | `owner: {type: app}`, `owner_type=app` | none added
| the client's own |

- A client built with `BackendOptions.userId` still sends that user on a
call without `userId`, as on its other calls.
- A client built on the deprecated `actingFor` drops its user on a call
naming none: the call is the app's.
- `userId` on a client that is not server side (a device, or a page on a
customer-id router) is a `ConfigurationError` before any request. A
server reached by customer id may name a user.

What the router answers (`acceleration/internal/api/connections.go`
`mayReach`, `ownerOf`, `listConnections`):
- the app's connections are reached whatever `userId` a call names;
- another user's is not found;
- `list({ userId })` holds only that user's.

No `force`, `auth_scheme`, `inputs` or all-users list.

## Changes

| Piece | Before | After |
| --- | --- | --- |
| `api.connections` | none | `create`, `authorize`, `get`, `list`,
`delete`, each with an optional `userId` in the options object |
| `Backend.actingFor` | public | public and working, `@deprecated`,
points at `userId` |
| `Backend.speakingFor` | none | `@internal`: the old `actingFor` body;
used by `connections` and `Dispatch.answer` (`src/dispatch.ts:264`) |
| Public wrappers that used `actingFor` | | none: `git grep -n
actingFor` over `sdks/js`, `examples/`, `docs` finds only
`Dispatch.answer` (internal) and tests. Every new parameter is optional
and last |
| `README.md`, `CHANGELOG.md`, `.claude/skills/sdk/SKILL.md` | | a
section, one entry, one note |

## Validation

`cd sdks/js && npm ci && npm test` (the SDK's real HTTP test router,
with a stand-in for the router's owner rule that records every request):
745/745 pass at `eaee43956` (fixer 2). Round 2 on `246c2dab7`: `npm ci`,
`types --check`, `npm test` 744/744, build: all exit 0.

| Test (`tests/connections.test.ts`) | Defect it catches |
| --- | --- |
| `names a user's connection as its owner and as the user acted for, so
the router takes it` | owner and header differ |
| `still speaks as the app's backend for a user, since a user's own
token is refused here` | a user token sent instead of the server one |
| `sends the user on every call about their connection, reads included`
| a call without its user |
| `names no user for the app's own connection, on any call` | a header
on an app call |
| `reads an empty user id as the app, rather than as a user nobody is` |
`""` taken as a user |
| `reaches the app's connection whoever it names, and only a user's own`
| reach rule broken |
| `lists every page of one user's connections, newest first, and not the
app's or another user's` | one page only; wrong owner |
| `stops at a page that says it is the last, or that gives no cursor to
go on from` | endless paging |
| `keeps one connector's when asked, and asks for every connector's
otherwise`; `asks for the connector it was given, and every connector's
for an empty one` | connector dropped or hard-coded |
| `leaves a label out of the request when none is given`; `sends the
label it was given` | label sent empty or lost |
| `sends the return URL it was given, and the user without one` | return
URL lost |
| `refuses a call naming no connection before asking the router` | an
empty id sent |
| `leaves a client built for a user sending that user when a call names
none, as its other calls do`; `keeps a client's own user when a call
names the empty user` | the client's own user cleared |
| `drops the deprecated actingFor user on a call naming none, so the
call is the app's` | the deprecated user leaks into an app call |
| `refuses to name a user on a device, which holds its own user's token`
| a device or page acting as a backend |
| `lets a server reached by customer id name a user, since it holds no
user's token` | the refusal widened to customer-id servers |
| `is still reached through the deprecated actingFor, sending what it
sent before userId` | backward compatibility: four backend shapes send
what base `fa2a6a66d` sent |

The existing dispatch test still asserts `answer`'s request unchanged.

Mutations: the author's 28 killed (`mutations.log`, `mutate.py`; three
paging ones by the 20 s test timeout). Round 2 reran the round-1 set:
all killed but two surviving mutants that are moved base code or
equivalent. Round 2's M3 survived, then was killed by the new row.

Live on the staging router, test user: connection to `linear`: create,
authorize, get (pending), list, delete; nothing left behind.

## Review rounds

| Round | Verdict | Findings | Sha |
| --- | --- | --- | --- |
| 1 | NO-GO | R1.1 `userId` refused off a server, R1.2 deprecated user
dropped on a no-user call, R1.3 six surviving mutants, R1.5 changelog
`(#2110)`: fixed; R1.4 `@internal` not stripped from dist, X1 cross-SDK
device check: tickets | `3fefe3055` |
| 2 | NO-GO (R2.1 Should fix) | R2.1 customer-id server refusal pinned
(`d96b127d7`), R2.2 changelog blank line (`eaee43956`): fixed |
`246c2dab7` |
| 3 | GO | R2.1 and R2.2 closed; M3 re-run and killed by the new row; no
new findings
([review](#2110 (review)))
| `77b528d78` |

Head `77b528d78` adds a main merge and restores main's CHANGELOG lines.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 20, 2026
)

## Why

A backend that connects its users' accounts (Linear, GitHub) has only
generated operations in the .NET SDK (AI-3375). It would set
`X-Stream-User-Id` by hand and keep it equal to `owner.user_id`. The
user is now an optional `userId` on each call (AI-3387).

The Go reference,
[#2095](#2095), is MERGED.
Siblings: [#2100](#2100) Rust,
[#2101](#2101) PHP,
[#2102](#2102) Ruby,
[#2103](#2103) Python,
[#2110](#2110) JS.

## How it works

```
VisionAgentsClient.Connections                                     (flat, no agents level)
 ├─ CreateAsync(connectorId, NewConnectionOptions?{Label, UserId})  POST   /v1/agents/connections
 ├─ AuthorizeAsync(id, AuthorizeOptions?{ReturnUrl, UserId})        POST   /v1/agents/connections/{id}/authorizations
 ├─ GetAsync(id, userId?)                                           GET    /v1/agents/connections/{id}
 ├─ ListAsync(ConnectionFilter?{ConnectorId, UserId})               GET    /v1/agents/connections (every page, limit 200)
 └─ DeleteAsync(id, userId?)                                        DELETE /v1/agents/connections/{id}
```

| `userId` / `UserId` | `owner` (create) | `X-Stream-User-Id` | list
`owner_type` |
| --- | --- | --- | --- |
| `"alice"` | `{type: user, user_id: alice}` | `alice`, every call,
reads included | `user` |
| `null` or `""` | `{type: app}` | none from the parameter; a client's
own `UserId` option is left as it is | `app` |

- Create, authorize and list take sealed options records, so a user
cannot land where a label or connector belongs. Get and delete take
`string? userId` last, before the `CancellationToken`.
- A user goes through the internal `ActingFor` that Dispatch already
uses: the server credential plus `X-Stream-User-Id`.
- An empty connection id is refused before any request is sent.

What the router answers (`acceleration/internal/api/connections.go:742`
`mayReach`):
- a backend reaches app connections whatever user it sends;
- a user's connection is reached only with that user;
- a list with a user holds only that user's connections.

## Changes

| Piece | Before | After |
| --- | --- | --- |
| `VisionAgentsClient.Connections` | none | `CreateAsync`,
`AuthorizeAsync`, `GetAsync`, `ListAsync`, `DeleteAsync` |
| `NewConnectionOptions`, `AuthorizeOptions`, `ConnectionFilter` | none
| sealed records with `UserId` (Go's `ConnectionRequest`,
`AuthorizeOptions`, `ConnectionFilter`) |
| `Backend.Acting`, `VisionAgentsClient.ActingFor` | internal |
unchanged, still internal: no public helper, so nothing to deprecate and
no `[Obsolete]` |
| Existing public wrappers | | none built on an acting helper (grep of
`sdks/dotnet`, its README, `examples/`, `docs/`), so none got a `userId`
|
| `README.md`, `CHANGELOG.md`, `.claude/skills/sdk/SKILL.md` | | a
section "A user's own accounts", one entry, one note |

`Backend` is `internal sealed class` (`Backend.cs:143`); `ActingFor` is
`internal` (`VisionAgentsClient.cs:125`), its only caller is Dispatch
(`Dispatch.cs:218`). The backward-compatibility test of the brief
therefore does not apply (decision Q0.1).

## Validation

Full suite in Docker: 323 total, 316 passed, 7 skipped (live), 0 failed
(base: 309, 302, 7). `ConnectionsTests` runs on the existing Kestrel
`TestRouter`, which records method, path, query, headers and body of
every request, reads included.

| Test | Defect it catches |
| --- | --- |
| `AUserGivenIsTheOwnerAndTheHeaderOnEveryCallReadsIncluded` | owner and
header differ, or a call drops the user; list query not
`owner_type=user` |
| `NoUserIsTheAppsOwnConnectionAndSendsNoHeader` (null and `""`) | app
connection sent with a user or header; authorize body not `{}` |
| `EmptyOptionalStringsAreLeftOutAndTheOwnerIsTheUserGiven` | empty
label or return URL sent; owner `user_id` hard-coded |
| `ABackendActingForAUserKeepsItsServerCredential` | user token replaces
the server token, direct or behind the proxy |
| `AUserGivenReplacesTheOneTheClientWasMadeForAndNoneLeavesItAsItIs` |
the given user ignored; an empty one changes the client's own user |
| `AListReadsEveryPageWithTheSameFilter` (and a theory on stop
conditions) | one page read; filter lost on later pages; endless paging
|
| `AFilterWithAConnectorAndNoUserListsTheAppsConnectionsOfThatConnector`
| connector dropped, or wrong `owner_type` |
| `AConnectionIdIsOnePathSegment` | an id not escaped into one path
segment |
| `AnEmptyConnectionIdIsRefusedBeforeAnythingIsSent` | an empty id sent
as a bare collection path |
| `AnotherUsersConnectionIsTheRoutersNotFound` | a 404 or 409 returned
as success instead of `RouterException` |

Mutations: 17 mutants on `Connections.cs` plus 16 on the options and
empty-string rules (author, round 1 and fix 1); round 2 reran 11, 0
survived. One fix-1 mutant did not build, a rerun was killed
(`mut-fix1.log`).

Live on staging with a test user: create linear (pending, owner `user`),
authorize (https launch URL, handoff token, 10 minute expiry), get, list
with the user holds it and the app list does not, get as another user
and with no user are 404 `connection_not_found`, delete; the user ends
with 0 linear connections, as before (`live/live-fix1.log`).

## Review rounds

| Round | Verdict | Findings | Sha |
| --- | --- | --- | --- |
| 1 | not a GO | R1.1 options records (adjacent strings), R1.2 three
surviving mutants, R1.4 changelog `(#2099)`: fixed; R1.3 (a client made
for one user loses its user token when a call names another) is a ticket
| `67c72f990` |
| 2 | NO-GO | R2.1 Blocker: `dotnet format --verify-no-changes` red;
fixed by `c05d9159e`, whitespace only | `a8f964d20` |
| 3 | GO | R2.1 closed (`dotnet format --verify-no-changes` exits 0; the
old lines fail it); no new findings
([review](#2099 (review)))
| `a8991f844` |

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 20, 2026
## Why

A backend that connects its users' accounts (Linear, GitHub) had only
generated operations in the PHP SDK (AI-3375). It would set
`X-Stream-User-Id` by hand and keep it equal to `owner.user_id`. The
user is now an optional `userId` on each call (AI-3387).

The Go reference,
[#2095](#2095), is MERGED.
Siblings: [#2099](#2099) .NET,
[#2100](#2100) Rust,
[#2102](#2102) Ruby,
[#2103](#2103) Python,
[#2110](#2110) JS.

## How it works

```
$client->connections
  ├─ create(NewConnection)                  POST   /v1/agents/connections
  ├─ authorize($id, AuthorizeOptions)       POST   /v1/agents/connections/{id}/authorizations
  ├─ get($id, ?string $userId = null)       GET    /v1/agents/connections/{id}
  ├─ list(ConnectionFilter)                 GET    /v1/agents/connections   (every page, limit 200)
  └─ delete($id, ?string $userId = null)    DELETE /v1/agents/connections/{id}
```

`NewConnection($connectorId, $label, $userId)`,
`AuthorizeOptions($returnUrl, $userId)` and `ConnectionFilter($userId,
$connectorId)` are readonly option objects (Go's `ConnectionRequest`,
`AuthorizeOptions`, `ConnectionFilter`). A string where an object goes
is a `TypeError` before anything is sent, so a user id cannot land in a
label, return URL or connector slot.

| `userId` | owner (create) | `X-Stream-User-Id` | list asks |
| --- | --- | --- | --- |
| `'ada'` | `{type: user, user_id: ada}` | `ada`, every call, reads
included | `owner_type=user` |
| left out or `''` | `{type: app}` | none, whoever the backend otherwise
acts for | `owner_type=app` |

- Behind the proxy the user is a header beside the server token, never a
user token.
- A device backend (`asUser`) and an empty id are refused before a
request is sent.

What the router answers (`acceleration/internal/api/connections.go:742`
`mayReach`):
- an app connection is reached by every backend call, one naming a user
included;
- a user's list holds only theirs.

## Changes

| Piece | Before | After |
| --- | --- | --- |
| `Client::$connections` | none | `Connections`: `create`, `authorize`,
`get`, `list`, `delete` |
| `NewConnection`, `AuthorizeOptions`, `ConnectionFilter` | none |
readonly options objects with `userId` |
| `Backend::onBehalfOf` | public | public and working, `@deprecated` in
favour of the `userId` parameter; calls `writingFor` |
| `Backend::speakingFor($userId)` | none | `@internal`: server
credential plus the header, none when empty (drops the backend's own
user); used by `Connections` |
| `Backend::writingFor($userId)` | none | `@internal`: the old
`onBehalfOf` body; used by `Worker/Dispatch.php:193`, so an empty writer
on a backend built with a user still sends that user, as on base |
| `Backend::actingFor` | signs a user token | unchanged: the device
path, not deprecated |
| Public wrappers that used `onBehalfOf` | | none: `grep -rn onBehalfOf`
over `sdks/php`, README, `examples/`, docs finds only `Dispatch::answer`
(internal) and the sdk skill |
| `README.md`, `CHANGELOG.md`, `.claude/skills/sdk/SKILL.md` | | a
section, one entry, one note |

## Validation

Round-3 reviewer on the head merged onto main, in Docker: `phpunit
--testsuite unit` OK (360 tests, 945 assertions); `phpstan analyse`
(max) no errors; `bin/generate.php ... --check` up to date (round 2).
`ConnectionsTest` runs on the `php -S` stand-in router and checks
method, path, query, body and headers of every request.

| Test | Defect it catches |
| --- | --- |
| `testAUsersConnectionNamesThemAsOwnerAndActingUser` | owner and header
differ, label or user dropped |
| `testAnAppConnectionNamesNoUser` | app connection with a user, or with
the backend's own user |
| `testEveryCallNamingAUserSendsItReadsIncluded` | a call without its
user |
| `testBehindTheProxyTheUserIsAHeaderBesideTheServersToken` | a user
token minted behind the proxy |
| `testWithNoProxyTheCustomerHeaderStaysBesideTheUser` | the customer
header lost |
| `testAuthorizingAnswersWhereAndHowLongTheConsentRuns` | return URL
dropped; launch URL, token or expiry lost |
| `testAStringWhereTheOptionsObjectGoesIsRefusedBeforeSending` | the old
string signature, where a user lands in a label |
| `testListingReadsEveryPageOfOneConnector` | one page only; connector
dropped |
| `testListingStopsOnACursorItAlreadyFollowedOrAnEmptyOne` | endless
paging |
| `testAnAppListByConnectorSendsNoUser`,
`testAnAppAuthorizationWithAReturnUrlSendsNoUser`,
`testAnAppConnectionWithALabelIsOwnedByTheApp` | a user swapped with
connector, return URL or label inside the objects |
| `testAnotherUsersConnectionIsTheRoutersNotFound` | a refusal returned
as success |
| `testRefusedBeforeSending` | a device backend or an empty id sent |
|
`ClientTest::testOnBehalfOfAnEmptyUserKeepsTheUserTheBackendWasBuiltWith`
| `onBehalfOf('')` changes the base request |
| `ClientTest::testADeviceBackendCannotActOnBehalfOfAUser` | the device
refusal of `onBehalfOf` removed |
|
`WorkerTest::testAnswerForAWriterWithoutAnIdKeepsTheUserTheBackendWasBuiltWith`
| `Dispatch::answer` request differs from base for an empty writer |

Backward compatibility: no public wrapper gained a parameter. The
existing `onBehalfOf` tests (`ClientTest`) and `Dispatch::answer` tests
(`WorkerTest`) pass unchanged.

Mutations: the author's 22, 21 killed and 1 equivalent (`mut/run1.log`);
the fixer's N1, N3 and O1-O6 killed; round 2 reviewer's 10 killed; round
3 rerun: 6 checked, 0 survived. Two mutants (an empty label or connector
sent) are equivalent, as the router trims or skips them.

Live on the staging router through the proxy, test user: create linear
(pending, owner user), authorize (consent, launch URL and handoff token
set, 600 s), get, get as another user and as the app are 404
`connection_not_found`, list holds it and the app list does not, delete
then get is 404; 0 left.

## Review rounds

| Round | Verdict | Findings | Sha |
| --- | --- | --- | --- |
| 0 (author question) | decision | R0.1 an empty writer must keep the
backend's own user as on base: fixed | `9fd8394f0` |
| 1 | NO-GO | R1.1 options objects, R1.2 two surviving mutants, R1.3
stale skill note: fixed | `9fd8394f0` |
| 2 | NO-GO | R2.1 three swap mutants (tests added), R2.2 named
`userId:` in docs: fixed | `81c2213cb` |
| 3 | GO | none | `9f649ea85` |

Head `ee224c707` adds main merges and restores main's CHANGELOG lines on
top of the GO sha.

## Questions

- PHP's `Backend::actingFor` signs a user token (the device path). In Go
and JavaScript `actingFor` names the server-side helper, so the same
name differs across SDKs. Left as the brief says.
- `Folder/Connector.php` (`fixedConnection`) has its own page loop over
`GET /v1/agents/connections`. It could call
`$client->connections->list(...)`. Not changed here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 20, 2026
…2100)

## Why

A backend that connects its users' accounts (Linear, GitHub) had only
generated operations in the Rust SDK (AI-3375). It had to build a whole
client with `ClientOptions::user_id` and keep it equal to
`owner.user_id`: the router refuses a user connection when the two
differ (`acceleration/internal/api/connections.go` `ownerOf`). The user
is now an optional `user_id` on each call (AI-3387).

The Go reference,
[#2095](#2095), is MERGED.
Siblings: [#2099](#2099) .NET,
[#2101](#2101) PHP,
[#2102](#2102) Ruby,
[#2103](#2103) Python,
[#2110](#2110) JS.

## How it works

```
client.connections()                                 sdks/rust/src/connections.rs
├─ create(&NewConnection{connector, label, user_id})        -> types::Connection
├─ authorize(id, &AuthorizeOptions{return_url, user_id})    -> types::Authorization (launch_url, handoff_token, expires_at)
├─ get(id, user_id: Option<&str>)
├─ list(&ConnectionFilter{connector, user_id})              owner_type user|app, limit=200, every page
└─ delete(id, user_id: Option<&str>)                        no force
```

| `user_id` | owner (create) | `X-Stream-User-Id` |
| --- | --- | --- |
| `Some("alice")` | `{type: user, user_id: alice}` | `alice`, every
call, reads included |
| `None` or `Some("")` | `{type: app}` | none from the call; a client's
own `ClientOptions::user_id` stays as built (as Go) |

- Options structs (`Default`) rather than adjacent `Option<&str>`, so a
label cannot be swapped for a user.
- A user named goes through the existing `pub(crate) Client::acting_for`
(dispatch's path, `dispatch.rs:374`): it clones the client, sets
`acting_for` and clears `ClientOptions::user_id`.
- An empty id is refused before any request.

What the router answers (`connections.go:742` `mayReach`):
- every backend call reaches an app connection, even one naming a user;
- `list` with a user holds only that user's;
- another user's connection is a 404, as for one that does not exist.

## Changes

| Piece | Before | After |
| --- | --- | --- |
| `Client::connections()` | none | `Connections` with `create`,
`authorize`, `get`, `list`, `delete` |
| `NewConnection`, `AuthorizeOptions`, `ConnectionFilter` | none |
`Default` structs with `user_id`, re-exported in `lib.rs` |
| `Backend.acting_for`, `Client::acting_for` | `pub(crate)` | unchanged:
no public helper, so nothing to deprecate and no `#[deprecated]`
(`backend.rs:189`) |
| Existing public wrappers | | none changed: searched `sdks/rust`,
README, `examples/`, docs. `connections` is the only wrapper taking
`user_id`, so no backward-compatibility test |
| `README.md`, `CHANGELOG.md`, `.claude/skills/sdk/SKILL.md` | | a
section "A user's own accounts", one entry, one note |

## Validation

`cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D
warnings`, `cargo run -p generate -- --check` and `cargo test`, in
`rust:1` per the sdk-rust skill: pass (round-2 reviewer, all 12 test
targets and doctests). The tests use the axum stand-in router
(`tests/support`), which records method, path, query, body and headers.

| Test | Defect it catches |
| --- | --- |
| `a_users_connection_names_them_as_owner_and_acting_user` | owner and
header differ; label dropped; `auth_scheme`/`inputs` sent |
|
`an_app_connection_names_no_owner_and_leaves_the_clients_own_user_as_it_is`
| `None`/`""` sent as a user; a client's own user cleared by a call
naming nobody |
| `every_call_sends_the_user_it_names_and_only_that_one` | header
missing on a call; header without a user; two headers |
| `behind_the_proxy_a_user_is_named_by_the_header_beside_a_server_token`
| a user token minted instead of the server token plus header |
| `authorizing_answers_where_and_how_long_the_consent_runs` | return URL
dropped; launch URL, token or expiry lost |
| `listing_reads_the_owners_connections_every_page` | one page only;
cursor not sent; wrong `owner_type`; connector or limit dropped |
| `a_list_naming_an_empty_user_is_the_apps_not_a_users` | an empty user
listed as `owner_type=user` or sent as a header |
| `the_apps_list_names_no_connector_unless_asked` | app list sent as
user, or with an unasked connector |
| `listing_stops_at_a_page_that_says_no_more_or_names_no_cursor` | a
cursor followed after `has_more: false` or when empty |
| `deleting_a_connection_sends_no_force` | `force` sent |
| `a_connection_with_no_id_is_refused_before_the_router` | an empty id
sent as a bare collection path |
| `another_users_connection_is_the_routers_not_found` | a refusal not
returned as `Error::Router` |

Mutations: the fixer's 22 killed (`fix-1-mutate.log`); round 2 reran
them plus 4 more: 26 checked, 0 survived.

Live on the staging router, test user, connector `linear`, booleans and
statuses only (`live/live-2.log`): create (owner user, pending),
authorize (https launch URL, token, expiry set), get, get as another
user and as the app are 404, list holds it and the app list does not,
delete; cleanup found 0 leftovers.

## Review rounds

| Round | Verdict | Findings | Sha |
| --- | --- | --- | --- |
| 1 | NO-GO | R1.1 options structs, R1.2 surviving list mutant, R1.3
changelog form, R1.4 `None` keeps the client's own user: all fixed |
`bbf74b9fd` |
| 2 | GO | no new findings | `b2083269b` |

Head `eca728e67` adds a main merge and restores main's CHANGELOG lines
on top of the GO sha.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 20, 2026
## Why

`Backend.speakingFor` (added in #2110) is tagged `@internal`, but the
package has no `stripInternal`, so `dist/backend.d.ts` published it as a
method of the public `Backend`, beside the deprecated `actingFor` it
duplicates. AI-3411.

`stripInternal` was not used. It would hide the 15 `@internal` symbols
that the published 0.5.0 `.d.ts` already exposes (`onRetry`, `Tools.of`,
`Conversation.said`/`observe`, `Session.cameraFrames`,
`LiveUI.observeTurns`, ...), which breaks published types. `speakingFor`
itself is not in 0.5.0.

Checked: `npm pack @stream-io/stream-agents@0.5.0`, then `grep -rl
@internal dist --include=*.d.ts` finds 15 tags.

## How it works

```
before: Backend.speakingFor(userId)      -> on the type, autocompleted
after:  speakingFor(backend, userId)     -> module function in backend.ts, no entry point re-exports it
        Backend.actingFor(userId)        -> calls it, same copy, same request
```

- `speakingFor` is a module function in `sdks/js/src/backend.ts`. No
entry point re-exports it: the test covers the five entry points (`.`,
`./node`, `./chat`, `./video`, `./react`) and `Backend`'s statics.
- `package.json` `exports` has only those five paths, so a consumer
cannot import `dist/backend.js`. The copy is the same code; its private
fields are reached by name (`acting["fetched"]`).

## Changes

- `sdks/js/src/backend.ts`: `speakingFor` becomes a module function;
`actingFor` calls it. The actsFor and actingForValue docs name
`actingFor`.
- `sdks/js/src/connections.ts`, `dispatch.ts`: call the function.
- `sdks/js/tests/backend.test.ts`: `@ts-expect-error` on
`backend.speakingFor`; `actingFor` still works; `speakingFor` absent
from all five entry points and from `Backend`'s statics.
- `sdks/js/tests/token.test.ts`: a copy acting for another user carries
neither the original's fetched token nor its user.
- `.claude/skills/sdk/SKILL.md` line 789 (AI-3413): a user's team is no
longer said to be `for_user(team=)`. It names `create_user_token(...,
team=)` and `user_id=` on `Client.agent`/`Client.router` of a client
built with `team=`/`usage_categories=`; `for_user` is deprecated
(#2103). Line 936: `speakingFor` is named as a module function in
`backend.ts`.
- No CHANGELOG entry: `speakingFor` was never released, so nothing
user-visible changes.

## Review rounds

| Round | Verdict | Findings | Fixed in |
|---|---|---|---|
| R1 | NO-GO | R1.1 no test that keeps `speakingFor` off the exports;
R1.2 actsFor/actingForValue docs named `speakingFor`; R1.3 SKILL.md:936
still called it a `Backend` method | 5430d99 |
| R2 | NO-GO | R2.1 test checked two of the five entry points; chat,
video and react re-exports survived | 788302d |
| R3 | GO | Orchestrator check: delta 5430d99..788302d is test-only
(+6); chat, video and react re-export mutants each fail; head 50/50 |
(no change) |

Follow-ups: `Tools.failure`, `ToolCalls.observe`, `offerTool` are
unreleased and published the same way, ticketed as AI-3451.

## Validation

- `cd sdks/js && npm run types -- --check && npm test` on 788302d: 794
pass, 0 fail.
- CI on 788302d: `sdks` pass, plus CodeQL, Analyze
(actions/go/python), GitGuardian and labeler, all pass.
- Mutations, each killed by a test: re-adding the method (tsc: unused
`@ts-expect-error`); a re-export of `speakingFor` from `index`, `node`,
`chat`, `video` or `react`; a `static speakingFor` on `Backend`;
dropping the `userIdValue`, `user`, `fetched` or `fetching` reset; each
of the three call sites (`connections.ts` x2, `dispatch.ts`).

AI-3411, AI-3413.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant