ruby_llm-ag_ui 0.1.0 → 0.3.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 +44 -0
  3. data/CONTRIBUTING.md +27 -3
  4. data/README.md +39 -115
  5. data/docs/_advanced/client-example.md +107 -0
  6. data/docs/_advanced/rails-integration.md +5 -2
  7. data/docs/_advanced/security-and-deployment.md +1 -1
  8. data/docs/_advanced/worker-recovery.md +104 -0
  9. data/docs/_core_features/cancellation.md +84 -0
  10. data/docs/_core_features/reconnects.md +13 -1
  11. data/docs/_core_features/streaming-runs.md +15 -0
  12. data/docs/_core_features/tool-progress.md +90 -0
  13. data/docs/_getting_started/configuration.md +2 -1
  14. data/docs/_getting_started/whats-new-in-0-3.md +61 -0
  15. data/docs/_reference/compatibility.md +83 -15
  16. data/docs/_reference/protocol-coverage.md +6 -5
  17. data/docs/_reference/release-history.md +4 -2
  18. data/docs/_reference/releasing.md +25 -0
  19. data/docs/_reference/upgrading.md +32 -18
  20. data/docs/{_getting_started → _reference}/whats-new-in-0-1.md +2 -1
  21. data/docs/_reference/whats-new-in-0-2.md +54 -0
  22. data/lib/ruby_llm/ag_ui/configuration.rb +7 -1
  23. data/lib/ruby_llm/ag_ui/coverage.rb +2 -2
  24. data/lib/ruby_llm/ag_ui/emitter.rb +5 -1
  25. data/lib/ruby_llm/ag_ui/error.rb +13 -2
  26. data/lib/ruby_llm/ag_ui/error_sanitizer.rb +1 -0
  27. data/lib/ruby_llm/ag_ui/mapper.rb +20 -1
  28. data/lib/ruby_llm/ag_ui/persistence.rb +18 -0
  29. data/lib/ruby_llm/ag_ui/rails/active_record_store.rb +21 -11
  30. data/lib/ruby_llm/ag_ui/rails/record.rb +8 -3
  31. data/lib/ruby_llm/ag_ui/rails/streaming.rb +3 -3
  32. data/lib/ruby_llm/ag_ui/redaction.rb +1 -0
  33. data/lib/ruby_llm/ag_ui/resume.rb +14 -6
  34. data/lib/ruby_llm/ag_ui/run.rb +33 -23
  35. data/lib/ruby_llm/ag_ui/run_record.rb +17 -4
  36. data/lib/ruby_llm/ag_ui/sse_writer.rb +16 -4
  37. data/lib/ruby_llm/ag_ui/store/base.rb +25 -2
  38. data/lib/ruby_llm/ag_ui/store/memory_store.rb +3 -7
  39. data/lib/ruby_llm/ag_ui/version.rb +1 -1
  40. metadata +30 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ab7bc5eeccd9381e134cd795b20b0815aed665ac3f4371d29503bed969811410
4
- data.tar.gz: 5991ee6bec49c64e3dd5ac0f8f9ccd18abe7c5f9aab55cb5493b232cff088cbe
3
+ metadata.gz: fd1d89205c88b89562445e5f654f2f2f931753ac4ff4e2ed4434031ad65251d6
4
+ data.tar.gz: ec70b5e27313a50c8596beaa33c2de9f3b8fc46fab5968b309cc8f626b4a70a0
5
5
  SHA512:
