teams_rb 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +39 -1
  3. data/docs/README.md +1 -1
  4. data/docs/essentials/README.md +1 -1
  5. data/docs/essentials/on-event.md +12 -2
  6. data/docs/essentials/sending-messages.md +7 -4
  7. data/docs/in-depth-guides/README.md +2 -0
  8. data/docs/in-depth-guides/agent-365.md +3 -1
  9. data/docs/in-depth-guides/files.md +99 -0
  10. data/docs/in-depth-guides/state.md +59 -0
  11. data/docs/in-depth-guides/streaming.md +6 -5
  12. data/docs/in-depth-guides/user-authentication.md +36 -8
  13. data/lib/teams/activity_context.rb +118 -15
  14. data/lib/teams/api/citation_appearance.rb +10 -2
  15. data/lib/teams/api/file_download_info.rb +34 -0
  16. data/lib/teams/api/message_activity.rb +37 -12
  17. data/lib/teams/api/sensitivity_usage_info.rb +38 -0
  18. data/lib/teams/app.rb +195 -153
  19. data/lib/teams/auth/jwt_validator.rb +17 -2
  20. data/lib/teams/cards/generated.rb +430 -430
  21. data/lib/teams/errors.rb +175 -4
  22. data/lib/teams/files/downloaded_file.rb +35 -0
  23. data/lib/teams/files/downloader.rb +405 -0
  24. data/lib/teams/files/files_accessor.rb +175 -0
  25. data/lib/teams/files/graph_share.rb +44 -0
  26. data/lib/teams/files/incoming_file.rb +128 -0
  27. data/lib/teams/files/inline_image.rb +88 -0
  28. data/lib/teams/files.rb +8 -0
  29. data/lib/teams/http_stream.rb +28 -28
  30. data/lib/teams/oauth/flow.rb +184 -0
  31. data/lib/teams/oauth/handlers.rb +376 -0
  32. data/lib/teams/oauth/pending_sign_ins.rb +300 -0
  33. data/lib/teams/oauth.rb +5 -0
  34. data/lib/teams/state/turn_state.rb +163 -0
  35. data/lib/teams/state/turn_state_container.rb +54 -0
  36. data/lib/teams/state/turn_state_loader.rb +143 -0
  37. data/lib/teams/state.rb +5 -0
  38. data/lib/teams/version.rb +1 -1
  39. data/lib/teams.rb +5 -0
  40. metadata +20 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1502c7094dd98f8e69bfc496dbc8887273cda01eefb1729ff20d480f2e490d24
4
- data.tar.gz: 13bdd7a69d783a0e7421c0ea9a2d1b6e5c364dfd89b1ccdbb38c7afa832008a6
3
+ metadata.gz: dd209c7e8203d20e777eafe28b30dbdb166c316f7f03afa93a01ad279eeb5634
4
+ data.tar.gz: ff5a8586dfb0db37b27f7dece214bf652a7b872f30b0c9a30c336e6d70f5947d
5
5
  SHA512:
