Compare commits
21 Commits
v0.0.1.alp
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 65a44ca150 | |||
| f4bf4eb625 | |||
| 49a161632e | |||
| 9277646a4b | |||
| 2cbc6adebc | |||
| f1e2f0c03f | |||
| 19f31a87fb | |||
|
|
425e423753 | ||
| 1d900af7bc | |||
| 5379aa0847 | |||
| 84442fd28e | |||
|
|
22e3127e90 | ||
| ef9f7e44dd | |||
|
|
78b6f9c9e9 | ||
| edad9c7018 | |||
|
|
a116b2708c | ||
| b16292723e | |||
| 8adc95985a | |||
| 5113a953db | |||
| de14d57634 | |||
| 2e866a618b |
74
.github/workflows/release.yml
vendored
Normal file
74
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
name: Push gem
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
ruby: ["3.2", "3.3", "3.4", "4.0"]
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Ruby ${{ matrix.ruby }}
|
||||
uses: ruby/setup-ruby@003a5c4d8d6321bd302e38f6f0ec593f77f06600 # v1.319.0
|
||||
with:
|
||||
ruby-version: ${{ matrix.ruby }}
|
||||
bundler-cache: true
|
||||
|
||||
- name: Verify tag matches gem version
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: >-
|
||||
ruby -Ilib -ropencode/version -e
|
||||
'expected = ENV.fetch("RELEASE_TAG").delete_prefix("v");
|
||||
abort "tag #{expected.inspect} does not match gem #{Opencode::VERSION.inspect}"
|
||||
unless Opencode::VERSION == expected'
|
||||
|
||||
- name: Run tests
|
||||
run: bundle exec rake test
|
||||
|
||||
- name: Build gem
|
||||
run: gem build opencode-ruby.gemspec
|
||||
|
||||
- name: Verify gem loads after install
|
||||
run: |
|
||||
bundle_gem_path="$(bundle exec ruby -e 'puts Gem.path.join(":")')"
|
||||
export GEM_HOME="${RUNNER_TEMP}/opencode-ruby-${{ matrix.ruby }}"
|
||||
export GEM_PATH="${GEM_HOME}:${bundle_gem_path}"
|
||||
mkdir -p "$GEM_HOME"
|
||||
gem_file="opencode-ruby-$(ruby -Ilib -ropencode/version -e 'print Opencode::VERSION').gem"
|
||||
gem install --local "$gem_file" --no-document
|
||||
ruby -ropencode-ruby -e '
|
||||
root = File.realpath(ENV.fetch("GEM_HOME"))
|
||||
path = File.realpath(Gem.loaded_specs.fetch("opencode-ruby").full_gem_path)
|
||||
abort "opencode-ruby loaded outside isolated GEM_HOME: #{path}" unless path.start_with?("#{root}/")
|
||||
puts Opencode::VERSION
|
||||
'
|
||||
|
||||
push:
|
||||
needs: verify
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
environment: release
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: ruby/setup-ruby@003a5c4d8d6321bd302e38f6f0ec593f77f06600 # v1.319.0
|
||||
with:
|
||||
ruby-version: "4.0"
|
||||
bundler-cache: true
|
||||
- uses: rubygems/release-gem@052cc82692552de3ef2b81fd670e41d13cba8092 # v1.4.0
|
||||
8
.github/workflows/test.yml
vendored
8
.github/workflows/test.yml
vendored
@@ -12,12 +12,12 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
ruby: ["3.2", "3.3", "3.4"]
|
||||
ruby: ["3.2", "3.3", "3.4", "4.0"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
|
||||
- name: Set up Ruby ${{ matrix.ruby }}
|
||||
uses: ruby/setup-ruby@v1
|
||||
uses: ruby/setup-ruby@003a5c4d8d6321bd302e38f6f0ec593f77f06600 # v1.319.0
|
||||
with:
|
||||
ruby-version: ${{ matrix.ruby }}
|
||||
bundler-cache: true
|
||||
@@ -30,5 +30,5 @@ jobs:
|
||||
|
||||
- name: Verify gem loads after install
|
||||
run: |
|
||||
gem install --local opencode-ruby-*.gem
|
||||
gem install opencode-ruby-*.gem --no-document
|
||||
ruby -ropencode-ruby -e 'puts Opencode::VERSION'
|
||||
|
||||
81
CHANGELOG.md
81
CHANGELOG.md
@@ -1,5 +1,82 @@
|
||||
# Changelog
|
||||
|
||||
## 0.0.1.alpha9 - 2026-07-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- Parse SSE events with CRLF, CR-only, or LF framing; accept `data:` fields
|
||||
with or without the optional leading space; join multiple `data:` fields;
|
||||
ignore the stream's optional leading UTF-8 BOM and comment fields; and decode
|
||||
correctly when a transport chunk splits any byte of the event framing.
|
||||
- Keep request instrumentation free of query credentials and private workspace
|
||||
paths.
|
||||
- Load non-empty todo events and written-file artifacts in standalone Ruby
|
||||
clients.
|
||||
- Bound reconnects after an interactive prompt loses its event stream, handle
|
||||
DNS failures as transient stream errors, and map non-404 4xx responses to
|
||||
`BadRequestError` consistently.
|
||||
- Retry the Rails recovery recipe with its replacement session and keep
|
||||
exception details out of user-facing message content.
|
||||
|
||||
### Changed
|
||||
|
||||
- Test Ruby 3.2, 3.3, 3.4, and 4.0; pin every third-party CI and release
|
||||
action to an exact reviewed commit; and use Ruby 4.0 for release builds.
|
||||
- Fail the trusted-publishing job before release when the pushed tag does not
|
||||
match `Opencode::VERSION`.
|
||||
|
||||
## 0.0.1.alpha8 - 2026-07-20
|
||||
|
||||
### Yanked
|
||||
|
||||
- Published from the unrepaired alpha8 source by mistake and yanked the same
|
||||
day. Use alpha9, which contains the intended alpha8 fixes and release gates.
|
||||
|
||||
## 0.0.1.alpha7 - 2026-07-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Add an at-most-once `on_subscribed` hook to the lower-level
|
||||
`Opencode::Client#stream_events` API. Higher-level orchestrators can now
|
||||
wait for `server.connected` before submitting `prompt_async` without
|
||||
abandoning their own Reply observers, persistence, or recovery pipeline.
|
||||
- Propagate subscription-hook failures directly and never invoke the hook
|
||||
again on SSE reconnect. Ambiguous prompt transport failures therefore
|
||||
cannot silently become duplicate turns.
|
||||
|
||||
## 0.0.1.alpha6 - 2026-07-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Make `Opencode::Client#stream` wait for OpenCode's initial
|
||||
`server.connected` SSE readiness frame before submitting `prompt_async`,
|
||||
closing the fast-response window where a turn could emit events before the
|
||||
client was listening.
|
||||
- Keep prompt submission at-most-once across automatic SSE reconnects. A
|
||||
reconnect now reopens only the event stream; it never posts the user prompt
|
||||
again, and prompt transport failures remain visible to the caller.
|
||||
|
||||
## 0.0.1.alpha5 - 2026-07-15
|
||||
|
||||
### Added
|
||||
|
||||
- Extend `Opencode::Client#create_session` with OpenCode's native parent,
|
||||
agent, model, metadata, and workspace fields while preserving the existing
|
||||
title and permission call shape. Session model strings are encoded with the
|
||||
session endpoint's `{ providerID, id }` shape rather than the message
|
||||
endpoint's `{ providerID, modelID }` shape.
|
||||
|
||||
## 0.0.1.alpha4 - 2026-07-12
|
||||
|
||||
### Fixed
|
||||
|
||||
- End SSE streams on current OpenCode `session.status` idle events while
|
||||
retaining compatibility with legacy `session.idle` events.
|
||||
- Reconcile every assistant message in the current user turn after multi-step
|
||||
tool loops, preserving stream-only parts without duplicating final text.
|
||||
- Parse terminal tool parts in standalone Ruby clients without relying on the
|
||||
Rails-loaded `Object#in?` extension.
|
||||
|
||||
## 0.0.1.alpha3 - 2026-07-10
|
||||
|
||||
### Added
|
||||
@@ -55,5 +132,7 @@ First public alpha. HTTP + SSE client for OpenCode REST API.
|
||||
### Compatibility
|
||||
|
||||
- Ruby ≥ 3.2
|
||||
- OpenCode server ≥ 1.15 (tested against the message bus schema in `packages/opencode/src/session/message-v2.ts`)
|
||||
- OpenCode targeted the then-current 1.15 message-bus shape. This historical
|
||||
target was not a blanket SemVer compatibility guarantee; use the README's
|
||||
current compatibility evidence for deployment decisions.
|
||||
- Runtime dependency: `activesupport (>= 6.1)` for `blank?`/`present?`/`presence`/`truncate`/`duplicable?`/`megabytes`. ActiveSupport is *not* Rails — it's a standalone helpers gem.
|
||||
|
||||
92
README.md
92
README.md
@@ -48,6 +48,29 @@ Multi-tenant apps construct multiple clients with different `base_url`s — each
|
||||
|
||||
## Core API
|
||||
|
||||
### Configured and parent-linked sessions
|
||||
|
||||
OpenCode can create a session under an existing parent and select its agent,
|
||||
model, metadata, workspace, and permission policy in the same request:
|
||||
|
||||
```ruby
|
||||
child = client.create_session(
|
||||
title: "Destination curator",
|
||||
parent_id: parent_session_id,
|
||||
agent: "destination-list-curator",
|
||||
model: "openai/gpt-5.5",
|
||||
metadata: { run_id: "9" },
|
||||
workspace_id: workspace_id,
|
||||
permissions: permission_rules
|
||||
)
|
||||
```
|
||||
|
||||
Model strings use OpenCode's `provider/model` form; a preformatted model hash
|
||||
with `providerID` and `id` keys is also accepted. These configured-session
|
||||
fields first appeared in OpenCode 1.16.1. That is an API-introduction note,
|
||||
not evidence that every later server is compatible; use the
|
||||
[certified compatibility evidence](#compatibility) for deployment choices.
|
||||
|
||||
### Streaming (the headline)
|
||||
|
||||
```ruby
|
||||
@@ -65,6 +88,11 @@ reply.reasoning_text # => the model's hidden reasoning, if any
|
||||
reply.parts_json # => the full ordered parts array, ready for persistence
|
||||
```
|
||||
|
||||
`stream` waits for OpenCode's initial `server.connected` SSE readiness frame
|
||||
before it submits the asynchronous prompt. If the event connection drops
|
||||
afterward, the client reconnects only the subscription; it never reposts the
|
||||
prompt. This prevents both missed fast responses and duplicate turns.
|
||||
|
||||
### Synchronous send (no streaming)
|
||||
|
||||
```ruby
|
||||
@@ -80,8 +108,9 @@ client.update_session(session_id, permissions: permission_rules)
|
||||
|
||||
OpenCode appends PATCHed permission rules and evaluates the last matching
|
||||
rule. Hosts should send a complete ordered policy and fingerprint it so the
|
||||
same policy is not appended on every turn. This endpoint requires OpenCode
|
||||
1.16.1 or newer; the rest of the client remains compatible with 1.15.
|
||||
same policy is not appended on every turn. This endpoint first appeared in
|
||||
OpenCode 1.16.1; that version floor describes endpoint availability, not
|
||||
compatibility with every later server.
|
||||
|
||||
### Lower-level event firehose
|
||||
|
||||
@@ -89,10 +118,27 @@ If you need raw SSE events (every server tick, todo update, prompt asked/replied
|
||||
|
||||
```ruby
|
||||
client.stream_events(session_id: session_id) do |event|
|
||||
puts event[:type] # "message.part.delta", "todo.updated", "session.idle", ...
|
||||
puts event[:type] # "message.part.delta", "todo.updated", "session.status", ...
|
||||
end
|
||||
```
|
||||
|
||||
Orchestrators that submit their own async prompt must do so through
|
||||
`on_subscribed`; the callback runs only after the first `server.connected`
|
||||
frame and at most once across automatic reconnects:
|
||||
|
||||
```ruby
|
||||
client.stream_events(
|
||||
session_id: session_id,
|
||||
on_subscribed: -> { client.send_message_async(session_id, prompt) }
|
||||
) do |event|
|
||||
reply.apply(event)
|
||||
end
|
||||
```
|
||||
|
||||
If the callback raises, `stream_events` propagates that error and does not
|
||||
retry it. This is intentional: a timed-out prompt response is ambiguous, so
|
||||
reposting could duplicate the model turn and its cost.
|
||||
|
||||
### Interactive prompts
|
||||
|
||||
When the agent uses the `question` or `permission` tools, opencode emits `question.asked` / `permission.asked` events. Answer them via:
|
||||
@@ -112,7 +158,7 @@ begin
|
||||
rescue Opencode::ConnectionError # server unreachable
|
||||
rescue Opencode::TimeoutError # client-side timeout
|
||||
rescue Opencode::SessionNotFoundError # 404 on a session
|
||||
rescue Opencode::StaleSessionError # session.idle never arrived
|
||||
rescue Opencode::StaleSessionError # no session event arrived after the prompt
|
||||
rescue Opencode::IdleStreamError # mid-turn SSE wedge
|
||||
rescue Opencode::ServerError # 5xx
|
||||
rescue Opencode::BadRequestError # 4xx other than 404
|
||||
@@ -156,8 +202,29 @@ Want every OpenCode endpoint auto-generated from the OpenAPI spec? Use [`opencod
|
||||
## Compatibility
|
||||
|
||||
- Ruby ≥ 3.2
|
||||
- OpenCode server ≥ 1.15
|
||||
- Runtime dependency: `activesupport (>= 6.1)` — *not* Rails. ActiveSupport is a standalone helpers gem (`blank?`, `present?`, `presence`, `truncate`, etc.).
|
||||
- Runtime dependency: `activesupport (>= 6.1, < 9.0)` — *not* Rails. ActiveSupport is a standalone helpers gem (`blank?`, `present?`, `presence`, `truncate`, etc.).
|
||||
- Runtime dependency: `marcel (~> 1.0)` for artifact MIME type detection.
|
||||
|
||||
OpenCode server compatibility is evidence-based, not an open-ended SemVer
|
||||
promise. OpenCode's HTTP, SSE, and runtime behavior can change independently
|
||||
of a numeric version floor, so this gem does not infer compatibility from a
|
||||
constraint such as `>= 1.15`.
|
||||
|
||||
Use the [OpenCode compatibility corpus](https://github.com/ajaynomics/opencode-compat)
|
||||
as the source of current evidence. Its
|
||||
[image matrix](https://github.com/ajaynomics/opencode-compat/blob/main/manifests/image-matrix.json)
|
||||
records the exact gem commit and immutable OpenCode OCI digest exercised by
|
||||
the `ruby-rest-sse` profile. Its
|
||||
[runtime tuples](https://github.com/ajaynomics/opencode-compat/blob/main/manifests/runtime-tuples.json)
|
||||
add the exact consumer commit and canary evidence needed for promotion and
|
||||
rollback. A version label or image tag is provenance only, never the execution
|
||||
coordinate.
|
||||
|
||||
A combination absent from passing evidence is **unverified**, not necessarily
|
||||
incompatible. Run the corpus against the exact gem, image digest, and consumer
|
||||
commit before adopting or promoting it. See the
|
||||
[certification policy](https://github.com/ajaynomics/opencode-compat/blob/main/docs/certification.md)
|
||||
for the full process.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -166,7 +233,18 @@ bundle install
|
||||
bundle exec rake test
|
||||
```
|
||||
|
||||
16-test smoke covers Client end-to-end against WebMock-stubbed OpenCode endpoints.
|
||||
The smoke suite covers Client end-to-end against WebMock-stubbed OpenCode
|
||||
endpoints, including subscription-before-prompt ordering and
|
||||
reconnect-without-repost.
|
||||
|
||||
The mistakenly published `0.0.1.alpha8` package contained unrepaired source and
|
||||
was yanked; use `0.0.1.alpha9` or later. The repository contains a tag-triggered
|
||||
`release.yml` workflow intended for RubyGems trusted publishing, but its
|
||||
trusted-publisher registration is not confirmed for alpha9. A `v*` tag push
|
||||
therefore does not currently guarantee publication. Before a future release,
|
||||
verify the RubyGems registry result explicitly. Once the workflow is registered
|
||||
as a trusted publisher for the `release` environment, it can build, attest, and
|
||||
publish without a long-lived RubyGems API key.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -128,12 +128,13 @@ class GenerateAssistantReplyJob < ApplicationJob
|
||||
end
|
||||
rescue Opencode::SessionNotFoundError, Opencode::StaleSessionError
|
||||
raise if attempted_recreate
|
||||
message.conversation.recreate_opencode_session!(client)
|
||||
session_id = message.conversation.recreate_opencode_session!(client)
|
||||
attempted_recreate = true
|
||||
retry
|
||||
end
|
||||
rescue StandardError => e
|
||||
message&.update!(status: :errored, content: "An error occurred: #{e.message.truncate(200)}")
|
||||
Rails.logger.error(e.full_message)
|
||||
message&.update!(status: :errored, content: "An error occurred. Please try again.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
# non-Rails apps.
|
||||
require "active_support/core_ext/object/blank" # provides blank?, present?, presence
|
||||
require "active_support/core_ext/object/duplicable"
|
||||
require "active_support/core_ext/hash/keys" # provides Hash#deep_stringify_keys
|
||||
require "active_support/core_ext/string/filters" # provides String#truncate
|
||||
require "active_support/core_ext/numeric/bytes" # provides Integer#megabytes
|
||||
require "marcel"
|
||||
|
||||
require_relative "opencode/version"
|
||||
require_relative "opencode/error"
|
||||
|
||||
@@ -25,8 +25,24 @@ module Opencode
|
||||
@workspace = workspace
|
||||
end
|
||||
|
||||
def create_session(title: nil, permissions: nil)
|
||||
body = { title: title, permission: permissions }.compact
|
||||
def create_session(
|
||||
title: nil,
|
||||
permissions: nil,
|
||||
parent_id: nil,
|
||||
agent: nil,
|
||||
model: nil,
|
||||
metadata: nil,
|
||||
workspace_id: nil
|
||||
)
|
||||
body = {
|
||||
title: title,
|
||||
permission: permissions,
|
||||
parentID: parent_id,
|
||||
agent: agent,
|
||||
model: format_session_model(model),
|
||||
metadata: metadata,
|
||||
workspaceID: workspace_id
|
||||
}.compact
|
||||
post("/session", body)
|
||||
end
|
||||
|
||||
@@ -115,21 +131,35 @@ module Opencode
|
||||
on_activity_tick: nil,
|
||||
&block
|
||||
)
|
||||
send_message_async(
|
||||
session_id, text,
|
||||
model: model, agent: agent, system: system, message_id: message_id
|
||||
)
|
||||
|
||||
reply = Opencode::Reply.new
|
||||
reply.add_observer(StreamBlockObserver.new(&block)) if block_given?
|
||||
|
||||
stream_events(
|
||||
# Opening the event stream after prompt_async leaves a race where a fast
|
||||
# turn can emit (and finish) before the client is subscribed. Wait for
|
||||
# OpenCode's initial server.connected SSE frame, then submit the prompt
|
||||
# exactly once. Reconnects invoke on_subscribed again, so mark the attempt
|
||||
# before the POST: an ambiguous prompt response must never cause the same
|
||||
# turn to be submitted twice.
|
||||
prompt_attempted = false
|
||||
on_subscribed = lambda do
|
||||
next false if prompt_attempted
|
||||
|
||||
prompt_attempted = true
|
||||
send_message_async(
|
||||
session_id, text,
|
||||
model: model, agent: agent, system: system, message_id: message_id
|
||||
)
|
||||
true
|
||||
end
|
||||
|
||||
consume_event_stream(
|
||||
session_id: session_id,
|
||||
timeout: stream_timeout,
|
||||
first_event_timeout: first_event_timeout,
|
||||
idle_stream_timeout: idle_stream_timeout,
|
||||
reply: reply,
|
||||
on_activity_tick: on_activity_tick
|
||||
on_activity_tick: on_activity_tick,
|
||||
on_subscribed: on_subscribed
|
||||
) do |event|
|
||||
reply.apply(event)
|
||||
end
|
||||
@@ -200,18 +230,12 @@ module Opencode
|
||||
request = Net::HTTP::Get.new(uri)
|
||||
add_auth_header(request)
|
||||
|
||||
response = Opencode::Instrumentation.instrument("opencode.request", method: request.method, path: request.path) do
|
||||
response = Opencode::Instrumentation.instrument("opencode.request", method: request.method, path: uri.path) do
|
||||
http_client.request(request)
|
||||
end
|
||||
|
||||
unless response.code.to_i.between?(200, 299)
|
||||
raise ServerError, "list_questions failed: HTTP #{response.code} — #{response.body.to_s[0, 200]}"
|
||||
end
|
||||
|
||||
return [] if response.body.blank?
|
||||
JSON.parse(response.body, symbolize_names: true)
|
||||
rescue JSON::ParserError => e
|
||||
raise ServerError, "list_questions returned invalid JSON: #{e.message}"
|
||||
body = handle_response(response)
|
||||
body.is_a?(Array) ? body : []
|
||||
rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
|
||||
raise TimeoutError, "OpenCode timeout after #{@timeout}s: #{e.message}"
|
||||
rescue Errno::ECONNREFUSED, SocketError => e
|
||||
@@ -225,6 +249,10 @@ module Opencode
|
||||
end
|
||||
|
||||
MAX_SSE_BUFFER = 1_048_576 # 1 MB — safety valve against pathological server responses
|
||||
# Keep CRLF atomic so it cannot backtrack into CR + LF and look like a
|
||||
# blank line. SSE also permits bare CR and LF line endings.
|
||||
SSE_EVENT_BOUNDARY = /(?>\r\n|[\r\n]){2}/
|
||||
UTF8_BOM = "\xEF\xBB\xBF".b.freeze
|
||||
SSE_RECONNECT_DELAY = 0.1
|
||||
TRANSIENT_SSE_ERRORS = [
|
||||
EOFError,
|
||||
@@ -233,12 +261,15 @@ module Opencode
|
||||
Net::ReadTimeout,
|
||||
Errno::ECONNREFUSED,
|
||||
Errno::ECONNRESET,
|
||||
Errno::EPIPE
|
||||
Errno::EPIPE,
|
||||
SocketError
|
||||
].freeze
|
||||
|
||||
# Opens SSE connection to GET /event, yields parsed events filtered by session_id.
|
||||
# Blocks until session goes idle or timeout, reconnecting across dropped
|
||||
# event-stream connections.
|
||||
# Blocks until the session reports idle or timeout, reconnecting across
|
||||
# dropped event-stream connections. Current OpenCode emits
|
||||
# `session.status` with `status.type == "idle"`; older versions emitted the
|
||||
# standalone `session.idle` event, so both remain terminal.
|
||||
#
|
||||
# first_event_timeout: seconds to wait for a session-specific event before
|
||||
# declaring the session stale. Server heartbeats don't count — they're global
|
||||
@@ -253,6 +284,13 @@ module Opencode
|
||||
# without nuking real reasoning. Callers that know their agent is
|
||||
# short-prompt + fast can pass a lower value.
|
||||
#
|
||||
# on_subscribed: optional callable invoked at most once, after the first
|
||||
# `server.connected` frame proves the SSE response body is flowing. This
|
||||
# is the safe place for higher-level orchestrators to submit prompt_async;
|
||||
# reconnects wait for their own connected frame but never invoke it again.
|
||||
# A raised callback error is propagated directly and is never treated as
|
||||
# a reconnectable SSE transport failure.
|
||||
#
|
||||
# idle_stream_timeout: seconds to wait BETWEEN meaningful events once
|
||||
# the session has started producing them. Default nil = no check
|
||||
# (preserves the overall `timeout` ceiling behavior). Opt-in heartbeat
|
||||
@@ -266,16 +304,32 @@ module Opencode
|
||||
# translate into a user-visible error / retry affordance.
|
||||
def stream_events(session_id:, timeout: 600, first_event_timeout: 120,
|
||||
idle_stream_timeout: nil,
|
||||
reply: nil, on_activity_tick: nil, &block)
|
||||
reply: nil, on_activity_tick: nil, on_subscribed: nil, &block)
|
||||
consume_event_stream(
|
||||
session_id: session_id,
|
||||
timeout: timeout,
|
||||
first_event_timeout: first_event_timeout,
|
||||
idle_stream_timeout: idle_stream_timeout,
|
||||
reply: reply,
|
||||
on_activity_tick: on_activity_tick,
|
||||
on_subscribed: on_subscribed,
|
||||
&block
|
||||
)
|
||||
end
|
||||
|
||||
private def consume_event_stream(session_id:, timeout:, first_event_timeout:,
|
||||
idle_stream_timeout:, reply:, on_activity_tick:,
|
||||
on_subscribed: nil, &block)
|
||||
uri = build_uri("/event")
|
||||
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
||||
first_event_deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + first_event_timeout
|
||||
received_session_event = false
|
||||
last_meaningful_event_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
subscription_callback_attempted = on_subscribed.nil?
|
||||
|
||||
loop do
|
||||
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
deadline = check_deadline_or_suspend(now, deadline, timeout, reply)
|
||||
deadline = check_deadline(now, deadline, timeout)
|
||||
|
||||
# NOTE: first_event_deadline is *not* suspension-eligible. If the agent
|
||||
# never gets started we want to fail fast — a session that's blocked on
|
||||
@@ -301,8 +355,12 @@ module Opencode
|
||||
http.open_timeout = 10
|
||||
http.read_timeout = 30
|
||||
|
||||
subscription_callback_error = nil
|
||||
event_callback_error = nil
|
||||
subscription_ready = on_subscribed.nil?
|
||||
begin
|
||||
buffer = String.new
|
||||
first_sse_event = true
|
||||
|
||||
http.request(request) do |response|
|
||||
unless response.is_a?(Net::HTTPSuccess)
|
||||
@@ -329,11 +387,54 @@ module Opencode
|
||||
raise ServerError, "SSE buffer exceeded #{MAX_SSE_BUFFER} bytes"
|
||||
end
|
||||
|
||||
while (idx = buffer.index("\n\n"))
|
||||
raw_event = buffer.slice!(0, idx + 2)
|
||||
event = parse_sse_event(raw_event, session_id)
|
||||
while (boundary = buffer.match(SSE_EVENT_BOUNDARY))
|
||||
raw_event = buffer.slice!(0, boundary.end(0))
|
||||
event = parse_sse_event(
|
||||
raw_event,
|
||||
session_id,
|
||||
allow_bom: first_sse_event
|
||||
)
|
||||
first_sse_event = false
|
||||
next unless event
|
||||
|
||||
unless subscription_ready
|
||||
# Every supported OpenCode server starts /event with this
|
||||
# frame. Receiving it proves the stream body is flowing; on
|
||||
# current servers the bus listener is registered eagerly,
|
||||
# and on older lazy-stream servers it is the strongest
|
||||
# available readiness handshake before prompting.
|
||||
next unless event[:type] == "server.connected"
|
||||
|
||||
turn_started = false
|
||||
unless subscription_callback_attempted
|
||||
# Mark the attempt before invoking the callback. A timeout
|
||||
# can mean the prompt reached OpenCode even though its HTTP
|
||||
# response did not reach us; retrying would duplicate the
|
||||
# turn. The caller receives the original error instead.
|
||||
subscription_callback_attempted = true
|
||||
begin
|
||||
turn_started = on_subscribed.call
|
||||
rescue StandardError => error
|
||||
# Prompt submission happens inside the open SSE response.
|
||||
# Do not mistake its transport failure for an SSE disconnect
|
||||
# and hide it behind a reconnect/first-event timeout.
|
||||
subscription_callback_error = error
|
||||
raise
|
||||
end
|
||||
end
|
||||
if turn_started
|
||||
# Before this fix stream_events began only after the prompt
|
||||
# POST returned. Preserve those timeout semantics: the turn
|
||||
# and first-session-event windows begin after prompt_async
|
||||
# succeeds, not while establishing the readiness handshake.
|
||||
started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
deadline = started_at + timeout
|
||||
first_event_deadline = started_at + first_event_timeout
|
||||
last_meaningful_event_at = started_at
|
||||
end
|
||||
subscription_ready = true
|
||||
end
|
||||
|
||||
unless event[:type]&.start_with?("server.")
|
||||
received_session_event = true
|
||||
last_meaningful_event_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
@@ -343,15 +444,23 @@ module Opencode
|
||||
# that's the whole point: a healthy long wait (user thinking
|
||||
# for 30 minutes) keeps the container warm via heartbeats so
|
||||
# the reaper doesn't kill it mid-wait.
|
||||
on_activity_tick&.call(event)
|
||||
block.call(event)
|
||||
return if event[:type] == "session.idle"
|
||||
begin
|
||||
on_activity_tick&.call(event)
|
||||
block.call(event)
|
||||
rescue StandardError => error
|
||||
event_callback_error = error
|
||||
raise
|
||||
end
|
||||
return if terminal_session_event?(event)
|
||||
end
|
||||
end
|
||||
end
|
||||
rescue *TRANSIENT_SSE_ERRORS
|
||||
raise if subscription_callback_error || event_callback_error
|
||||
|
||||
# Treat transport-level SSE disconnects like clean EOF: reconnect
|
||||
# until session.idle, the overall timeout, or first-event timeout.
|
||||
# until an idle session event, the overall timeout, or first-event
|
||||
# timeout.
|
||||
ensure
|
||||
begin
|
||||
http&.finish if http&.started?
|
||||
@@ -385,13 +494,16 @@ module Opencode
|
||||
# the caller's reply is still a usable Result either way.
|
||||
def merge_final_exchange(session_id, reply)
|
||||
exchange = get_messages(session_id)
|
||||
last_assistant = Array(exchange).reverse_each.find do |message|
|
||||
message.dig(:info, :role) == "assistant"
|
||||
end
|
||||
return unless last_assistant
|
||||
polled = current_turn_parts(exchange)
|
||||
return if polled.empty?
|
||||
|
||||
polled = Opencode::ResponseParser.extract_interleaved_parts(last_assistant)
|
||||
reply.sync_recovered_parts(polled) if polled.any?
|
||||
merged = merge_stream_only_parts(reply.result.parts_json, polled)
|
||||
reply.sync_recovered_parts(merged)
|
||||
# sync_recovered_parts intentionally never deletes live parts because it
|
||||
# is also used during mid-stream recovery. This is the terminal poll, so
|
||||
# the wire snapshot is authoritative: remove any replayed trailing wire
|
||||
# part after observers have seen recovered additions/updates.
|
||||
reply.replace_parts(merged) unless reply.result.parts_json == merged
|
||||
rescue Opencode::Error
|
||||
# Stream's result is still complete; the merge was a polish, not a
|
||||
# requirement.
|
||||
@@ -403,11 +515,55 @@ module Opencode
|
||||
# the prompt resolves. Otherwise apply the normal deadline check.
|
||||
def check_deadline_or_suspend(now, deadline, timeout, reply)
|
||||
return now + timeout if reply&.prompt_blocked?
|
||||
|
||||
check_deadline(now, deadline, timeout)
|
||||
end
|
||||
|
||||
def check_deadline(now, deadline, timeout)
|
||||
raise TimeoutError, "SSE stream timed out after #{timeout}s" if now > deadline
|
||||
|
||||
deadline
|
||||
end
|
||||
|
||||
def terminal_session_event?(event)
|
||||
return true if event[:type] == "session.idle"
|
||||
return false unless event[:type] == "session.status"
|
||||
|
||||
status = event.dig(:properties, :status)
|
||||
status = status[:type] || status["type"] if status.is_a?(Hash)
|
||||
status == "idle"
|
||||
end
|
||||
|
||||
# OpenCode persists one assistant message per model step. A tool loop can
|
||||
# therefore produce several assistant messages for one user turn (for
|
||||
# example skill -> task -> final text). Reconcile the complete current turn
|
||||
# instead of aligning the live parts array with only the last assistant
|
||||
# message, which corrupts tool parts and duplicates final text.
|
||||
def current_turn_parts(exchange)
|
||||
messages = Array(exchange)
|
||||
last_user_index = messages.rindex { |message| message.dig(:info, :role) == "user" }
|
||||
current_turn = last_user_index ? messages.drop(last_user_index + 1) : messages
|
||||
|
||||
current_turn
|
||||
.select { |message| message.dig(:info, :role) == "assistant" }
|
||||
.flat_map { |message| Opencode::ResponseParser.extract_interleaved_parts(message) }
|
||||
end
|
||||
|
||||
def merge_stream_only_parts(stream_parts, wire_parts)
|
||||
remaining_wire = Array(wire_parts).dup
|
||||
merged = []
|
||||
|
||||
Array(stream_parts).each do |part|
|
||||
if Opencode::PartSource.stream_only?(part)
|
||||
merged << part
|
||||
elsif remaining_wire.any?
|
||||
merged << remaining_wire.shift
|
||||
end
|
||||
end
|
||||
|
||||
merged.concat(remaining_wire)
|
||||
end
|
||||
|
||||
def prompt_payload(text, parts:, model:, agent:, system:, message_id:, no_reply:, tools:, format:, variant:)
|
||||
message_parts = parts || [ { type: "text", text: text } ]
|
||||
{
|
||||
@@ -431,6 +587,14 @@ module Opencode
|
||||
{ providerID: provider, modelID: model_id }
|
||||
end
|
||||
|
||||
def format_session_model(model)
|
||||
return nil unless model
|
||||
return model if model.is_a?(Hash)
|
||||
|
||||
provider, model_id = model.split("/", 2)
|
||||
{ providerID: provider, id: model_id }
|
||||
end
|
||||
|
||||
def post(path, body)
|
||||
uri = build_uri(path)
|
||||
request = Net::HTTP::Post.new(uri)
|
||||
@@ -470,7 +634,7 @@ module Opencode
|
||||
add_auth_header(request)
|
||||
|
||||
response = nil
|
||||
result = Opencode::Instrumentation.instrument("opencode.request", method: request.method, path: request.path) do
|
||||
result = Opencode::Instrumentation.instrument("opencode.request", method: request.method, path: request.uri.path) do
|
||||
response = http_client.request(request)
|
||||
handle_response(response)
|
||||
end
|
||||
@@ -491,11 +655,22 @@ module Opencode
|
||||
end
|
||||
end
|
||||
|
||||
def parse_sse_event(raw, session_id)
|
||||
data_line = raw.lines.find { |l| l.start_with?("data: ") }
|
||||
return nil unless data_line
|
||||
def parse_sse_event(raw, session_id, allow_bom: false)
|
||||
if allow_bom && raw.b.start_with?(UTF8_BOM)
|
||||
raw = raw.byteslice(UTF8_BOM.bytesize..)
|
||||
end
|
||||
|
||||
json = JSON.parse(data_line.sub("data: ", "").strip, symbolize_names: true)
|
||||
data = raw.split(/\r\n|\r|\n/, -1).filter_map do |line|
|
||||
next if line.start_with?(":")
|
||||
|
||||
field, value = line.split(":", 2)
|
||||
next unless field == "data"
|
||||
|
||||
(value || "").delete_prefix(" ")
|
||||
end
|
||||
return nil if data.empty?
|
||||
|
||||
json = JSON.parse(data.join("\n"), symbolize_names: true)
|
||||
|
||||
event_session = json.dig(:properties, :sessionID) ||
|
||||
json.dig(:properties, :info, :sessionID) ||
|
||||
@@ -511,23 +686,30 @@ module Opencode
|
||||
end
|
||||
|
||||
def handle_response(response)
|
||||
return {} if response.code.to_i == 204
|
||||
status = response.code.to_i
|
||||
return {} if status == 204
|
||||
|
||||
body = if response.body.present?
|
||||
JSON.parse(response.body, symbolize_names: true)
|
||||
else
|
||||
{}
|
||||
end
|
||||
body = parse_response_body(response, status)
|
||||
|
||||
case response.code.to_i
|
||||
case status
|
||||
when 200..299 then body
|
||||
when 400 then raise BadRequestError.new(error_message(body, "Bad request"), response: body)
|
||||
when 404 then raise SessionNotFoundError.new(error_message(body, "Session not found"), response: body)
|
||||
when 400..499 then raise BadRequestError.new(error_message(body, "Bad request"), response: body)
|
||||
when 500..599 then raise ServerError.new(error_message(body, "Server error"), response: body)
|
||||
else raise Error.new("Unexpected response: #{response.code}", response: body)
|
||||
end
|
||||
end
|
||||
|
||||
def parse_response_body(response, status)
|
||||
return {} if response.body.blank?
|
||||
|
||||
JSON.parse(response.body, symbolize_names: true)
|
||||
rescue JSON::ParserError
|
||||
raise ServerError.new("Invalid JSON from OpenCode (HTTP #{response.code}): #{response.body&.truncate(200)}")
|
||||
if status.between?(200, 299)
|
||||
raise ServerError.new("Invalid JSON from OpenCode (HTTP #{response.code}): #{response.body&.truncate(200)}")
|
||||
end
|
||||
|
||||
{ message: response.body.to_s.truncate(200) }
|
||||
end
|
||||
|
||||
# OpenCode HTTP error bodies use a wrapped shape: { name:, data: { message:, kind?: } }.
|
||||
@@ -535,6 +717,9 @@ module Opencode
|
||||
# `body[:message]` is no longer populated for errors — only `body[:data][:message]`.
|
||||
# We read both to keep older mock servers working in tests.
|
||||
def error_message(body, fallback)
|
||||
return body.truncate(200) if body.is_a?(String) && body.present?
|
||||
return fallback unless body.is_a?(Hash)
|
||||
|
||||
body.dig(:data, :message) || body[:message] || fallback
|
||||
end
|
||||
end
|
||||
|
||||
@@ -27,7 +27,7 @@ module Opencode
|
||||
def self.extract_tool_summary(response_body)
|
||||
parts = response_body[:parts] || []
|
||||
parts
|
||||
.select { |p| p[:type] == "tool" && p.dig(:state, :status).in?(TERMINAL_STATUSES) }
|
||||
.select { |p| p[:type] == "tool" && TERMINAL_STATUSES.include?(p.dig(:state, :status)) }
|
||||
.map { |p| build_tool_summary(p) }
|
||||
end
|
||||
|
||||
@@ -42,7 +42,7 @@ module Opencode
|
||||
{ "type" => "reasoning", "content" => part[:text] }
|
||||
when "tool"
|
||||
status = part.dig(:state, :status)
|
||||
next unless status.in?(TERMINAL_STATUSES)
|
||||
next unless TERMINAL_STATUSES.include?(status)
|
||||
|
||||
build_tool_summary(part)
|
||||
else
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Opencode
|
||||
VERSION = "0.0.1.alpha3"
|
||||
VERSION = "0.0.1.alpha9"
|
||||
end
|
||||
|
||||
@@ -30,14 +30,10 @@ Gem::Specification.new do |spec|
|
||||
%w[README.md LICENSE CHANGELOG.md opencode-ruby.gemspec]
|
||||
spec.require_paths = ["lib"]
|
||||
|
||||
# The only runtime dependency is ActiveSupport (NOT Rails). ActiveSupport
|
||||
# is a standalone gem providing the `present?`/`blank?`/`presence`/
|
||||
# `truncate`/`duplicable?` helpers used in this gem's code. It does NOT
|
||||
# pull in ActiveRecord, ActionView, ActionController, Turbo, or any other
|
||||
# Rails-only piece. Most Ruby apps in the wild already have ActiveSupport
|
||||
# transitively via another gem; in the rare case yours doesn't, ~250 LOC
|
||||
# of core_ext is added when this gem installs.
|
||||
# ActiveSupport supplies the small set of core extensions used by the
|
||||
# client without pulling in Rails. Marcel identifies artifact content types.
|
||||
spec.add_runtime_dependency "activesupport", ">= 6.1", "< 9.0"
|
||||
spec.add_runtime_dependency "marcel", "~> 1.0"
|
||||
|
||||
spec.add_development_dependency "minitest", "~> 5.20"
|
||||
spec.add_development_dependency "rake", "~> 13.0"
|
||||
|
||||
22
test/conversation_recipe_test.rb
Normal file
22
test/conversation_recipe_test.rb
Normal file
@@ -0,0 +1,22 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "test_helper"
|
||||
|
||||
class ConversationRecipeTest < Minitest::Test
|
||||
RECIPE = File.read(File.expand_path("../examples/conversation_recipe.rb", __dir__))
|
||||
|
||||
def test_recovery_retries_with_the_recreated_session
|
||||
assert_includes RECIPE,
|
||||
"session_id = message.conversation.recreate_opencode_session!(client)"
|
||||
end
|
||||
|
||||
def test_user_facing_error_does_not_include_exception_details
|
||||
assert_includes RECIPE, 'content: "An error occurred. Please try again."'
|
||||
refute_includes RECIPE, 'content: "An error occurred: #{e.message.truncate(200)}"'
|
||||
end
|
||||
|
||||
def test_error_reporting_works_on_the_supported_rails_6_1_baseline
|
||||
assert_includes RECIPE, "Rails.logger.error(e.full_message)"
|
||||
refute_includes RECIPE, "Rails.error.report"
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,7 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "test_helper"
|
||||
require "timeout"
|
||||
|
||||
# End-to-end smoke test of the gem's public surface. Validates that the
|
||||
# headline `client.stream(...)` API + Reply::Result + error model + the
|
||||
@@ -11,6 +12,7 @@ class SmokeTest < Minitest::Test
|
||||
BASE = "http://opencode.test"
|
||||
PASSWORD = "test-secret"
|
||||
SESSION_ID = "ses_smoke_1"
|
||||
CONNECTED_EVENT = { type: "server.connected", properties: {} }.freeze
|
||||
|
||||
def setup
|
||||
@client = Opencode::Client.new(
|
||||
@@ -46,6 +48,7 @@ class SmokeTest < Minitest::Test
|
||||
|
||||
def test_create_session_returns_session_id
|
||||
stub_request(:post, "#{BASE}/session")
|
||||
.with(body: { title: "smoke", permission: [] }.to_json)
|
||||
.to_return(status: 200, body: { id: SESSION_ID, title: "smoke" }.to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
@@ -53,6 +56,51 @@ class SmokeTest < Minitest::Test
|
||||
assert_equal SESSION_ID, response[:id]
|
||||
end
|
||||
|
||||
def test_create_session_sends_native_child_and_configuration_fields
|
||||
permissions = [ { permission: "skill", pattern: "*", action: "deny" } ]
|
||||
expected_body = {
|
||||
title: "curator",
|
||||
permission: permissions,
|
||||
parentID: "ses_parent",
|
||||
agent: "destination-list-curator",
|
||||
model: { providerID: "openrouter", id: "anthropic/claude-sonnet-4" },
|
||||
metadata: { run: "9" },
|
||||
workspaceID: "wrk_1"
|
||||
}
|
||||
|
||||
stub_request(:post, "#{BASE}/session")
|
||||
.with(body: expected_body.to_json)
|
||||
.to_return(status: 200, body: { id: SESSION_ID }.to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
response = @client.create_session(
|
||||
title: "curator",
|
||||
permissions: permissions,
|
||||
parent_id: "ses_parent",
|
||||
agent: "destination-list-curator",
|
||||
model: "openrouter/anthropic/claude-sonnet-4",
|
||||
metadata: { run: "9" },
|
||||
workspace_id: "wrk_1"
|
||||
)
|
||||
|
||||
assert_equal SESSION_ID, response[:id]
|
||||
assert_requested :post, "#{BASE}/session", body: expected_body.to_json, times: 1
|
||||
end
|
||||
|
||||
def test_create_session_preserves_a_preformatted_model
|
||||
model = { providerID: "openai", id: "gpt-5.5", variant: "high" }
|
||||
|
||||
stub_request(:post, "#{BASE}/session")
|
||||
.with(body: { model: model }.to_json)
|
||||
.to_return(status: 200, body: { id: SESSION_ID }.to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
response = @client.create_session(model: model)
|
||||
|
||||
assert_equal SESSION_ID, response[:id]
|
||||
assert_requested :post, "#{BASE}/session", body: { model: model }.to_json, times: 1
|
||||
end
|
||||
|
||||
def test_update_session_patches_permissions_and_returns_the_updated_session
|
||||
permissions = [
|
||||
{ permission: "skill", pattern: "*", action: "deny" },
|
||||
@@ -79,16 +127,68 @@ class SmokeTest < Minitest::Test
|
||||
assert_equal({}, response)
|
||||
end
|
||||
|
||||
def test_send_message_async_serializes_a_structured_child_prompt
|
||||
schema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
requirement_suggestions: {
|
||||
type: "array",
|
||||
items: { type: "string" }
|
||||
}
|
||||
},
|
||||
required: [ "requirement_suggestions" ],
|
||||
additionalProperties: false
|
||||
}
|
||||
invocation_query =
|
||||
"Complete the bounded structured request from the preloaded worker skill and immutable Rails context."
|
||||
expected_body = {
|
||||
messageID: "msg_worker_1",
|
||||
parts: [ { type: "text", text: invocation_query } ],
|
||||
agent: "destination-list-curator",
|
||||
format: {
|
||||
type: "json_schema",
|
||||
schema: schema,
|
||||
retryCount: 0
|
||||
},
|
||||
system: "Immutable Rails context"
|
||||
}
|
||||
serialized_body = nil
|
||||
|
||||
prompt = stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.with(body: expected_body.to_json)
|
||||
.to_return do |request|
|
||||
serialized_body = request.body
|
||||
{ status: 204, body: "" }
|
||||
end
|
||||
|
||||
@client.send_message_async(
|
||||
SESSION_ID,
|
||||
invocation_query,
|
||||
agent: "destination-list-curator",
|
||||
system: "Immutable Rails context",
|
||||
message_id: "msg_worker_1",
|
||||
format: {
|
||||
type: "json_schema",
|
||||
schema: schema,
|
||||
retryCount: 0
|
||||
}
|
||||
)
|
||||
|
||||
assert_equal expected_body.to_json, serialized_body
|
||||
assert_requested prompt, times: 1
|
||||
end
|
||||
|
||||
def test_stream_returns_typed_Reply_Result_with_full_text
|
||||
stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_return(status: 204, body: "")
|
||||
|
||||
sse = [
|
||||
CONNECTED_EVENT,
|
||||
{ type: "message.part.delta",
|
||||
properties: { sessionID: SESSION_ID, partID: "p1", field: "text", delta: "hello " } },
|
||||
{ type: "message.part.delta",
|
||||
properties: { sessionID: SESSION_ID, partID: "p1", field: "text", delta: "world" } },
|
||||
{ type: "session.idle", properties: { sessionID: SESSION_ID } }
|
||||
{ type: "session.status", properties: { sessionID: SESSION_ID, status: { type: "idle" } } }
|
||||
].map { |e| "data: #{e.to_json}\n\n" }.join
|
||||
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
@@ -111,11 +211,365 @@ class SmokeTest < Minitest::Test
|
||||
refute_empty parts_yielded
|
||||
end
|
||||
|
||||
def test_stream_waits_for_server_connected_before_posting_the_prompt
|
||||
request_order = []
|
||||
connection_count = 0
|
||||
terminal_event = {
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return do
|
||||
connection_count += 1
|
||||
request_order << :sse_accepted
|
||||
events = if connection_count == 1
|
||||
[ { type: "server.heartbeat", properties: {} } ]
|
||||
else
|
||||
[ CONNECTED_EVENT, terminal_event ]
|
||||
end
|
||||
{
|
||||
status: 200,
|
||||
body: events.map { |event| "data: #{event.to_json}\n\n" }.join,
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
}
|
||||
end
|
||||
|
||||
stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_return do
|
||||
request_order << :prompt
|
||||
{ status: 204, body: "" }
|
||||
end
|
||||
|
||||
stub_request(:get, "#{BASE}/session/#{SESSION_ID}/message")
|
||||
.to_return(status: 200, body: [].to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
@client.stream(SESSION_ID, "ping", stream_timeout: 1, first_event_timeout: 1)
|
||||
|
||||
assert_equal [ :sse_accepted, :sse_accepted, :prompt ], request_order
|
||||
end
|
||||
|
||||
def test_stream_does_not_post_when_sse_subscription_is_rejected
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(status: 503, body: "unavailable")
|
||||
prompt = stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_return(status: 204, body: "")
|
||||
|
||||
error = assert_raises(Opencode::ServerError) do
|
||||
@client.stream(SESSION_ID, "ping", stream_timeout: 1, first_event_timeout: 1)
|
||||
end
|
||||
|
||||
assert_match "SSE connection failed: HTTP 503", error.message
|
||||
assert_not_requested prompt
|
||||
end
|
||||
|
||||
def test_stream_surfaces_prompt_timeout_without_reconnecting
|
||||
event_stream = stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(status: 200, body: "data: #{CONNECTED_EVENT.to_json}\n\n",
|
||||
headers: { "Content-Type" => "text/event-stream" })
|
||||
prompt = stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_raise(Net::ReadTimeout.new("prompt timed out"))
|
||||
|
||||
error = assert_raises(Opencode::TimeoutError) do
|
||||
@client.stream(SESSION_ID, "ping", stream_timeout: 1, first_event_timeout: 1)
|
||||
end
|
||||
|
||||
assert_match "OpenCode timeout after 5s", error.message
|
||||
assert_requested event_stream, times: 1
|
||||
assert_requested prompt, times: 1
|
||||
end
|
||||
|
||||
def test_stream_reconnects_without_reposting_the_prompt
|
||||
first_connection = [
|
||||
CONNECTED_EVENT,
|
||||
{ type: "server.heartbeat", properties: {} }
|
||||
]
|
||||
second_connection = [
|
||||
CONNECTED_EVENT,
|
||||
{
|
||||
type: "message.part.delta",
|
||||
properties: { sessionID: SESSION_ID, partID: "p1", field: "text", delta: "once" }
|
||||
},
|
||||
{
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
]
|
||||
|
||||
event_stream = stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(
|
||||
{
|
||||
status: 200,
|
||||
body: first_connection.map { |event| "data: #{event.to_json}\n\n" }.join,
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
},
|
||||
{
|
||||
status: 200,
|
||||
body: second_connection.map { |event| "data: #{event.to_json}\n\n" }.join,
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
}
|
||||
)
|
||||
prompt = stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_return(status: 204, body: "")
|
||||
stub_request(:get, "#{BASE}/session/#{SESSION_ID}/message")
|
||||
.to_return(status: 200, body: [].to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
reply = @client.stream(SESSION_ID, "ping", stream_timeout: 1, first_event_timeout: 1)
|
||||
|
||||
assert_equal "once", reply.full_text
|
||||
assert_requested event_stream, times: 2
|
||||
assert_requested prompt, times: 1
|
||||
end
|
||||
|
||||
def test_stream_events_invokes_on_subscribed_once_after_connected_across_reconnects
|
||||
order = []
|
||||
connections = [
|
||||
[ CONNECTED_EVENT, { type: "server.heartbeat", properties: {} } ],
|
||||
[
|
||||
CONNECTED_EVENT,
|
||||
{
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
]
|
||||
]
|
||||
|
||||
event_stream = stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return do
|
||||
events = connections.shift or raise "unexpected third SSE connection"
|
||||
order << :sse_accepted
|
||||
{
|
||||
status: 200,
|
||||
body: events.map { |event| "data: #{event.to_json}\n\n" }.join,
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
}
|
||||
end
|
||||
|
||||
subscribed_calls = 0
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 1,
|
||||
first_event_timeout: 1,
|
||||
on_subscribed: -> {
|
||||
subscribed_calls += 1
|
||||
order << :prompt
|
||||
true
|
||||
}
|
||||
) { |_event| }
|
||||
|
||||
assert_equal 1, subscribed_calls
|
||||
assert_equal [ :sse_accepted, :prompt, :sse_accepted ], order
|
||||
assert_requested event_stream, times: 2
|
||||
end
|
||||
|
||||
def test_stream_events_surfaces_on_subscribed_timeout_without_reconnecting
|
||||
event_stream = stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(status: 200, body: "data: #{CONNECTED_EVENT.to_json}\n\n",
|
||||
headers: { "Content-Type" => "text/event-stream" })
|
||||
|
||||
calls = 0
|
||||
error = assert_raises(Net::ReadTimeout) do
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 1,
|
||||
first_event_timeout: 1,
|
||||
on_subscribed: -> {
|
||||
calls += 1
|
||||
raise Net::ReadTimeout, "ambiguous prompt response"
|
||||
}
|
||||
) { |_event| }
|
||||
end
|
||||
|
||||
assert_equal "Net::ReadTimeout with \"ambiguous prompt response\"", error.message
|
||||
assert_equal 1, calls
|
||||
assert_requested event_stream, times: 1
|
||||
end
|
||||
|
||||
def test_stream_events_accepts_standard_sse_framing_variants
|
||||
terminal_event = {
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
connected_data = JSON.pretty_generate(CONNECTED_EVENT).lines(chomp: true)
|
||||
.map { |line| "data: #{line}\r\n" }
|
||||
.join
|
||||
body = ": readiness comment\r\nevent: message\r\n#{connected_data}\r\n" \
|
||||
"data:#{terminal_event.to_json}\r\r"
|
||||
|
||||
event_stream = stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(status: 200, body: body,
|
||||
headers: { "Content-Type" => "text/event-stream" })
|
||||
|
||||
subscribed_calls = 0
|
||||
event_types = []
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 1,
|
||||
first_event_timeout: 1,
|
||||
on_subscribed: -> {
|
||||
subscribed_calls += 1
|
||||
true
|
||||
}
|
||||
) { |event| event_types << event.fetch(:type) }
|
||||
|
||||
assert_equal 1, subscribed_calls
|
||||
assert_equal [ "server.connected", "session.status" ], event_types
|
||||
assert_requested event_stream, times: 1
|
||||
end
|
||||
|
||||
def test_stream_events_handles_a_bom_and_boundaries_split_across_chunks
|
||||
terminal_event = {
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
body = "\uFEFF: initial comment\r\n\r\n" \
|
||||
"data: #{CONNECTED_EVENT.to_json}\r\n\r\n" \
|
||||
"data: #{terminal_event.to_json}\n\n"
|
||||
chunks = body.b.bytes.map { |byte| byte.chr(Encoding::BINARY) }
|
||||
|
||||
response = Net::HTTPOK.new("1.1", "200", "OK")
|
||||
response.define_singleton_method(:read_body) do |&callback|
|
||||
chunks.each(&callback)
|
||||
end
|
||||
http = Object.new
|
||||
http.define_singleton_method(:use_ssl=) { |_value| }
|
||||
http.define_singleton_method(:open_timeout=) { |_value| }
|
||||
http.define_singleton_method(:read_timeout=) { |_value| }
|
||||
http.define_singleton_method(:request) do |_request, &callback|
|
||||
callback.call(response)
|
||||
end
|
||||
http.define_singleton_method(:started?) { false }
|
||||
|
||||
subscribed_calls = 0
|
||||
event_types = []
|
||||
Net::HTTP.stub(:new, ->(_host, _port) { http }) do
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 1,
|
||||
first_event_timeout: 1,
|
||||
on_subscribed: -> {
|
||||
subscribed_calls += 1
|
||||
true
|
||||
}
|
||||
) { |event| event_types << event.fetch(:type) }
|
||||
end
|
||||
|
||||
assert_equal 1, subscribed_calls
|
||||
assert_equal [ "server.connected", "session.status" ], event_types
|
||||
end
|
||||
|
||||
def test_stream_events_preserves_question_and_permission_wait_state
|
||||
events = [
|
||||
{
|
||||
type: "question.asked",
|
||||
properties: { id: "que_1", sessionID: SESSION_ID, questions: [] }
|
||||
},
|
||||
{
|
||||
type: "question.replied",
|
||||
properties: { requestID: "que_1", sessionID: SESSION_ID, answers: [ [ "yes" ] ] }
|
||||
},
|
||||
{
|
||||
type: "permission.asked",
|
||||
properties: { id: "per_1", sessionID: SESSION_ID, permission: "bash" }
|
||||
},
|
||||
{
|
||||
type: "permission.replied",
|
||||
properties: { requestID: "per_1", sessionID: SESSION_ID, reply: "once" }
|
||||
},
|
||||
{
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
]
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(
|
||||
status: 200,
|
||||
body: events.map { |event| "data: #{event.to_json}\n\n" }.join,
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
)
|
||||
|
||||
reply = Opencode::Reply.new
|
||||
wait_states = []
|
||||
@client.stream_events(session_id: SESSION_ID, reply: reply) do |event|
|
||||
reply.apply(event)
|
||||
wait_states << reply.prompt_blocked?
|
||||
end
|
||||
|
||||
assert_equal [ true, false, true, false, false ], wait_states
|
||||
end
|
||||
|
||||
def test_prompt_wait_does_not_suspend_timeout_after_disconnect
|
||||
question = {
|
||||
type: "question.asked",
|
||||
properties: { id: "que_1", sessionID: SESSION_ID, questions: [] }
|
||||
}
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(
|
||||
status: 200,
|
||||
body: "data: #{question.to_json}\n\n",
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
).then.to_raise(Errno::ECONNREFUSED)
|
||||
|
||||
reply = Opencode::Reply.new
|
||||
assert_raises(Opencode::TimeoutError) do
|
||||
Timeout.timeout(0.5) do
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 0.01,
|
||||
first_event_timeout: 1,
|
||||
reply: reply
|
||||
) { |event| reply.apply(event) }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def test_connected_prompt_wait_suspends_timeout_while_events_keep_arriving
|
||||
question = {
|
||||
type: "question.asked",
|
||||
properties: { id: "que_1", sessionID: SESSION_ID, questions: [] }
|
||||
}
|
||||
replied = {
|
||||
type: "question.replied",
|
||||
properties: { requestID: "que_1", sessionID: SESSION_ID, answers: [ [ "yes" ] ] }
|
||||
}
|
||||
idle = {
|
||||
type: "session.status",
|
||||
properties: { sessionID: SESSION_ID, status: { type: "idle" } }
|
||||
}
|
||||
|
||||
response = Net::HTTPOK.new("1.1", "200", "OK")
|
||||
response.define_singleton_method(:read_body) do |&callback|
|
||||
callback.call("data: #{question.to_json}\n\n")
|
||||
sleep 0.02
|
||||
callback.call("data: #{replied.to_json}\n\n")
|
||||
callback.call("data: #{idle.to_json}\n\n")
|
||||
end
|
||||
http = Object.new
|
||||
http.define_singleton_method(:use_ssl=) { |_value| }
|
||||
http.define_singleton_method(:open_timeout=) { |_value| }
|
||||
http.define_singleton_method(:read_timeout=) { |_value| }
|
||||
http.define_singleton_method(:request) { |_request, &callback| callback.call(response) }
|
||||
http.define_singleton_method(:started?) { false }
|
||||
|
||||
reply = Opencode::Reply.new
|
||||
Net::HTTP.stub(:new, ->(_host, _port) { http }) do
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 0.01,
|
||||
first_event_timeout: 1,
|
||||
reply: reply
|
||||
) { |event| reply.apply(event) }
|
||||
end
|
||||
end
|
||||
|
||||
def test_stream_block_is_optional
|
||||
stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_return(status: 204, body: "")
|
||||
|
||||
sse = [
|
||||
CONNECTED_EVENT,
|
||||
{ type: "message.part.delta",
|
||||
properties: { sessionID: SESSION_ID, partID: "p1", field: "text", delta: "ack" } },
|
||||
{ type: "session.idle", properties: { sessionID: SESSION_ID } }
|
||||
@@ -133,6 +587,90 @@ class SmokeTest < Minitest::Test
|
||||
assert_equal "ack", reply.full_text
|
||||
end
|
||||
|
||||
def test_stream_merges_a_multi_assistant_tool_loop_without_duplicate_text
|
||||
stub_request(:post, "#{BASE}/session/#{SESSION_ID}/prompt_async")
|
||||
.to_return(status: 204, body: "")
|
||||
|
||||
skill_part = {
|
||||
id: "p_skill", sessionID: SESSION_ID, messageID: "m_skill",
|
||||
type: "tool", tool: "skill", callID: "call_skill",
|
||||
state: { status: "completed", input: { name: "travelwolf-itinerary" }, output: "loaded" }
|
||||
}
|
||||
task_part = {
|
||||
id: "p_task", sessionID: SESSION_ID, messageID: "m_task",
|
||||
type: "tool", tool: "task", callID: "call_task",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { subagent_type: "itinerary-planner" },
|
||||
output: "{\"days\":[]}",
|
||||
metadata: { sessionId: "ses_child" }
|
||||
}
|
||||
}
|
||||
sse = [
|
||||
CONNECTED_EVENT,
|
||||
{
|
||||
type: "todo.updated",
|
||||
properties: {
|
||||
sessionID: SESSION_ID,
|
||||
todos: [ { content: "Plan", status: "in-progress", priority: "high" } ]
|
||||
}
|
||||
},
|
||||
{ type: "message.part.updated", properties: { sessionID: SESSION_ID, part: skill_part } },
|
||||
{ type: "message.part.updated", properties: { sessionID: SESSION_ID, part: task_part } },
|
||||
{ type: "message.part.delta",
|
||||
properties: { sessionID: SESSION_ID, partID: "p_text", field: "text", delta: "SUBAGENT_OK" } },
|
||||
{ type: "message.part.delta",
|
||||
properties: { sessionID: SESSION_ID, partID: "p_text_replay", field: "text", delta: "SUBAGENT_OK" } },
|
||||
{ type: "session.status", properties: { sessionID: SESSION_ID, status: { type: "idle" } } }
|
||||
].map { |event| "data: #{event.to_json}\n\n" }.join
|
||||
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(status: 200, body: sse,
|
||||
headers: { "Content-Type" => "text/event-stream" })
|
||||
|
||||
exchange = [
|
||||
{ info: { role: "user" }, parts: [ { type: "text", text: "previous" } ] },
|
||||
{ info: { role: "assistant" }, parts: [ { type: "text", text: "previous answer" } ] },
|
||||
{ info: { role: "user" }, parts: [ { type: "text", text: "plan" } ] },
|
||||
{ info: { role: "assistant" }, parts: [ skill_part ] },
|
||||
{ info: { role: "assistant" }, parts: [ task_part ] },
|
||||
{ info: { role: "assistant" }, parts: [ { type: "text", text: "SUBAGENT_OK" } ] }
|
||||
]
|
||||
stub_request(:get, "#{BASE}/session/#{SESSION_ID}/message")
|
||||
.to_return(status: 200, body: exchange.to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
reply = @client.stream(SESSION_ID, "plan", stream_timeout: 1)
|
||||
|
||||
assert_equal "SUBAGENT_OK", reply.full_text
|
||||
assert_equal %w[todowrite skill task], reply.tool_parts.map { |part| part.fetch("tool") }
|
||||
assert_equal(
|
||||
[ { "content" => "Plan", "status" => "in_progress", "priority" => "high" } ],
|
||||
reply.tool_parts.first.dig("input", "todos")
|
||||
)
|
||||
assert_equal "ses_child", reply.tool_parts.last.dig("metadata", "sessionId")
|
||||
end
|
||||
|
||||
def test_write_artifacts_work_in_a_standalone_client
|
||||
response = {
|
||||
parts: [
|
||||
{
|
||||
type: "tool",
|
||||
tool: "write",
|
||||
state: {
|
||||
status: "completed",
|
||||
input: { filePath: "/tmp/report.md", content: "# Report" }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
assert_equal(
|
||||
[ { filename: "report.md", content: "# Report", content_type: "text/markdown" } ],
|
||||
Opencode::ResponseParser.extract_artifact_files(response)
|
||||
)
|
||||
end
|
||||
|
||||
def test_connection_refused_raises_ConnectionError
|
||||
stub_request(:get, "http://opencode.dead/global/health")
|
||||
.to_raise(Errno::ECONNREFUSED)
|
||||
@@ -151,6 +689,85 @@ class SmokeTest < Minitest::Test
|
||||
end
|
||||
end
|
||||
|
||||
def test_plain_text_404_preserves_SessionNotFoundError
|
||||
stub_request(:get, "#{BASE}/session/missing/message")
|
||||
.to_return(status: 404, body: "not found", headers: { "Content-Type" => "text/plain" })
|
||||
|
||||
assert_raises(Opencode::SessionNotFoundError) do
|
||||
@client.get_messages("missing")
|
||||
end
|
||||
end
|
||||
|
||||
def test_non_404_client_errors_raise_BadRequestError
|
||||
stub_request(:get, "#{BASE}/session")
|
||||
.to_return(status: 401, body: { error: "unauthorized" }.to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
assert_raises(Opencode::BadRequestError) { @client.list_sessions }
|
||||
end
|
||||
|
||||
def test_plain_text_client_errors_raise_BadRequestError
|
||||
stub_request(:get, "#{BASE}/session")
|
||||
.to_return(status: 401, body: "unauthorized", headers: { "Content-Type" => "text/plain" })
|
||||
|
||||
assert_raises(Opencode::BadRequestError) { @client.list_sessions }
|
||||
end
|
||||
|
||||
def test_non_object_json_client_errors_raise_BadRequestError
|
||||
[ '"unauthorized"', "[]", "null" ].each do |body|
|
||||
stub_request(:get, "#{BASE}/session")
|
||||
.to_return(status: 401, body: body, headers: { "Content-Type" => "application/json" })
|
||||
|
||||
assert_raises(Opencode::BadRequestError) { @client.list_sessions }
|
||||
end
|
||||
end
|
||||
|
||||
def test_list_questions_uses_the_public_error_hierarchy
|
||||
stub_request(:get, "#{BASE}/question")
|
||||
.to_return(status: 401, body: { error: "unauthorized" }.to_json,
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
assert_raises(Opencode::BadRequestError) { @client.list_questions }
|
||||
end
|
||||
|
||||
def test_stream_retries_socket_errors_until_its_timeout
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_raise(SocketError.new("name resolution failed"))
|
||||
|
||||
assert_raises(Opencode::StaleSessionError) do
|
||||
@client.stream_events(
|
||||
session_id: SESSION_ID,
|
||||
timeout: 1,
|
||||
first_event_timeout: 0.01
|
||||
) { }
|
||||
end
|
||||
end
|
||||
|
||||
def test_stream_does_not_swallow_socket_errors_from_the_caller_block
|
||||
event = {
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: SESSION_ID,
|
||||
part: { id: "part_1", type: "text", text: "hello" }
|
||||
}
|
||||
}
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/event(\?.*)?\z})
|
||||
.to_return(
|
||||
status: 200,
|
||||
body: "data: #{event.to_json}\n\n",
|
||||
headers: { "Content-Type" => "text/event-stream" }
|
||||
)
|
||||
|
||||
error = assert_raises(SocketError) do
|
||||
Timeout.timeout(0.5) do
|
||||
@client.stream_events(session_id: SESSION_ID, timeout: 1, first_event_timeout: 1) do
|
||||
raise SocketError, "caller lookup failed"
|
||||
end
|
||||
end
|
||||
end
|
||||
assert_equal "caller lookup failed", error.message
|
||||
end
|
||||
|
||||
def test_instrumentation_adapter_receives_request_events
|
||||
events = []
|
||||
Opencode::Instrumentation.adapter = ->(name, payload, &block) {
|
||||
@@ -167,6 +784,47 @@ class SmokeTest < Minitest::Test
|
||||
"instrumentation adapter must receive opencode.request events"
|
||||
end
|
||||
|
||||
def test_instrumentation_does_not_expose_scoped_query_values
|
||||
events = []
|
||||
Opencode::Instrumentation.adapter = ->(name, payload, &block) {
|
||||
events << [ name, payload ]
|
||||
block.call
|
||||
}
|
||||
client = Opencode::Client.new(
|
||||
base_url: "#{BASE}?token=base-secret",
|
||||
directory: "/private/workspace",
|
||||
workspace: "workspace-secret"
|
||||
)
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/session\?.*})
|
||||
.to_return(status: 200, body: "[]",
|
||||
headers: { "Content-Type" => "application/json" })
|
||||
|
||||
client.list_sessions
|
||||
|
||||
payload = events.find { |name, _| name == "opencode.request" }.last
|
||||
assert_equal "/session", payload.fetch(:path)
|
||||
end
|
||||
|
||||
def test_list_questions_instrumentation_does_not_expose_scoped_query_values
|
||||
events = []
|
||||
Opencode::Instrumentation.adapter = ->(name, payload, &block) {
|
||||
events << [ name, payload ]
|
||||
block.call
|
||||
}
|
||||
client = Opencode::Client.new(
|
||||
base_url: "#{BASE}?token=base-secret",
|
||||
directory: "/private/workspace",
|
||||
workspace: "workspace-secret"
|
||||
)
|
||||
stub_request(:get, %r{#{Regexp.escape(BASE)}/question\?.*})
|
||||
.to_return(status: 200, body: "[]", headers: { "Content-Type" => "application/json" })
|
||||
|
||||
client.list_questions
|
||||
|
||||
payload = events.find { |name, _| name == "opencode.request" }.last
|
||||
assert_equal "/question", payload.fetch(:path)
|
||||
end
|
||||
|
||||
def test_Reply_distill_returns_typed_Result
|
||||
parts = [
|
||||
{ "type" => "text", "content" => "hi" },
|
||||
|
||||
26
test/readme_contract_test.rb
Normal file
26
test/readme_contract_test.rb
Normal file
@@ -0,0 +1,26 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "test_helper"
|
||||
|
||||
class ReadmeContractTest < Minitest::Test
|
||||
README = File.read(File.expand_path("../README.md", __dir__))
|
||||
|
||||
def test_server_compatibility_points_to_exact_certification_evidence
|
||||
assert_includes README, "https://github.com/ajaynomics/opencode-compat"
|
||||
assert_includes README, "manifests/image-matrix.json"
|
||||
assert_includes README, "manifests/runtime-tuples.json"
|
||||
refute_match(/OpenCode server\s*(?:>=|≥)\s*\d/, README)
|
||||
end
|
||||
|
||||
def test_release_guidance_does_not_claim_trusted_publishing_is_configured
|
||||
assert_includes README, "`0.0.1.alpha8` package contained unrepaired source"
|
||||
assert_includes README, "was yanked"
|
||||
assert_includes README, "registration is not confirmed for alpha9"
|
||||
assert_includes README, "does not currently guarantee publication"
|
||||
end
|
||||
|
||||
def test_compatibility_documents_every_runtime_dependency
|
||||
assert_includes README, "`activesupport (>= 6.1, < 9.0)`"
|
||||
assert_includes README, "`marcel (~> 1.0)`"
|
||||
end
|
||||
end
|
||||
74
test/release_workflow_test.rb
Normal file
74
test/release_workflow_test.rb
Normal file
@@ -0,0 +1,74 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "minitest/autorun"
|
||||
require "yaml"
|
||||
|
||||
class ReleaseWorkflowTest < Minitest::Test
|
||||
ROOT = File.expand_path("..", __dir__)
|
||||
WORKFLOW_PATH = File.join(ROOT, ".github", "workflows", "release.yml")
|
||||
SETUP_RUBY_ACTION = "ruby/setup-ruby@003a5c4d8d6321bd302e38f6f0ec593f77f06600"
|
||||
RELEASE_GEM_ACTION = "rubygems/release-gem@052cc82692552de3ef2b81fd670e41d13cba8092"
|
||||
|
||||
def workflow
|
||||
@workflow ||= YAML.safe_load(File.read(WORKFLOW_PATH), aliases: false)
|
||||
end
|
||||
|
||||
def push_job
|
||||
workflow.fetch("jobs").fetch("push")
|
||||
end
|
||||
|
||||
def verify_job
|
||||
workflow.fetch("jobs").fetch("verify")
|
||||
end
|
||||
|
||||
def test_release_job_is_inert_on_non_github_runners
|
||||
assert_equal "${{ github.server_url == 'https://github.com' }}", push_job.fetch("if")
|
||||
end
|
||||
|
||||
def test_release_job_keeps_the_trusted_publisher_boundary
|
||||
assert_equal "release", push_job.fetch("environment")
|
||||
assert_equal(
|
||||
{ "contents" => "write", "id-token" => "write" },
|
||||
push_job.fetch("permissions")
|
||||
)
|
||||
|
||||
steps = push_job.fetch("steps")
|
||||
setup_ruby = steps.find { |step| step["uses"] == SETUP_RUBY_ACTION }
|
||||
|
||||
assert_equal "4.0", setup_ruby.dig("with", "ruby-version")
|
||||
assert_equal true, setup_ruby.dig("with", "bundler-cache")
|
||||
assert_equal 1, steps.count { |step| step["uses"] == RELEASE_GEM_ACTION }
|
||||
assert steps.filter_map { |step| step["uses"] }.all? { |uses| uses.match?(/@[0-9a-f]{40}\z/) }
|
||||
refute steps.any? { |step| step.key?("run") }
|
||||
end
|
||||
|
||||
def test_release_tag_must_match_the_gem_version_before_publish
|
||||
preflight = verify_job.fetch("steps").find { |step| step["name"] == "Verify tag matches gem version" }
|
||||
|
||||
refute_nil preflight
|
||||
assert_equal "${{ github.ref_name }}", preflight.dig("env", "RELEASE_TAG")
|
||||
assert_includes preflight.fetch("run"), "unless Opencode::VERSION == expected"
|
||||
end
|
||||
|
||||
def test_verification_job_has_read_only_credentials
|
||||
assert_equal({ "contents" => "read" }, verify_job.fetch("permissions"))
|
||||
|
||||
checkout = verify_job.fetch("steps").find { |step| step.fetch("uses", "").start_with?("actions/checkout@") }
|
||||
assert_equal false, checkout.dig("with", "persist-credentials")
|
||||
end
|
||||
|
||||
def test_release_verifies_the_supported_matrix_and_installed_gem_before_publish
|
||||
assert_equal %w[3.2 3.3 3.4 4.0], verify_job.dig("strategy", "matrix", "ruby")
|
||||
assert_equal "verify", push_job.fetch("needs")
|
||||
|
||||
commands = verify_job.fetch("steps").filter_map { |step| step["run"] }.join("\n")
|
||||
assert_includes commands, "bundle exec rake test"
|
||||
assert_includes commands, "gem build opencode-ruby.gemspec"
|
||||
assert_includes commands, "bundle exec ruby -e"
|
||||
assert_includes commands, 'GEM_HOME="${RUNNER_TEMP}/opencode-ruby-${{ matrix.ruby }}"'
|
||||
assert_includes commands, 'gem_file="opencode-ruby-$(ruby -Ilib -ropencode/version'
|
||||
assert_includes commands, 'gem install --local "$gem_file" --no-document'
|
||||
assert_includes commands, "Gem.loaded_specs.fetch(\"opencode-ruby\").full_gem_path"
|
||||
assert_includes commands, "ruby -ropencode-ruby"
|
||||
end
|
||||
end
|
||||
67
test/workflow_contract_test.rb
Normal file
67
test/workflow_contract_test.rb
Normal file
@@ -0,0 +1,67 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require "minitest/autorun"
|
||||
require "yaml"
|
||||
|
||||
class WorkflowContractTest < Minitest::Test
|
||||
ROOT = File.expand_path("..", __dir__)
|
||||
WORKFLOW_DIRECTORY = File.join(ROOT, ".github", "workflows")
|
||||
TEST_WORKFLOW_PATH = File.join(WORKFLOW_DIRECTORY, "test.yml")
|
||||
ACTION_PINS = {
|
||||
"actions/checkout" => "9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0",
|
||||
"ruby/setup-ruby" => "003a5c4d8d6321bd302e38f6f0ec593f77f06600",
|
||||
"rubygems/release-gem" => "052cc82692552de3ef2b81fd670e41d13cba8092"
|
||||
}.freeze
|
||||
|
||||
def test_matrix_covers_every_supported_ruby
|
||||
workflow = YAML.safe_load(File.read(TEST_WORKFLOW_PATH), aliases: false)
|
||||
versions = workflow.dig("jobs", "test", "strategy", "matrix", "ruby")
|
||||
|
||||
assert_equal %w[3.2 3.3 3.4 4.0], versions
|
||||
end
|
||||
|
||||
def test_every_third_party_action_uses_its_reviewed_commit
|
||||
action_uses = Dir[File.join(WORKFLOW_DIRECTORY, "*.{yml,yaml}")].sort.flat_map do |path|
|
||||
workflow = YAML.safe_load(File.read(path), aliases: false)
|
||||
|
||||
workflow_uses(workflow)
|
||||
end
|
||||
|
||||
assert_equal 7, action_uses.length
|
||||
action_uses.each do |action_use|
|
||||
action, separator, revision = action_use.rpartition("@")
|
||||
|
||||
assert_equal "@", separator
|
||||
assert_equal ACTION_PINS.fetch(action), revision
|
||||
assert_match(/\A[0-9a-f]{40}\z/, revision)
|
||||
end
|
||||
end
|
||||
|
||||
def test_action_discovery_only_reads_workflow_action_locations
|
||||
workflow = YAML.safe_load(<<~YAML, aliases: false)
|
||||
jobs:
|
||||
reusable:
|
||||
uses: "owner/workflow@revision"
|
||||
with:
|
||||
uses: ordinary-job-input
|
||||
test:
|
||||
steps:
|
||||
- uses: "owner/action@revision"
|
||||
with:
|
||||
uses: ordinary-step-input
|
||||
YAML
|
||||
|
||||
assert_equal %w[owner/workflow@revision owner/action@revision], workflow_uses(workflow)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def workflow_uses(node)
|
||||
node.fetch("jobs").values.flat_map do |job|
|
||||
action_uses = job.key?("uses") ? [job.fetch("uses")] : []
|
||||
step_uses = job.fetch("steps", []).filter_map { |step| step["uses"] }
|
||||
|
||||
action_uses.concat(step_uses)
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user