6
- metadata.gz: 205524fd5c5cbcd214da1f98c2c2b3678e0961b417ee598803741b577a7c7400be2e51b8d78716905cb14b2fb386d3ee46a8a3e157947cbf06afe6eaf8d01669
7
- data.tar.gz: 8680a5a03eacc9cfa8d3920db2be725d5f148befd24125a9b6875312307c4207528f69b527dc294f7e064a2c4f33d0c5bf3666318d3ea81f5927089f6408ae78
6
+ metadata.gz: 7526b6e10f776726e8647efa1a47819d4958b0f0e54cb57f65c81968c4929bbf7330a326197adcbc869f1cc3333921d37f8eb74eb088da9f71690cea7a2c6715
7
+ data.tar.gz: ec8fd2a7271e5aa28f8084716a75ebd8d5067a2d7d4e164aa521e8ceeea4b24897397242f1110ef0cd6cd4b5588dd0fb7c25e732c137ea196c5249ef5ece7f28
data/CHANGELOG.md CHANGED
@@ -6,6 +6,50 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.3.0] - 2026-10-20
10
+
11
+ ### Added
12
+
13
+ - Explicit stopped-worker recovery with a `worker_lost` outcome, retaining run
14
+ identity and exposing unknown tool effects for host reconciliation.
15
+ - Atomic storage revisions and independent-process SQLite reservation,
16
+ approval redemption, conflicting-write, and worker-death tests.
17
+ - Exact-run, actor-scoped cancellation and HTTP abort workflows in the offline
18
+ browser example, plus real RubyLLM HTTP timeout and cancellation checkpoints
19
+ verified without a provider connection.
20
+
21
+ ### Fixed
22
+
23
+ - Continue a live run after its response transport disconnects, preserving the
24
+ real outcome and side-effect identity instead of failing the run on a write.
25
+ - Reject stale record writes and preserve uncertain database-write outcomes.
26
+ Disable callbacks even when a producer cannot persist its final record.
27
+ - Keep uncertain reservation and approval acknowledgements separate from run
28
+ failures, without executing a provider turn or guessing whether a decision committed.
29
+ - Recognize Puma connection failures as disconnected transports and classify
30
+ Faraday timeouts as `transport_timeout` instead of generic transport errors.
31
+ - Require JSON 2.x so Rails 8.0 can load a real RubyLLM chat without passing
32
+ a removed `quirks_mode` option to JSON 3.
33
+
34
+ ## [0.2.0] - 2026-10-19
35
+
36
+ ### Added
37
+
38
+ - Opt-in tool progress as redacted `ACTIVITY_SNAPSHOT` events, with stable
39
+ per-call identity and per-run or global configuration.
40
+ - Installed-artifact host checks for generated migrations, RubyLLM model setup,
41
+ actor-scoped chat persistence, and Ruby/Rails run paths.
42
+ - A pinned official AG-UI client demo for Ruby and Rails, with browser workflow
43
+ tests, mobile screenshots, and schema validation of consumed events.
44
+
45
+ ### Fixed
46
+
47
+ - Reconnect an exact completed resume request without redeeming its approval
48
+ again. Changed input still conflicts, and a new run cannot reuse an answered
49
+ interrupt.
50
+ - Supply the required actor scope in the opt-in live-provider check and exercise
51
+ its run setup offline, before provider verification.
52
+
9
53
  ## [0.1.0] - 2026-10-18
10
54
 
11
55
  ### Added
data/CONTRIBUTING.md CHANGED
@@ -7,8 +7,7 @@ with tests are the easiest to accept.
7
7
 
8
8
  ```bash
9
9
  bundle install
10
- bundle exec rspec
11
- bundle exec rubocop
10
+ bin/check
12
11
  ```
13
12
 
14
13
  ## Ground rules
@@ -33,15 +32,40 @@ bundle exec rubocop
33
32
 
34
33
  ## Tests
35
34
 
35
+ Run focused specs first, then `bin/check`. For client or demo changes, also run
36
+ `bin/check-browser` and inspect its screenshots. The browser suite uses synthetic
37
+ fixtures, a real AG-UI client, and a temporary local server. Keep artifacts in
38
+ ignored `tmp/`. Use `bin/check --package --browser` for the full local check,
39
+ or `bin/check-browser --grep "rails: approval"` for one browser workflow.
40
+ The package probe installs the artifact outside the checkout using available
41
+ development dependencies; `bin/verify-package` separately tests clean dependency
42
+ resolution. Shut down all task-owned processes when the check finishes.
43
+
36
44
  Every behavior change needs a test, and lifecycle, identity and security changes
37
45
  need their negative case too. The acceptance IDs (FR-01..FR-08) are referenced
38
46
  in spec descriptions. Offline CI uses fakes; live provider tests are opt-in and
39
47
  never required:
40
48
 
41
49
  ```bash
42
- RUBY_LLM_LIVE=1 OPENAI_API_KEY=... bundle exec rspec spec/live
50
+ RUBY_LLM_LIVE=1 bundle exec rspec spec/live
43
51
  ```
44
52
 