6
- metadata.gz: cceee102720b9bee0243602582c815ba0deeb3b8b23f7580c324b72b6b1a4431083ec68926677887acd4d3780520d31be30460499d9d2868b1adeb9f60ef671e
7
- data.tar.gz: 71df520f4b46f72ec60919a9c0cf2403d5a0e7b5e7118503130a3ca9e77cd8d933a5841040078ddde03c8188a06a6db4c8e369e1c7e334237c0e6db432c74433
6
+ metadata.gz: c88e73cd9cb04de3685ac6caf5ca316cbd3a93fb09ba76a2826e7362d2704b34f354d2544ff892887fb6254afe62465b52bb6f24c31a247006d1a2f24a125c17
7
+ data.tar.gz: 44209fe95b43d9aa551df3f5d80796e69bd04625ee26dc335e49907af87e602bc08f76d579700334d32756835de98af94222b6b9b6a332349bea9c71e96c9182
data/CHANGELOG.md CHANGED
@@ -6,6 +6,43 @@ All notable changes to this project are documented in this file. The format foll
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [2.1.0] - 2026-11-05
10
+
11
+ ### Added
12
+
13
+ - `ctx.stream.update(text, text_format:)` sets the text format of an informative update, matching the TypeScript, Python, and .NET SDKs
14
+ - Receiving files: `ctx.files` lists the inbound activity's uploaded files (`list`/`first`) as lazy `Files::IncomingFile` handles with `download` (a `Files::DownloadedFile` snapshot), `text`, `save_as`, and `stream`; downloads are plain GETs with no bot token, following redirects only over HTTPS. Typed `Teams::FileError` subclasses: `FileUrlExpiredError` (`reason` `first_fetch`/`reread`) and `FileScopeNotSupportedError`. Adds `Api::FileDownloadInfo` and `Api::FILE_DOWNLOAD_INFO_CONTENT_TYPE`. Matches the TypeScript, Python, and .NET SDKs
15
+ - Agentic users receive files in personal chats, group chats, and channels: files that arrive with only a `content_url` are read through Microsoft Graph `/shares` with the agent's own token (never the app's), with `FileCredentialError` (no usable Graph credential, detected before the request; `actor`, `cause_detail`) and `FileAccessError` (refused by storage; `status`, `actor`, `details`). Matches the TypeScript, Python, and .NET SDKs
16
+ - Pasted inline images are listed by `ctx.files` with `attachment_style` `"inlineImage"` (named from the message's HTML format hint; downloads report the format the bytes actually are), read from the Bot API with the turn's token and only under the activity's service URL; `list`/`first` accept `attachment_style:` to filter. Adds `InlineImageTransformationError` (415) and `InlineImageAccessError` (401/403). Matches the TypeScript, Python, and .NET SDKs
17
+ - Per-turn state (opt-in `state:` App option, `true` or `State::StateOptions`): `ctx.state.conversation` and `ctx.state.user` are Hash-like `State::TurnState` scopes loaded before the handlers and saved after the turn (also when a handler raised) only when their content changed, including nested changes; emptied scopes are deleted, `ctx.state.delete` removes both, and the state is sealed after the turn (`State::TurnStateSealedError`). Stored as JSON under percent-encoded `{prefix}:conv:{conversationId}` / `{prefix}:user:{conversationId}:{userId}` keys in the app's storage or a dedicated one. Matches the TypeScript, Python, and .NET SDKs
18
+ - Multiple OAuth connections: `app.add_oauth_flow(name, oauth_card_text:, sign_in_button_text:)` registers an `OAuth::Flow` (case-insensitive, unique names; `app.get_oauth_flow` looks one up) with connection-bound `sign_in`, `sign_out`, `get_token`, `signed_in?`, and per-flow `on_sign_in`/`on_sign_in_failure` handlers; `app.on_oauth_sign_in_failure` receives an `OAuth::SignInFailureEvent`; `ctx.get_user_token(connection_name:)` and `ctx.get_connection_status`. Registering a flow enables per-turn state unless `state:` was set. Matches the TypeScript, Python, and .NET SDKs
19
+ - OAuth callbacks route to their registered flow: `ctx.sign_in` records the pending sign-in (in per-turn state, or a bounded process-local cache when state is off), token exchanges reach the flow they name, `signin/verifyState` probes pending flows, then registered flows, then the default connection, and `signin/failure` is attributed to the pending silent-SSO sign-in (or reported to every flow with `connection_name` `nil` when it cannot be). Terminal Token Service errors notify the flow's failure handlers (`code` `tokenservice.http_<status>`). Matches the TypeScript, Python, and .NET SDKs
20
+ - Microsoft Purview sensitivity labels: `Api::SensitivityUsageInfo` (`at_id` label id sent as `@id`, optional `name`/`description`/`position`, `at_type` defaulting to `CreativeWork`), `add_sensitivity_label(label)` writing it to the root message entity (replacing any earlier label), and citation `usage_info:` accepting it (citation usage info now defaults `@type` to `CreativeWork`). Matches the TypeScript, Python, and .NET SDKs
21
+
22
+ ### Changed
23
+
24
+ - Targeted sends are no longer rejected by the SDK in 1:1 (personal) conversations; the Teams service decides whether a targeted message is valid (a plain 1:1 bot chat answers 400 `BadArgument`), matching the same change in the TypeScript, Python, and .NET SDKs
25
+ - Teams no longer supports stopping a stream, so stream cancellation handling is removed: a 403 mentioning cancellation is a `TerminalStreamError` like any other terminal stream failure, emits after it keep working, and the streaming time limit is documented as ten minutes. Matches the TypeScript, Python, and .NET SDKs
26
+ - `signin/verifyState` answers 404 (instead of 412) when no connection accepts the code, and token-exchange deduplication now also holds across instances through conversation state, expires completed exchanges after five minutes, and answers an in-flight duplicate with 412 when the original exchange raised. Matches the TypeScript and Python SDKs
27
+ - `ctx.sign_in` falls through to the OAuth card only when the Token Service answers 404 (no token); other Token Service failures now raise instead of being treated as a signed-out user, matching the Python SDK
28
+ - Adaptive Card classes no longer serialize schema defaults for optional fields the caller never set (for example `theme`, `fillMode`, `horizontalAlignment`, `requires`), which roughly tripled payload size; `version` keeps its `1.5` default and explicitly set values, including `false`, still serialize. Regenerated from the same generator change in the TypeScript, Python, and .NET SDKs
29
+
30
+ ### Deprecated
31
+
32
+ - `app.on_sign_in` is renamed `app.on_oauth_sign_in` (same block arguments): app-level OAuth events now carry the `on_oauth_` prefix, like `app.on_oauth_sign_in_failure`, which keeps them apart from the `on_signin_*` invoke routes. The old name still works and emits a deprecation warning.
33
+ - `HttpStream#canceled` always returns false, and `Teams::StreamCancelledError` is never raised
34
+ - `add_sensitivity_label(name, description:, pattern:)` with a label name string; it writes a name-only label without the Purview label id. Pass an `Api::SensitivityUsageInfo` instead
35
+
36
+ ### Fixed
37
+
38
+ - `ctx.reply` quotes the inbound message only when its id is a plain numeric message id (digits, not all zeros). Invokes, card-button messages, and feedback carry service-generated ids such as `f:<guid>` that the service rejects as quote targets with 400, so `ctx.reply` failed in card, dialog, and feedback handlers; it now sends without a quote there, exactly like `ctx.post`. Matches the same fix in the TypeScript, Python, and .NET SDKs
39
+ - Streamed text chunks carry the `textFormat` of the last emitted message, so streamed extended markdown (task lists, strikethrough) no longer renders as plain markdown until the message closes. Matches the same fix in the TypeScript, Python, and .NET SDKs
40
+ - Targeted message updates no longer send `recipient` in the payload (the recipient of an existing targeted message cannot change; it only selects the targeted endpoint); the returned `SentActivity` still carries it. Matches the TypeScript and Python SDKs
41
+
42
+ ### Security
43
+
44
+ - Entra-authenticated inbound activities are accepted only when the token was requested by the Agent 365 platform app: the caller app is read from `azp`, or from `appid` when `azp` is absent, and compared case-insensitively; tokens requested by any other client app are rejected with 401. Bot Framework tokens are unaffected. Matches the same fix in the TypeScript, Python, and .NET SDKs
45
+
9
46
  ## [2.0.3] - 2026-11-05
10
47
 
11
48
  ### Added
@@ -87,7 +124,8 @@ the Python SDK made when it joined the family.
87
124
  - Thread-safe token management, storage, and JWKS caching for multi-threaded Rack servers
88
125
  - Documentation mirroring the official teams-sdk docs structure (getting started, essentials, in-depth guides)
89
126
 
90
- [Unreleased]: https://github.com/bavmind/teams_rb/compare/v2.0.3...HEAD
127
+ [Unreleased]: https://github.com/bavmind/teams_rb/compare/v2.1.0...HEAD
128
+ [2.1.0]: https://github.com/bavmind/teams_rb/compare/v2.0.3...v2.1.0
91
129
  [2.0.3]: https://github.com/bavmind/teams_rb/compare/v2.0.2...v2.0.3
92
130
  [2.0.2]: https://github.com/bavmind/teams_rb/compare/v2.0.1...v2.0.2
93
131
  [2.0.1]: https://github.com/bavmind/teams_rb/compare/v2.0.0...v2.0.1
data/docs/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  - [App basics](essentials/app-basics.md) — configuration, credentials, lifecycle
16
16
  - [Listening to activities](essentials/on-activity.md) — routing, middleware, invokes, meeting events
17
- - [Listening to events](essentials/on-event.md) — `on_sign_in`, `on_error`
17
+ - [Listening to events](essentials/on-event.md) — `on_oauth_sign_in`, `on_oauth_sign_in_failure`, `on_error`
18
18
  - [Sending messages](essentials/sending-messages.md) — `post`, `reply`, `quote`, `update`, `typing`, formatting, mentions
19
19
  - [Proactive messaging](essentials/proactive-messaging.md) — conversation references, creating conversations, threading
20
20
  - [The API client](essentials/api-client.md) — `api.conversations`, `api.teams`, `api.meetings`, `api.users`, `api.bots`
@@ -4,7 +4,7 @@ The concepts every Teams app uses:
4
4
 
5
5
  - [App basics](app-basics.md) — configuration, credentials, lifecycle, storage
6
6
  - [Listening to activities](on-activity.md) — routing, middleware, invokes, the escape hatch
7
- - [Listening to events](on-event.md) — `on_sign_in`, `on_error`
7
+ - [Listening to events](on-event.md) — `on_oauth_sign_in`, `on_oauth_sign_in_failure`, `on_error`
8
8
  - [Sending messages](sending-messages.md) — the send verbs, `SentActivity`, formatting, mentions, labels, citations
9
9
  - [Proactive messaging](proactive-messaging.md) — conversation references, creating conversations
10
10
  - [The API client](api-client.md) — the full `teams.api` surface
@@ -1,19 +1,29 @@
1
1
  # Listening to events
2
2
 
3
- Beyond activity routes, the app emits two application-level events, registered with named methods (the Ruby counterpart of the TypeScript/Python event emitters).
3
+ Beyond activity routes, the app emits application-level events, registered with named methods (the Ruby counterpart of the TypeScript/Python event emitters). OAuth events carry the `on_oauth_` prefix, which keeps them apart from the `on_signin_*` invoke routes.
4
4
 
5
5
  ## Sign-in
6
6
 
7
7
  Fires whenever a user sign-in completes through the default OAuth handlers — both the silent token-exchange path and the interactive card path:
8
8
 
9
9
  ```ruby
10
- teams.on_sign_in do |ctx, token_response|
10
+ teams.on_oauth_sign_in do |ctx, token_response|
11
11
  ctx.post "Welcome! You're signed in."
12
12
  # token_response.token is the user's access token for the
13
13
  # OAuth connection's scopes; ctx is the invoke's activity context
14
14
  end
15
15
  ```
16
16
 
17
+ ## Sign-in failure
18
+
19
+ Fires when the Teams client reports a failed sign-in (the `signin/failure` invoke), with the connection it was attributed to:
20
+
21
+ ```ruby
22
+ teams.on_oauth_sign_in_failure do |event|
23
+ event.context.log.warn("Sign-in failed (#{event.connection_name}): #{event.code} #{event.message}")
24
+ end
25
+ ```
26
+
17
27
  See [User authentication](../in-depth-guides/user-authentication.md) for the full flow.
18
28
 
19
29
  ## Errors
@@ -9,7 +9,7 @@ ctx.quote "message-id", "a reply quoting a specific message"
9
9
  ctx.update "activity-id", "replaces a previous bot message"
10
10
  ```
11
11
 
12
- `post` is Ruby's spelling of the SDKs' `send` (Ruby reserves `Object#send`), with identical semantics — including: an activity that already carries an `id` is **updated** instead of created. `ctx.update` is sugar over exactly that. `reply` adds the Teams quoted-reply entity and placeholder, matching the other SDKs.
12
+ `post` is Ruby's spelling of the SDKs' `send` (Ruby reserves `Object#send`), with identical semantics — including: an activity that already carries an `id` is **updated** instead of created. `ctx.update` is sugar over exactly that. `reply` adds the Teams quoted-reply entity and placeholder, matching the other SDKs — but only when the inbound id is a plain numeric message id (typed messages, edits, deletes, reactions). Invokes and card-button messages carry ids like `f:<guid>` that cannot be quoted, so there `reply` sends exactly like `post`; use `ctx.quote(message_id, ...)` to quote a specific message.
13
13
 
14
14
  All sends accept a String, a `Teams::Api::MessageActivity`, an Adaptive Card, or a raw activity Hash (symbol or string keys — they're normalized).
15
15
 
@@ -32,14 +32,17 @@ ctx.update sent.id, "Done!"
32
32
  ```ruby
33
33
  ctx.post Teams::Api::MessageActivity.new("**markdown**", text_format: "markdown")
34
34
  # text_format: plain | markdown | xml | extendedmarkdown
35
- # ("extendedmarkdown" is in public preview and may be subject to change)
35
+
36
+ label = Teams::Api::SensitivityUsageInfo.new(at_id: purview_label_id, name: "Confidential")
36
37
 
37
38
  ctx.post Teams::Api::MessageActivity.new("Quarterly numbers")
38
39
  .add_ai_generated # "AI generated" badge
39
- .add_sensitivity_label("Confidential", description: "Internal only")
40
+ .add_sensitivity_label(label) # Purview sensitivity label shield
40
41
  .add_feedback # thumbs up/down feedback buttons
41
42
  ```
42
43
 
44
+ Sensitivity labels are identified by their Microsoft Purview label id (`at_id`); Teams resolves the label's display name and description from it, using `name` only as a fallback. A citation can carry its own label through `usage_info:`. The older `add_sensitivity_label("Confidential", description: ...)` name-only form still works but is deprecated.
45
+
43
46
  Mentions:
44
47
 
45
48
  ```ruby
@@ -70,7 +73,7 @@ ctx.typing # animated ellipsis in the chat
70
73
 
71
74
  ## Targeted messages
72
75
 
73
- When the inbound message targets the bot (`recipient.isTargeted`), `ctx.post` and `ctx.reply` automatically answer as targeted messages visible only to that user, matching TypeScript/Python — including the `targetedMessageInfo` entity and the targeted API routes. Targeted messages aren't supported in 1:1 chats (the SDK raises).
76
+ When the inbound message targets the bot (`recipient.isTargeted`), `ctx.post` and `ctx.reply` automatically answer as targeted messages visible only to that user, matching TypeScript/Python — including the `targetedMessageInfo` entity and the targeted API routes.
74
77
 
75
78
  ## Delivery semantics
76
79
 
@@ -8,6 +8,8 @@ Feature guides for building richer Teams apps:
8
8
  - [Feedback](feedback.md) — thumbs up/down on bot messages
9
9
  - [Message reactions](message-reactions.md) — sending and receiving reactions
10
10
  - [Streaming](streaming.md) — chunked responses, informative updates, events, typed errors
11
+ - [Receiving files](files.md) — `ctx.files`: listing, downloading, and streaming attached files
12
+ - [State](state.md) — per-turn conversation and user state (`ctx.state`)
11
13
  - [User authentication](user-authentication.md) — OAuth sign-in, token exchange, Azure setup
12
14
  - [Tabs and remote functions](tabs.md) — calling the bot backend from a tab with SSO
13
15
  - [Agent 365](agent-365.md) — running as an agentic user (experimental)
@@ -13,7 +13,9 @@ instantiate **agentic apps** from it, and each app can carry **agentic users**
13
13
  Nothing to configure. When Teams delivers an activity to an agentic user, the
14
14
  identity arrives on the activity's `recipient` account and the request carries
15
15
  an Entra-issued token (accepted automatically alongside classic Bot Framework
16
- tokens). The SDK scopes the whole turn to that identity — `ctx.post`, replies,
16
+ tokens, but only when the Agent 365 platform requested it — Entra tokens from
17
+ any other client app are rejected with 401). The SDK scopes the whole turn to
18
+ that identity — `ctx.post`, replies,
17
19
  and streaming authenticate as the agent, not the app:
18
20
 
19
21
  ```ruby
@@ -0,0 +1,99 @@
1
+ # Receiving files
2
+
3
+ When a user attaches a file to a message, Teams stores it in OneDrive or SharePoint and hands your bot a small metadata attachment describing it. `ctx.files` turns those attachments into lazy `Teams::Files::IncomingFile` handles: listing makes no network requests, and the bytes are fetched only when you ask for them.
4
+
5
+ ## Enable file support in your manifest
6
+
7
+ Teams only offers the attach button in a 1:1 chat with your bot when the manifest opts in:
8
+
9
+ ```json
10
+ "bots": [
11
+ {
12
+ "botId": "${{BOT_ID}}",
13
+ "scopes": ["personal"],
14
+ "supportsFiles": true
15
+ }
16
+ ]
17
+ ```
18
+
19
+ Without it no file reaches your handler and `ctx.files.list` is always empty.
20
+
21
+ For an [Agent 365](agent-365.md) agentic user, an administrator must consent a Graph file permission (such as `Files.Read.All`) on the agent's blueprint instead — see [inheritable permissions](https://learn.microsoft.com/entra/agent-id/concept-inheritable-permissions).
22
+
23
+ ## Access attached files
24
+
25
+ ```ruby
26
+ teams.on_message do |ctx|
27
+ files = ctx.files.list
28
+ next ctx.reply("Send me a file and I will read it.") if files.empty?
29
+
30
+ ctx.reply "You sent #{files.length} file(s): #{files.map(&:name).join(", ")}"
31
+ end
32
+ ```
33
+
34
+ `ctx.files.first` returns the first file or `nil`. Uploaded files and images pasted inline are listed — cards, mentions, and malformed file entries are skipped, never raised. Any file type sent as an upload is included.
35
+
36
+ Filter by how each item was attached:
37
+
38
+ ```ruby
39
+ ctx.files.list(attachment_style: "file") # uploaded files only
40
+ ctx.files.list(attachment_style: "inlineImage") # pasted images only
41
+ ```
42
+
43
+ ### Pasted inline images
44
+
45
+ An image pasted into the message body is listed with `attachment_style` `"inlineImage"`, named `image-<attachment id>` with an extension (and `content_type`) only for PNG, JPEG, GIF, or WebP. Teams saves a pasted GIF as a static PNG, so it is listed as `.gif` but `download` reports the format the bytes actually are. Inline images are read from the Bot API with the same token the turn replies with, and only from under the activity's service URL — an image hosted anywhere else is skipped with a warning. Some formats, such as BMP and AVIF, cannot be converted by Teams and fail to download; the same image sent as a file attachment works.
46
+
47
+ ### File metadata
48
+
49
+ | Reader | Description |
50
+ |---|---|
51
+ | `name` | Display name, including the extension when known |
52
+ | `extension` | Extension without the dot (`"pdf"`), from the platform's file type |
53
+ | `scope` | Conversation type the file arrived in (`"personal"`, ...) |
54
+ | `source` | Where the SDK found the file; `"botActivity"` today |
55
+ | `attachment_style` | `"file"` for a file attachment |
56
+ | `content_type` | MIME type when the source provides one; `nil` for file attachments (read `DownloadedFile#content_type` instead) |
57
+ | `content_url` | Browsable OneDrive/SharePoint link; not a byte URL |
58
+ | `unique_id` | OneDrive/SharePoint identifier, for correlation and logging |
59
+ | `raw` | The original attachment hash |
60
+
61
+ ## Read a file
62
+
63
+ ```ruby
64
+ file = ctx.files.first
65
+ downloaded = file.download # Teams::Files::DownloadedFile
66
+ downloaded.bytes # binary String
67
+ downloaded.content_type # from the download response
68
+ file.text # download + UTF-8 decode (lossy)
69
+ file.save_as("tmp/report.pdf") # streams to disk, never buffers the file
70
+ file.stream { |chunk| parser << chunk } # raw chunks; returns an Enumerator without a block
71
+ ```
72
+
73
+ The handle memoizes nothing, so every call fetches again. In a personal chat the download link is short-lived, so download once and reuse the `DownloadedFile` (its `text` and `save_as` never re-fetch).
74
+
75
+ The download is a plain GET with no token attached: the link carries its own credential, and the SDK never sends the bot's token to the storage host. Redirects are followed only over HTTPS.
76
+
77
+ ## Conversation scope support
78
+
79
+ - **Personal chats.** A traditional bot receives a short-lived, pre-authorized link that the SDK fetches directly. An agentic user receives no link — only `content_url` — so the SDK reads the bytes through Microsoft Graph `/shares` with the agent's own token. Your handler code is the same either way.
80
+ - **Group chats and channels.** Teams delivers files there only to agentic users, again carrying just `content_url`, and the SDK reads them through Graph as the agent. A traditional bot receives no files in these scopes.
81
+
82
+ An agentic user always reads as itself, never as the app: an app-only token sees what the app may read tenant-wide, a different set from what was shared with the agent.
83
+
84
+ ## Handle errors
85
+
86
+ All file errors inherit from `Teams::FileError`:
87
+
88
+ | Error | Raised when | Carries |
89
+ |---|---|---|
90
+ | `Teams::FileUrlExpiredError` | The short-lived download link lapsed. | `reason`: `"first_fetch"` (no bytes were ever fetched; the file has to be sent again) or `"reread"` (an earlier download succeeded; reuse its `DownloadedFile`) |
91
+ | `Teams::FileCredentialError` | The Graph read an agentic user's file needs was ruled out before the request: no token could be acquired, or the token carries no `Files.*`/`Sites.*` permission. | `actor`, `cause_detail` (why token acquisition failed, when it raised) |
92
+ | `Teams::FileAccessError` | The storage service refused the Graph read. | `status` (`401`: the token was rejected; `403`: the identity lacks the grant — this also covers a file never shared with it and an item that does not exist), `actor`, `details` (the service's own words) |
93
+ | `Teams::InlineImageTransformationError` | Teams could not convert a pasted image for download (`415`). | `status`, `code` (e.g. `"TransformationFailed"`), `details`, `actor` |
94
+ | `Teams::InlineImageAccessError` | The Bot API refused the token presented for a pasted image. | `status` (`401` rejected token, `403` not allowed), `actor`, `details` |
95
+ | `Teams::FileScopeNotSupportedError` | `download` was called on a file from a scope that cannot be downloaded yet. A traditional bot receives files only in personal chats. | `scope` |
96
+
97
+ `actor` is `"agentic_user"` when the inbound activity carries an agentic identity, `"app"` otherwise.
98
+
99
+ Failures the SDK cannot attribute (a storage 5xx, a network error) raise a plain `Teams::Error`.
@@ -0,0 +1,59 @@
1
+ # State
2
+
3
+ Per-turn state stores conversation and user data across activities. It is loaded before your handlers run, saved automatically after the turn, and exposed as `ctx.state`.
4
+
5
+ ## Setup
6
+
7
+ State is off by default (`ctx.state` is `nil`). Enable it with the `state:` option:
8
+
9
+ ```ruby
10
+ teams = Teams::App.new(state: true)
11
+ ```
12
+
13
+ `state: true` uses the app's `storage:` — the in-memory `Teams::Storage::MemoryStore` unless you pass another — which is fine for local development, but values are lost on restart and aren't shared across instances (the SDK logs a warning). See [Distributed state](#distributed-state).
14
+
15
+ ## Reading and writing state
16
+
17
+ ```ruby
18
+ teams.on_message do |ctx|
19
+ ctx.state.conversation["count"] = ctx.state.conversation.fetch("count", 0) + 1
20
+ ctx.state.user["name"] ||= ctx.activity.from.name
21
+
22
+ ctx.reply "Message #{ctx.state.conversation["count"]} in this chat"
23
+ end
24
+ ```
25
+
26
+ `ctx.state.conversation` is shared by everyone in the conversation; `ctx.state.user` is scoped to the sender **within that conversation** and is `nil` when the activity has no sender id. Both behave like a `Hash` (`[]`, `[]=`, `fetch`, `delete`, `key?`, `each`, `clear`, ...). Keys are strings — `state[:count]` reads and writes `"count"`.
27
+
28
+ Values must be JSON-serializable (`String`, `Integer`, `Float`, `true`/`false`, `nil`, `Array`, `Hash`); anything else raises when the turn is saved. Nested changes are detected, so `ctx.state.user["prefs"]["theme"] = "dark"` persists without reassignment, and nested hash keys come back as strings on the next turn.
29
+
30
+ A scope is written only when its content changed during the turn, and the save also runs when a handler raises. After the turn the state is sealed: don't keep it for background work — any later access raises `Teams::State::TurnStateSealedError`.
31
+
32
+ ## Clearing state
33
+
34
+ Remove a value with `delete(key)` or empty a scope with `clear` (an emptied scope is deleted from storage at the end of the turn). To remove both scopes from storage immediately:
35
+
36
+ ```ruby
37
+ ctx.state.delete
38
+ ```
39
+
40
+ Values written after `delete` are saved normally at the end of the turn.
41
+
42
+ ## Distributed state
43
+
44
+ Pass any storage object with `get(key)`, `set(key, value)`, and `delete(key)` — state values are JSON strings — through `Teams::State::StateOptions`:
45
+
46
+ ```ruby
47
+ class RedisStateStorage
48
+ def initialize(redis) = @redis = redis
49
+ def get(key) = @redis.get(key)
50
+ def set(key, value) = @redis.set(key, value, ex: 7 * 24 * 3600)
51
+ def delete(key) = @redis.del(key)
52
+ end
53
+
54
+ teams = Teams::App.new(
55
+ state: Teams::State::StateOptions.new(storage: RedisStateStorage.new(Redis.new), key_prefix: "ts")
56
+ )
57
+ ```
58
+
59
+ Keys are `{key_prefix}:conv:{conversation id}` and `{key_prefix}:user:{conversation id}:{user id}`, with each id percent-encoded. Expiry and other storage policies belong to the storage provider; state has none by default.
@@ -12,8 +12,8 @@ teams.on_message do |ctx|
12
12
  end
13
13
  ```
14
14
 
15
- - `emit(text)` appends to the streamed message.
16
- - `update(text)` sends an informative status update (shown before content starts).
15
+ - `emit(text)` appends to the streamed message. Chunks use the `text_format` of the last emitted `MessageActivity`, so streamed extended markdown renders as such before the message completes.
16
+ - `update(text, text_format: nil)` sends an informative status update (shown before content starts); `text_format` applies to that update only.
17
17
  - `clear_text` discards accumulated text — e.g. to replace streamed text with a final card.
18
18
  - `close` finalizes explicitly; it's called for you when the handler returns.
19
19
 
@@ -39,12 +39,13 @@ ctx.stream.on_close { |sent| Analytics.record_stream(sent.id) }
39
39
 
40
40
  ## Reuse and typed errors
41
41
 
42
- Emitting again after `close` starts a **new** streamed message on the same stream. If Teams stops a stream, the SDK raises typed errors:
42
+ Emitting again after `close` starts a **new** streamed message on the same stream. If Teams rejects a stream, the SDK raises typed errors:
43
43
 
44
- - `Teams::StreamCancelledError` — the user cancelled (sticky: the next `emit` also raises)
45
44
  - `Teams::StreamNotAllowedError`, `Teams::TerminalStreamError` — terminal failures
46
45
 
47
- Chunk-send errors are recorded on the stream and surface when `close` sends the final message. A stream that exceeds the Teams two-minute limit finalizes automatically by updating the streamed message in place.
46
+ Chunk-send errors are recorded on the stream and surface when `close` sends the final message. A stream that exceeds the Teams ten-minute limit (counted from the first informative or content chunk) finalizes automatically by updating the streamed message in place.
47
+
48
+ Teams no longer supports stopping a stream, so `canceled` always returns false and `Teams::StreamCancelledError` is never raised; both are deprecated.
48
49
 
49
50
  ## Gotchas
50
51
 
@@ -26,12 +26,12 @@ teams.on_message(/^login$/i) do |ctx|
26
26
  ctx.reply "Already signed in!" if token # nil means a card was sent
27
27
  end
28
28
 
29
- teams.on_sign_in do |ctx, token_response|
29
+ teams.on_oauth_sign_in do |ctx, token_response|
30
30
  ctx.post "Welcome! You're signed in."
31
31
  end
32
32
  ```
33
33
 
34
- `ctx.sign_in` returns the token when the user is already signed in; otherwise it sends an OAuth card and returns `nil`. In group chats and channels the card is delivered in the conversation as a targeted message only the requesting user sees; in channels the card always uses the sign-in button (silent SSO is not supported in channel scope). The SDK's **default handlers** then complete the sign-in invokes automatically — both the interactive card path (`signin/verifyState`) and silent SSO (`signin/tokenExchange`) — and fire `on_sign_in`. You don't handle the invokes yourself.
34
+ `ctx.sign_in` returns the token when the user is already signed in; otherwise it sends an OAuth card and returns `nil`. In group chats and channels the card is delivered in the conversation as a targeted message only the requesting user sees; in channels the card always uses the sign-in button (silent SSO is not supported in channel scope). The SDK's **default handlers** then complete the sign-in invokes automatically — both the interactive card path (`signin/verifyState`) and silent SSO (`signin/tokenExchange`) — and fire `on_oauth_sign_in`. You don't handle the invokes yourself.
35
35
 
36
36
  `ctx.sign_out` clears the stored token.
37
37
 
@@ -40,21 +40,49 @@ end
40
40
  Most often through the [user Graph client](../essentials/graph.md):
41
41
 
42
42
  ```ruby
43
- teams.on_sign_in do |ctx, _token|
43
+ teams.on_oauth_sign_in do |ctx, _token|
44
44
  me = ctx.user_graph.get("/me")
45
45
  ctx.post "Hello #{me["displayName"]}"
46
46
  end
47
47
  ```
48
48
 
49
- Or the raw token from the token service:
49
+ Or the raw token: `ctx.get_user_token(connection_name: "graph")` returns it, or `nil` when the user is not signed in. Only the token service's 404 means "not signed in" — any other failure raises, so an outage is never mistaken for a signed-out user (the same applies to `ctx.sign_in`). `ctx.get_connection_status` returns the token status of every OAuth connection on the bot in one call.
50
+
51
+ ## Multiple connections
52
+
53
+ Register each OAuth connection as a named flow, then sign in, read tokens, and react to completions per connection:
50
54
 
51
55
  ```ruby
52
- response = ctx.api.users.get_token(
53
- user_id: ctx.activity.from.id, connection_name: "graph", channel_id: ctx.activity.channel_id
54
- )
55
- response.token # the delegated access token
56
+ github = teams.add_oauth_flow("github", oauth_card_text: "Sign in with GitHub")
57
+ graph = teams.add_oauth_flow("graph")
58
+
59
+ teams.on_message("/github") { |ctx| github.sign_in(ctx) }
60
+ teams.on_message("/logout") { |ctx| github.sign_out(ctx) }
61
+
62
+ github.on_sign_in do |event|
63
+ event.context.post "Signed in to GitHub (#{event.connection_name})"
64
+ end
65
+ github.on_sign_in_failure do |event|
66
+ event.context.log.warn("GitHub sign-in failed: #{event.code} #{event.message}")
67
+ end
68
+
69
+ teams.get_oauth_flow("GITHUB") # case-insensitive lookup; raises when not registered
70
+ github.get_token(ctx) # token or nil
71
+ github.signed_in?(ctx)
56
72
  ```
57
73
 
74
+ `flow.sign_in` always uses the flow's own connection; its card text defaults to the flow's and can be overridden per call. Flow handlers run in registration order and are isolated: one that raises is logged and the rest still run. The app-level `on_oauth_sign_in` still fires for every connection, and `teams.on_oauth_sign_in_failure { |event| ... }` receives each `signin/failure` callback once as a `Teams::OAuth::SignInFailureEvent` (`context`, `connection_name`, `code`, `message`).
75
+
76
+ ### How callbacks find their flow
77
+
78
+ - **Silent SSO** (`signin/tokenExchange`) names its connection, so it always reaches the right flow.
79
+ - **The card's sign-in button** (`signin/verifyState`) carries only a one-time code. The SDK tries the connections in order — the ones with a pending sign-in for this user (newest first), the remaining registered flows, then `default_connection_name` — until one accepts the code; none accepting answers 404.
80
+ - **`signin/failure`** carries no connection either. It is attributed to the newest pending sign-in that offered silent SSO; if none can be found, `on_oauth_sign_in_failure` reports `connection_name` `nil` and every registered flow's failure handlers are notified, each with its own connection name.
81
+
82
+ `flow.sign_in` / `ctx.sign_in` record the pending sign-in in [per-turn state](state.md), which registering a flow turns on when you didn't set `state:`. With `state: false`, pending sign-ins live in a short-lived in-process cache, so a callback handled by another instance cannot be attributed — use shared state storage when running several instances.
83
+
84
+ Teams delivers one silent-SSO exchange to every client the user is signed in on; the SDK runs it once. Duplicates answer 200 without firing the sign-in events again, both on the same instance and — through conversation state — across instances.
85
+
58
86
  ## Custom invoke handling
59
87
 
60
88
  The defaults run first; handlers you register on `on_signin_verify_state` / `on_signin_token_exchange` / `on_signin_failure` run **after** them, for custom behavior. Don't fetch the token yourself in a verify-state handler — the magic code is single-use and the default already consumed it.
@@ -5,15 +5,26 @@ require "json"
5
5
 
6
6
  module Teams
7
7
  class ActivityContext
8
- attr_reader :app, :activity, :conversation_reference, :extra, :stream
8
+ # Typed messages, edits, deletes, and reactions carry plain numeric
9
+ # message ids; invokes and card-button messages carry service-generated
10
+ # ids such as "f:<guid>", which the service rejects as quote targets.
11
+ NUMERIC_MESSAGE_ID = /\A0*[1-9][0-9]*\z/
9
12
 
10
- def initialize(app:, activity:, conversation_reference:, extra: {}, stream: nil, api: nil)
13
+ # state is the turn's State::TurnStateContainer (ctx.state.conversation,
14
+ # ctx.state.user), or nil when the app was built without state:.
15
+ attr_reader :app, :activity, :conversation_reference, :extra, :stream, :state
16
+
17
+ def initialize(app:, activity:, conversation_reference:, extra: {}, stream: nil, api: nil, files_credential: nil,
18
+ files_bot_api_credential: nil, state: nil)
11
19
  @app = app
12
20
  @activity = activity
13
21
  @conversation_reference = conversation_reference
14
22
  @extra = extra
15
23
  @stream = stream
16
24
  @api = api
25
+ @files_credential = files_credential
26
+ @files_bot_api_credential = files_bot_api_credential
27
+ @state = state
17
28
  end
18
29
 
19
30
  def ref
@@ -38,6 +49,18 @@ module Teams
38
49
  @api || app.api
39
50
  end
40
51
 
52
+ # The uploaded files and pasted inline images on the inbound activity, as
53
+ # Files::IncomingFile handles. See Files::FilesAccessor.
54
+ def files
55
+ @files ||= Files::FilesAccessor.new(
56
+ activity,
57
+ downloader: app.files_downloader,
58
+ credential: @files_credential,
59
+ bot_api_credential: @files_bot_api_credential,
60
+ logger: log
61
+ )
62
+ end
63
+
41
64
  # The TypeScript, Python, and .NET SDKs call this operation `send`.
42
65
  # Ruby already defines Object#send for dynamic dispatch, so the public
43
66
  # Ruby API uses `post` to avoid shadowing a core language method.
@@ -45,8 +68,11 @@ module Teams
45
68
  app.send_activity(conversation_reference, apply_targeted_defaults(activity_or_text), api:)
46
69
  end
47
70
 
71
+ # Quotes the inbound message only when its id is a plain numeric message
72
+ # id (digits, not all zeros), like the TypeScript, Python, and .NET SDKs;
73
+ # otherwise sends exactly like post. Use quote to quote a specific id.
48
74
  def reply(activity_or_text)
49
- return post(activity_or_text) unless activity.id
75
+ return post(activity_or_text) unless NUMERIC_MESSAGE_ID.match?(activity.id.to_s)
50
76
  # Replies to targeted inbound messages are targeted sends: no quoted
51
77
  # reply and no replyToId, matching the TypeScript and Python SDKs.
52
78
  return post(activity_or_text) if targeted_reply?(activity_or_text)
@@ -99,20 +125,17 @@ module Teams
99
125
  # chats and channels the card is a targeted message visible only to the
100
126
  # requesting user; channels omit the token exchange resource because
101
127
  # channel scope cannot do the silent SSO exchange, so the card renders
102
- # the sign-in button instead.
128
+ # the sign-in button instead. With registered OAuth flows, prefer
129
+ # app.get_oauth_flow(name).sign_in(ctx), which pins the connection to
130
+ # the flow that owns it (the Python SDK marks this helper deprecated in
131
+ # its documentation for the same reason).
103
132
  def sign_in(connection_name: nil, oauth_card_text: "Please Sign In...", sign_in_button_text: "Sign In")
104
133
  connection_name ||= app.default_connection_name
105
134
 
106
- begin
107
- response = api.users.get_token(
108
- user_id: activity.from.id,
109
- connection_name:,
110
- channel_id: activity.channel_id
111
- )
112
- return response.token if response.token && !response.token.to_s.empty?
113
- rescue HttpError
114
- # No token yet; continue with the OAuth card flow.
115
- end
135
+ connection_name = OAuth.normalize_connection_name(connection_name)
136
+
137
+ token = get_user_token(connection_name:)
138
+ return token if token && !token.to_s.empty?
116
139
 
117
140
  state = Base64.strict_encode64(JSON.generate(
118
141
  "connectionName" => connection_name,
@@ -143,10 +166,60 @@ module Teams
143
166
  ]
144
167
  }
145
168
 
146
- app.send_activity(conversation_reference, payload, api:)
169
+ send_sign_in_card(payload, connection_name, sso_offered: card.key?("tokenExchangeResource"))
170
+ nil
171
+ end
172
+
173
+ # The user's token for a connection (default: the app's default
174
+ # connection), or nil when not signed in. Only the Token Service's 404
175
+ # means "not signed in"; other failures raise, so an outage is never
176
+ # mistaken for a signed-out user. Prefer app.get_oauth_flow(name).get_token
177
+ # with registered flows.
178
+ def get_user_token(connection_name: nil)
179
+ api.users.get_token(
180
+ user_id: activity.from.id,
181
+ connection_name: connection_name || app.default_connection_name,
182
+ channel_id: activity.channel_id
183
+ ).token
184
+ rescue HttpError => error
185
+ raise unless error.status == 404
186
+
147
187
  nil
148
188
  end
149
189
 
190
+ # Token status for every OAuth connection on the bot in one Token Service
191
+ # call. The bulk call can lag a fresh sign-in or omit a connection, so a
192
+ # registered flow reported missing or without a token is re-checked with
193
+ # a direct lookup, like the Python SDK.
194
+ def get_connection_status
195
+ statuses = api.users.get_token_status(user_id: activity.from.id, channel_id: activity.channel_id)
196
+ registered = app.oauth_registry.each_with_object({}) do |flow, names|
197
+ names[OAuth.lookup_key(flow.connection_name)] = flow.connection_name
198
+ end
199
+ return statuses if registered.empty?
200
+
201
+ resolved = Set.new
202
+ corrected = statuses.map do |status|
203
+ key = OAuth.lookup_key(status.connection_name)
204
+ resolved << key if key
205
+ next status if key.nil? || !registered.key?(key) || status.has_token
206
+
207
+ get_user_token(connection_name: registered[key]) ? Api::TokenStatus.new(status.to_h.merge("hasToken" => true)) : status
208
+ end
209
+
210
+ registered.each do |key, name|
211
+ next if resolved.include?(key)
212
+
213
+ corrected << Api::TokenStatus.new(
214
+ "channelId" => activity.channel_id,
215
+ "connectionName" => name,
216
+ "hasToken" => !get_user_token(connection_name: name).nil?,
217
+ "serviceProviderDisplayName" => ""
218
+ )
219
+ end
220
+ corrected
221
+ end
222
+
150
223
  # Clears the user's token for the connection. Failures are logged, not
151
224
  # raised, matching the TypeScript/Python SDKs.
152
225
  def sign_out(connection_name: nil)
@@ -163,6 +236,36 @@ module Teams
163
236
 
164
237
  private
165
238
 
239
+ # Records which connection the sign-in started on, so the connection-less
240
+ # verify-state and failure callbacks can be routed to its flow, then sends
241
+ # the card. With state the record is saved right away; if the card cannot
242
+ # be sent, the previous records are restored so they cannot mis-route a
243
+ # later callback.
244
+ def send_sign_in_card(payload, connection_name, sso_offered:)
245
+ cache = app.oauth_pending_cache
246
+ scope = { conversation_id: activity.conversation&.id, user_id: activity.from&.id }
247
+ previous = OAuth::PendingSignIns.list(state, cache, **scope)
248
+ begin
249
+ OAuth::PendingSignIns.record(state, cache, connection_name, sso_offered:, **scope)
250
+ state&.save
251
+ app.send_activity(conversation_reference, payload, api:)
252
+ rescue StandardError
253
+ begin
254
+ OAuth::PendingSignIns.replace(state, cache, previous, **scope)
255
+ if state
256
+ state.user&.mark_dirty
257
+ state.save
258
+ end
259
+ rescue StandardError => rollback_error
260
+ log&.warn(
261
+ "Failed to roll back pending OAuth sign-in state for connection '#{connection_name}': " \
262
+ "#{rollback_error.message}"
263
+ )
264
+ end
265
+ raise
266
+ end
267
+ end
268
+
166
269
  def incoming_targeted_sender
167
270
  return nil unless activity.message?
168
271
  return nil unless activity.recipient.is_targeted == true