53
+ Load provider credentials through your environment or an untracked env file,
54
+ never through command-line arguments. See the
55
+ [compatibility guide](https://rubyllm-ag-ui.wangyaodi.com/compatibility/) for
56
+ what each check establishes.
57
+
58
+ ## Documentation
59
+
60
+ - Keep README to the project introduction, installation, one example, and links.
61
+ - Keep usage, configuration, compatibility, and API details in `docs/`, the
62
+ source of the documentation site. Link to a guide instead of copying it.
63
+ - Keep contributor rules here, shipped changes in [CHANGELOG.md](CHANGELOG.md),
64
+ and proposed work in [ROADMAP.md](ROADMAP.md).
65
+ - Change a public API's guide in the same commit. Follow [AGENTS.md](AGENTS.md)
66
+ and build with `docs/bin/build.sh` before submitting documentation changes.
67
+ - Keep example READMEs specific to running or adapting that example.
68
+
45
69
  ## Commit style
46
70
 
47
71
  Conventional Commits (`feat:`, `fix:`, `docs:`, `test:`, `chore:`, `refactor:`),
data/README.md CHANGED
@@ -2,145 +2,69 @@
2
2
 
3
3
  [![CI](https://github.com/yorzi/ruby_llm-ag-ui/actions/workflows/ci.yml/badge.svg)](https://github.com/yorzi/ruby_llm-ag-ui/actions/workflows/ci.yml)
4
4
 
5
- Run [RubyLLM](https://rubyllm.com) 2.x chats as [AG-UI](https://github.com/ag-ui-protocol/ag-ui) 1.0 agent runs.
6
-
7
- `ruby_llm-ag_ui` turns one RubyLLM chat turn into one AG-UI run: it validates the
8
- inbound `RunAgentInput`, maps RubyLLM streaming, tool and lifecycle behavior onto
9
- schema-valid AG-UI events, turns `requires_approval` pauses into interrupt
10
- outcomes with host-authorized resume, reports `Chat#cancel` as the cancelled
11
- outcome, and writes the stream as Server-Sent Events. A pure-Ruby core comes
12
- with an optional Rails adapter.
13
-
14
- > **Unofficial community project.** This gem is not affiliated with, endorsed
15
- > by, or maintained by the RubyLLM maintainers or the AG-UI protocol
16
- > maintainers. `RubyLLM::` and "AG-UI" appear here because this gem extends
17
- > those projects, not because it speaks for them.
18
-
19
- ## Why
20
-
21
- If your agent already runs on RubyLLM and you want an AG-UI client (CopilotKit,
22
- `@ag-ui/client`, or another AG-UI consumer) in front of it, you currently have
23
- to hand-map RubyLLM callbacks, approval pauses and cancellation onto the AG-UI
24
- run lifecycle, and you have to parse and authorize `RunAgentInput` yourself:
25
- the community Ruby SDK builds outbound events but has no inbound parser. The
26
- usual results are wrong terminal events, duplicate runs on retry, approvals that
27
- are not bound to the call they approve, and cancellations reported as success.
28
- This gem removes that mapping work.
29
-
30
- ## What it does and does not do
31
-
32
- It owns the RubyLLM → AG-UI mapping, input parsing, event ordering, run identity
33
- and terminal correctness. It is **not** an AG-UI core SDK, a schema fork, a chat
34
- UI, a CopilotKit runtime clone, or a second agent framework. RubyLLM owns the
35
- agent loop, tool execution, approval pauses and cancellation checkpoints. Your
36
- application owns identity, authorization, which tools and model a run may use,
37
- and persistence.
38
-
39
- ## Status
40
-
41
- Version `0.1.0` is the first release. The pure-Ruby core, run store, approval/resume, cancel
42
- handling and the Rails adapter are implemented and covered by an offline test
43
- suite. Compatibility claims for real AG-UI clients and live providers are
44
- tracked in the [compatibility guide](https://rubyllm-ag-ui.wangyaodi.com/compatibility/) and are
45
- **not** asserted until recorded there.
46
-
47
- Read the [documentation site](https://rubyllm-ag-ui.wangyaodi.com/) for the
48
- guides, protocol coverage, compatibility matrix and security model. Its source
49
- is in [docs/](https://github.com/yorzi/ruby_llm-ag-ui/tree/main/docs).
50
-
51
- ## Installation
5
+ Connect [RubyLLM](https://rubyllm.com) chats to [AG-UI](https://docs.ag-ui.com)
6
+ clients over Server-Sent Events. The gem handles streaming text, tool calls, approval and resume,
7
+ cancellation outcomes, and run identity. Use it from plain Ruby or with the
8
+ optional Rails adapter.
52
9
 
53
- ```ruby
54
- # Gemfile
55
- gem 'ruby_llm-ag_ui', '~> 0.1.0'
56
- ```
10
+ Your application provides authentication, tool permissions, chat history, and
11
+ the model. This is an unofficial community project, independent of the
12
+ RubyLLM and AG-UI maintainers.
57
13
 
58
- ```bash
59
- bundle install
14
+ **[Documentation](https://rubyllm-ag-ui.wangyaodi.com/)** ·
15
+ [Getting started](https://rubyllm-ag-ui.wangyaodi.com/getting-started/) ·
16
+ [Rails guide](https://rubyllm-ag-ui.wangyaodi.com/rails-integration/) ·
17
+ [Compatibility](https://rubyllm-ag-ui.wangyaodi.com/compatibility/)
18
+
19
+ ## Install
20
+
21
+ ```ruby
22
+ gem 'ruby_llm-ag_ui', '~> 0.3.0'
60
23
  ```
61
24
 
62
- Requires Ruby >= 3.2, RubyLLM >= 2.1 and `ag-ui-protocol` ~> 0.2.0.
63
- Runtime dependencies also select patched `cgi`, `resolv`, `uri` and `zlib` gems.
25
+ Requires Ruby >= 3.2, RubyLLM >= 2.1 and < 3.0, and `ag-ui-protocol` 0.2.x.
26
+ Run `bundle install` after adding the gem.
64
27
 
65
- ## Quick start (pure Ruby)
28
+ ## Stream a run
66
29
 
67
- The host authenticates, authorizes and builds the chat; the gem writes the
68
- stream.
30
+ Pass a chat authorized for the current actor, a shared run store, and an
31
+ IO-like response stream from your application:
69
32
 
70
33
  ```ruby
71
- require 'ruby_llm'
72
34
  require 'ruby_llm/ag_ui'
73
35
 
74
- input = RubyLLM::AgUI::Input.parse(request_body) # bounds, validates, digests
75
- chat = host_chat_for(actor, input.thread_id) # your RubyLLM::Chat
36
+ input = RubyLLM::AgUI::Input.parse(request_body)
37
+ chat = authorized_chat_for(current_user, input.thread_id)
76
38
 
77
39
  RubyLLM::AgUI::Run.new(
78
40
  chat: chat,
79
41
  input: input,
80
- scope: "tenant:#{tenant.id}:actor:#{actor.id}", # from authenticated identity
42
+ scope: "actor:#{current_user.id}",
81
43
  store: run_store
82
- ).stream(to: sse_io)
83
- ```
84
-
85
- `scope` is what the run is reserved under: it must be a non-empty String the host
86
- builds from authenticated identity, never anything from the request body.
87
-
88
- `examples/pure_ruby/app.rb` is a runnable Rack endpoint that streams a complete
89
- run (a tool call, an approval pause and the run that answers it) with no
90
- provider and no credentials (`rake example`, or
91
- `rackup examples/pure_ruby/config.ru`). Set `RUBY_LLM_AG_UI_EXAMPLE_MODEL` to
92
- drive a real `RubyLLM::Chat` through the same code.
93
-
94
- ## Rails
95
-
96
- The optional adapter provides a controller concern, a durable run store keyed
97
- by the actor's scope, and reconnect snapshots. It loads only when
98
- `Rails::Railtie` is already defined.
99
-
100
- ```ruby
101
- class AgentRunsController < ApplicationController
102
- include RubyLLM::AgUI::Rails::Streaming
103
-
104
- def create
105
- stream_ag_ui_run { |input| current_user.chats.find_or_create_by!(ag_ui_thread_id: input.thread_id) }
106
- end
107
-
108
- def ag_ui_scope
109
- "actor:#{current_user.id}"
110
- end
111
- end
44
+ ).stream(to: response_stream)
112
45
  ```
113
46
 
114
- See the [Rails integration guide](https://rubyllm-ag-ui.wangyaodi.com/rails-integration/) and `examples/rails_8`.
47
+ Build `scope` from authenticated identity. See the
48
+ [streaming guide](https://rubyllm-ag-ui.wangyaodi.com/streaming-runs/) for setup
49
+ and the [examples](examples/) for integration code.
115
50
 
116
51
  ## Development
117
52
 
118
- ```bash
53
+ ```sh
119
54
  bundle install
120
55
  bundle exec rspec
121
56
  bundle exec rubocop
122
- rake example # prints a full AG-UI run as SSE
57
+ bundle exec rake example # offline approval and resume demo, no API key needed
123
58
  ```
124
59
 
125
- The suite is offline: fakes instead of a provider, no network, no credentials.
126
- The only test that talks to a model is opt-in:
127
-
128
- ```bash
129
- RUBY_LLM_LIVE=1 OPENAI_API_KEY=... bundle exec rspec spec/live
130
- ```
131
-
132
- ## Documentation
133
-
134
- - [Architecture](https://rubyllm-ag-ui.wangyaodi.com/overview/) - the components, run, and invariants.
135
- - [Protocol coverage](https://rubyllm-ag-ui.wangyaodi.com/protocol-coverage/) - all 31 AG-UI 1.0 event types
136
- and what this gem does with each.
137
- - [Compatibility](https://rubyllm-ag-ui.wangyaodi.com/compatibility/) - what this repository verifies.
138
- - [Rails](https://rubyllm-ag-ui.wangyaodi.com/rails-integration/) - the controller concern, store, and transport.
139
- - [Security](https://rubyllm-ag-ui.wangyaodi.com/security-and-deployment/) - the threat model and deployment checklist.
140
-
141
- ## License
60
+ The default suite is offline. Real client and provider verification is tracked
61
+ in the [compatibility guide](https://rubyllm-ag-ui.wangyaodi.com/compatibility/).
62
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for development and documentation rules,
63
+ [ROADMAP.md](ROADMAP.md) for the proposed path to 1.0, and
64
+ [CHANGELOG.md](CHANGELOG.md) for shipped changes.
142
65
 
143
- MIT. See [LICENSE.txt](LICENSE.txt). Read the [third-party notices](https://rubyllm-ag-ui.wangyaodi.com/third-party-notices/).
66
+ ## License and security
144
67
 
145
- This is an unofficial community project and is not affiliated with the RubyLLM or
146
- AG-UI maintainers. Report security issues privately. See [SECURITY.md](SECURITY.md).
68
+ [MIT](LICENSE.txt). See the
69
+ [third-party notices](https://rubyllm-ag-ui.wangyaodi.com/third-party-notices/)
70
+ and report vulnerabilities through [SECURITY.md](SECURITY.md).
@@ -0,0 +1,107 @@
1
+ ---
2
+ layout: default
3
+ title: Client Example
4
+ nav_order: 3
5
+ description: Run a real AG-UI browser client against offline Ruby and Rails endpoints.
6
+ ---
7
+
8
+ # {{ page.title }}
9
+
10
+ {{ page.description }}
11
+ {: .fs-6 .fw-300 }
12
+
13
+ After reading this guide, you will know:
14
+
15
+ * How to run the maintained offline client example.
16
+ * Which interactions it verifies with the official client.
17
+ * Which responsibilities remain with a real host application.
18
+
19
+ ## Run the Example
20
+
21
+ From the repository, install the development dependencies and build the client:
22
+
23
+ ```sh
24
+ bundle install
25
+ npm ci
26
+ npm run build:demo
27
+ bundle exec ruby examples/client/server.rb
28
+ ```
29
+
30
+ Open `http://127.0.0.1:3199`. Stop the server with `Ctrl-C` when finished.
31
+ The host binds loopback and serves only the demo HTML and its locally bundled
32
+ JavaScript. It creates and removes a temporary SQLite database on each run.
33
+ No CDN, provider account, or API key is needed.
34
+
35
+ Choose **Plain Ruby** or **Rails + SQLite**, then run a turn. The official
36
+ `@ag-ui/client` package consumes the SSE stream. The scripted host retains one
37
+ chat per fixture actor and thread, so approval resumes the original tool call
38
+ and later turns use the same conversation.
39
+
40
+ ## Try the Interactions
41
+
42
+ The tool scenario pauses for approval. Approve it to run a synthetic order
43
+ cancellation once, or deny it to leave the order unchanged. Tool results stay
44
+ redacted by default. Approved tools also publish synthetic progress counts;
45
+ the host policy withholds progress messages. The text, sanitized failure, and cancelled scenarios show
46
+ the other run outcomes.
47
+
48
+ During approved progress, **Cancel server run** requests cancellation for the
49
+ exact fixture actor, thread, and run. The host rejects another actor, an old
50
+ run id, or a completed run. The synthetic tool checks cancellation before its
51
+ effect. This does not establish cancellation latency for a real provider or
52
+ arbitrary tool.
53
+
54
+ **Disconnect stream** calls the client's HTTP abort. The producer keeps running
55
+ and records its actual outcome. Reconnect after it finishes to read that result
56
+ without repeating the tool. An early reconnect is refused while the host still
57
+ owns the active chat. The timeout scenario produces a sanitized recorded failure.
58
+
59
+ Use **Reconnect completed run** after a successful turn. The client sends the
60
+ original input and receives the recorded outcome and snapshot; no new model
61
+ turn or text delta is produced.
62
+
63
+ ## Check in a Browser
64
+
65
+ ```sh
66
+ bin/check-browser
67
+ ```
68
+
69
+ This runs Playwright with Chrome or its installed Chromium. On Linux, install
70
+ the browser first with `npx playwright install --with-deps chromium`. Set
71
+ `CHROME_BIN` to select another local Chrome executable.
72
+
73
+ The check starts its own server, runs desktop and 390px mobile scenarios, saves
74
+ screenshots and consumed events under ignored `tmp/browser/`, and stops the
75
+ server and browser. It validates the captured events against the pinned JSON
76
+ schema. Failures retain traces and screenshots. Inspect those artifacts before
77
+ retrying; a screenshot alone is not an assertion.
78
+
79
+ ## Verify an Installed Gem
80
+
81
+ ```sh
82
+ bin/check --package
83
+ ```
84
+
85
+ The package probe builds a gem, installs that artifact outside the checkout,
86
+ and checks both run paths, generated migration, approval, progress, and
87
+ reconnect. It also generates RubyLLM's models and tables, applies the Rails
88
+ example migrations in order, and checks actor-scoped chat persistence. It uses
89
+ available development dependencies. Use `bin/verify-package --rails --audit`
90
+ after `bundle exec rake build` to resolve dependencies in a clean gem home.
91
+
92
+ ## Adapt to a Real Host
93
+
94
+ The example's actor header is a synthetic identity selector. It does not
95
+ provide authentication, CSRF protection, or durable chat history. The run store
96
+ uses SQLite, but the scripted chat objects live in one process and disappear
97
+ when that process stops. A real host authorizes the thread and the next user
98
+ turn, persists its RubyLLM chat, and rechecks tool permission before execution.
99
+
100
+ The demo and browser suite make no live provider call. Read
101
+ [Compatibility]({% link _reference/compatibility.md %}) for the exact versions
102
+ and evidence boundaries.
103
+
104
+ ## Next Steps
105
+
106
+ * [Rails Integration]({% link _advanced/rails-integration.md %}) - install the adapter in your application.
107
+ * [Approval and Resume]({% link _core_features/approval-and-resume.md %}) - inspect the resume contract.
@@ -106,8 +106,11 @@ what makes run identity survive a worker:
106
106
 
107
107
  - `reserve` inserts; a `RecordNotUnique` means another worker won, and the
108
108
  existing row is attached or refused by digest.
109
- - `redeem_interrupt` runs under `row.with_lock`, so exactly one resume records a
110
- decision and the tool runs once.
109
+ - `redeem_interrupt` uses a conditional update and revalidates competing
110
+ decisions, so only one caller redeems an approval.
111
+ - `save` checks record revisions and refuses stale writers. Keep its returned
112
+ record for the next update. See [Worker Recovery]({% link _advanced/worker-recovery.md %})
113
+ before closing a run whose producer stopped.
111
114
  - `find_interrupt` is scoped by `(scope, thread_id, interrupt_id)`, so an
112
115
  interrupt id is not a global key.
113
116
 
@@ -52,7 +52,7 @@ responsibility.
52
52
  - **Redeclare a run id.** The same identity with a *different* input is refused
53
53
  as `RunConflictError` (409 in the Rails adapter) rather than executed
54
54
  ("refuses the same identity with a changed input as a conflict").
55
- - **Run the same tool twice.** A resume is recorded once; a second answer to the
55
+ - **Run the same tool twice.** A resume is recorded once; a new run that answers the
56
56
  same interrupt is refused without executing the tool ("refuses a decision
57
57
  another resume already recorded, without executing the tool").
58
58
  - **Widen what an approval covers.** An interrupt pins the tool call and the
@@ -0,0 +1,104 @@
1
+ ---
2
+ layout: default
3
+ title: Worker Recovery
4
+ nav_order: 4
5
+ description: Close a run after confirmed worker loss without repeating unknown tool effects.
6
+ ---
7
+
8
+ # {{ page.title }}
9
+
10
+ {{ page.description }}
11
+ {: .fs-6 .fw-300 }
12
+
13
+ After reading this guide, you will know:
14
+
15
+ * How to close a run whose worker has stopped.
16
+ * How record revisions prevent stale writes.
17
+ * Why recovery cannot prove or undo tool effects.
18
+
19
+ ## Recover a Stopped Worker
20
+
21
+ First confirm through your process manager that the producer has stopped.
22
+ Then load its record using an authorized scope and exact identity:
23
+
24
+ ```ruby
25
+ record = store.find(scope: authenticated_scope, thread_id: thread_id, run_id: run_id)
26
+ raise 'Run not found' unless record
27
+
28
+ # The host has confirmed that the producer and its tool threads have stopped.
29
+ recovered = store.recover(record)
30
+ recovered.status # => :failed
31
+ recovered.failure.fetch('code') # => 'worker_lost'
32
+ ```
33
+
34
+ Use `ActiveRecordStore` when the record must survive a process exit. Recovery
35
+ changes a reserved or started record to failed. It retains the identity,
36
+ snapshot, and input digest. The original request can reconnect to a sanitized
37
+ `RUN_ERROR` with code `worker_lost`; it cannot execute the run again.
38
+
39
+ Recovery does not stop a worker. A timeout, disconnected browser, or old
40
+ `updated_at` value does not prove the worker is dead. Confirm that all producer
41
+ and tool activity has stopped before calling this method. The gem does not
42
+ provide leases, worker discovery, or automatic recovery.
43
+
44
+ ## Keep the Latest Record
45
+
46
+ Each successful store write increments `RunRecord#revision`. Keep the record
47
+ returned by `save` if you write it again:
48
+
49
+ ```ruby
50
+ record = store.save(record.start(now: Time.now))
51
+ record = store.save(record.finish(:succeeded, now: Time.now))
52
+ ```
53
+
54
+ `save` and `recover` raise `StaleRecordError` when the stored revision changed
55
+ since you read it. This error is a `RunConflictError`. Reload and inspect the
56
+ current outcome before making another decision. A terminal outcome cannot be
57
+ replaced by recovery. The revision is separate from event sequence numbers.
58
+
59
+ The memory store checks revisions under its mutex. The ActiveRecord store uses
60
+ a conditional database update against the observed payload. Competing approval
61
+ redemptions reload and revalidate after a conflict; a repeated decision is a
62
+ replay, and a disagreeing decision is refused.
63
+
64
+ ## Handle an Uncertain Database Write
65
+
66
+ `Run#stream` raises `PersistenceError` if storage fails without a reliable
67
+ acknowledgement. It does not attempt another terminal write or send a guessed
68
+ `RUN_ERROR`. The first write may already have committed. When storage becomes
69
+ available, reload the exact identity. Reconnect if it ended; confirm the worker
70
+ has stopped before recovering a non-terminal record.
71
+
72
+ This applies to identity reservation and approval redemption as well as status
73
+ writes. If approval acknowledgement is lost, the decision may already be stored
74
+ even though the chat never received it. Inspect both records and reconcile the
75
+ chat; do not issue a new resume or execute the tool on the assumption that the
76
+ decision failed.
77
+
78
+ A stale or failed producer disables its mapper callbacks before returning, so
79
+ reusing its chat cannot append events to that old stream.
80
+
81
+ ## Reconcile External Effects
82
+
83
+ A tool may complete its external change before the worker dies. A recovered
84
+ record says that execution ended without a recorded outcome; it does not say
85
+ that the tool failed or that no effect occurred. Inspect the external system
86
+ and use host-owned idempotency keys before starting another run. Never delete
87
+ the reservation to retry an uncertain effect. The gem does not promise
88
+ exactly-once external effects across crashes.
89
+
90
+ The host also serializes different run ids that share one mutable chat. Run
91
+ identity and approval redemption do not lock an entire conversation.
92
+
93
+ ## Upgrade the Store Contract
94
+
95
+ The revision lives in the JSON payload, so the shipped table needs no new
96
+ migration. Records written before 0.3 load with revision zero. Drain old workers
97
+ before upgrading: a 0.2 writer does not honor the new conditional-write contract.
98
+ Custom stores must implement atomic revision checks, return the incremented
99
+ record from `save`, and provide the same recovery semantics as `Store::Base`.
100
+
101
+ ## Next Steps
102
+
103
+ * [Reconnects and Run Identity]({% link _core_features/reconnects.md %}) - report a recorded outcome.
104
+ * [Security and Deployment]({% link _advanced/security-and-deployment.md %}) - keep authorization in the host.
@@ -0,0 +1,84 @@
1
+ ---
2
+ layout: default
3
+ title: Cancellation and Timeouts
4
+ nav_order: 5
5
+ description: Request cancellation on the authorized producer and distinguish it from a disconnected stream or provider timeout.
6
+ ---
7
+
8
+ # {{ page.title }}
9
+
10
+ {{ page.description }}
11
+ {: .fs-6 .fw-300 }
12
+
13
+ After reading this guide, you will know:
14
+
15
+ * How to request cancellation on the producer's chat.
16
+ * Why aborting a browser request does not cancel server work.
17
+ * How provider timeouts become recorded failures.
18
+
19
+ ## Request Cancellation in the Host
20
+
21
+ Resolve the active chat through your host's authenticated registry, using the
22
+ exact actor, thread, and run identity. The lookup below is application code:
23
+
24
+ ```ruby
25
+ chat = authorized_active_chat_for(current_actor, thread_id: thread_id, run_id: run_id)
26
+ chat.cancel
27
+ ```
28
+
29
+ RubyLLM checks cancellation cooperatively. When it raises `CancelledError`,
30
+ `Run` closes open content and persists a cancelled outcome. The client receives
31
+ `RUN_FINISHED` with `outcome.type` equal to `cancelled`. A cancellation request
32
+ is not proof that the run has stopped; wait for its recorded outcome.
33
+
34
+ Reject a cancellation for another actor, a previous run, or an inactive chat.
35
+ Otherwise a delayed cancellation can stop a later turn. The host serializes
36
+ operations on a mutable chat and delivers cancellation to the worker that owns
37
+ it. Calling `cancel` on a newly loaded chat in another process does not cancel
38
+ the original in-memory object. The gem supplies no cross-worker message broker.
39
+
40
+ ## Keep HTTP Abort Separate
41
+
42
+ `HttpAgent#abortRun()` stops the browser's HTTP subscription. It does not call
43
+ `Chat#cancel`. While the producer remains alive, the gem detaches its failed
44
+ writer and continues to record the actual outcome. Reconnect with the same
45
+ input and run id after completion to read that result.
46
+
47
+ Wire an explicit, authorized cancellation endpoint when your application needs
48
+ server cancellation. The maintained client example shows both actions. See
49
+ [Client Example]({% link _advanced/client-example.md %}).
50
+
51
+ ## Bound Provider Requests
52
+
53
+ Set provider transport limits through RubyLLM's context:
54
+
55
+ ```ruby
56
+ context = RubyLLM.context do |config|
57
+ config.request_timeout = 30
58
+ config.max_retries = 0
59
+ end
60
+ chat = context.chat(model: 'gpt-4o-mini')
61
+ ```
62
+
63
+ A provider request timeout ends the AG-UI run as failed, with a sanitized
64
+ `RUN_ERROR` code `transport_timeout`. Reconnecting reports the same failure
65
+ without a new provider request. A timeout is not a cancelled outcome.
66
+
67
+ The request timeout does not bound an entire multi-request turn or a local
68
+ tool. Provider retries can extend elapsed time. Put deadlines and cancellation
69
+ checkpoints in your tools and reconcile external effects before retrying an
70
+ uncertain action. Cancellation cannot undo a tool that already changed an
71
+ external system.
72
+
73
+ ## Check the Offline Evidence
74
+
75
+ `spec/integration/provider_lifecycle_spec.rb` runs the real RubyLLM chat with an
76
+ intercepted HTTP request. It verifies timeout classification and cancellation
77
+ before a provider request. It uses synthetic configuration and makes no live
78
+ provider call. Browser fixtures separately exercise host cancellation and
79
+ HTTP abort; they do not establish a provider's cancellation latency.
80
+
81
+ ## Next Steps
82
+
83
+ * [Streaming Runs]({% link _core_features/streaming-runs.md %}) - understand terminal outcomes.
84
+ * [Worker Recovery]({% link _advanced/worker-recovery.md %}) - close a run after confirmed worker death.
@@ -29,12 +29,24 @@ The store reserves a run before any provider work. It keys the record by authent
29
29
 
30
30
  Reconnect does not replay text or tool deltas. Replaying deltas could display text twice or repeat a side effect. The host can publish a state snapshot for a finished run, but the gem does not reconstruct conversation history.
31
31
 
32
+ The same rule applies to a completed approval-resume run. Resend its exact
33
+ input, including `resume`, with the original run id to receive the recorded
34
+ outcome without applying the decision again. A new run id that tries to answer
35
+ an already answered interrupt is refused. Changing the input under an existing
36
+ run id is a conflict.
37
+
32
38
  ## Choose a Store
33
39
 
34
- `MemoryStore` is suitable for tests and a single process. Its records disappear on restart and are not shared between workers. The Rails adapter's `ActiveRecordStore` persists records and redeems interrupts under a database lock.
40
+ `MemoryStore` is suitable for tests and a single process. Its records disappear on restart and are not shared between workers. The Rails adapter's `ActiveRecordStore` persists records and redeems interrupts with atomic conditional updates.
35
41
 
36
42
  The store boundary is `RubyLLM::AgUI::Store::Base`. Configure a compatible store globally or pass it to `Run.new`. For multi-process deployments, the database must enforce unique run identity and serialize interrupt redemption.
37
43
 
44
+ Store writes check `RunRecord#revision` and refuse stale snapshots. A run whose
45
+ worker died remains non-terminal until the host confirms the worker stopped
46
+ and explicitly recovers it. See
47
+ [Worker Recovery]({% link _advanced/worker-recovery.md %}) before changing a
48
+ stuck record; deleting its reservation can repeat unknown tool effects.
49
+
38
50
  ## Next Steps
39
51
 
40
52
  * [Configuration]({% link _getting_started/configuration.md %}) - set the default store.