Initial opencode-ruby v0.0.1.alpha1 — hand-rolled HTTP+SSE client for OpenCode

Headline API:

  reply = client.stream(session_id, "Explain monads") do |part|
    print part["content"] if part["type"] == "text"
  end
  reply.full_text   # final accumulated text

Sources ported from ajaynomics/ajent-rails lib/opencode/client/ after
the Phase-1+2 tier carve + Phase-2.5 boundary cleanup (see ajent-rails
PRs #840 and #843). Rails-runtime coupling stripped:

  - Defaults read from ENV[OPENCODE_BASE_URL/SERVER_PASSWORD/TIMEOUT]
    instead of Rails.application.config.x.opencode_blackline.*
  - EventTraceable.timed_event(...) calls swapped for
    Opencode::Instrumentation.instrument(...) — pluggable adapter
    (default no-op) that callers wire to ActiveSupport::Notifications,
    OpenTelemetry, stdout, etc.

Runtime dependency: activesupport (>= 6.1, < 9.0) for the small
core_ext surface (blank?/present?/presence/truncate/duplicable?/
megabytes). ActiveSupport is NOT Rails — it's a standalone helpers
gem that most Ruby apps already have transitively.

What's in the gem:

  Opencode::Client          HTTP + SSE client; #stream block-form API
  Opencode::Reply           SSE-event accumulator with observer protocol
  Opencode::Reply::Result   typed Struct value object
  Opencode::ReplyObserver   observer protocol module (no-op defaults)
  Opencode::Prompts         per-Reply pending question/permission registry
  Opencode::Tracer          callable that prefixes event names
  Opencode::Instrumentation pluggable adapter
  Opencode::ResponseParser  wire-format extractors
  Opencode::ToolPart        canonical tool-part hash shape
  Opencode::PartSource      wire-vs-stream-only discriminator
  Opencode::Todo            todo status canonicalization
  Opencode::Error (+ 7 subclasses)

What's out (per design D18 — wait for demand signal):

  - acts_as_opencode_session concern
  - ActiveRecord-backed session lifecycle
  - rails generators
  - opencode-rails as a separate gem

Instead, examples/conversation_recipe.rb ships as a ~140-line
plain-ActiveRecord blueprint demonstrating session lifecycle,
with_lock, update_columns mid-stream pattern, and CAS-safe finalize.

Tests: 12 runs, 25 assertions, 0 failures (smoke test against
WebMock-stubbed OpenCode endpoints — covers the postcard, error
model, Instrumentation, and Reply::Result shape).

Authored against ajent-rails commit 02954eeb (opencode-gem/phase-3-prep).
This commit is contained in:
2026-05-19 20:06:40 -07:00
parent a04330b78d
commit e3e7b69c7f
22 changed files with 2478 additions and 1 deletions

View File

@@ -0,0 +1,62 @@
# frozen_string_literal: true
require "set"
module Opencode
# A Part's provenance — where it came from in the OpenCode wire model.
#
# Two source classes exist:
#
# - Wire parts: emitted by the OpenCode message-parts pipeline and
# echoed back by `GET /session/:id/message`. These are authoritative
# for finalization — when the final exchange poll lands, wire parts
# overwrite whatever streaming captured.
#
# - Stream-only parts: synthesized from bus events that OpenCode does
# NOT persist as message parts. The host's Opencode::Reply
# materializes them so per-product ReplyStream observers can render
# them through the same tool partials as real tool parts, and
# Opencode::Turn preserves them across exchange-finalization so the
# final assistant message keeps what the user watched live.
#
# `todo.updated` is the first stream-only source (OpenCode emits the
# full todo list on a bus event but never records it as a message part).
# Future sources land here too: add the constant, add it to STREAM_ONLY,
# both `Reply#append_part` callers and `Turn#stream_only_part?` keep
# working with no further edits.
#
# This module exists because the previous shape coupled Reply and Turn
# through a magic-string comparison of `metadata.source ==
# Opencode::Reply::TODO_STREAM_SOURCE`. Two classes carrying the same
# discriminator string is a "next time someone adds a source they'll
# only update one place" bug waiting to happen. The source-of-truth
# now lives here; both consumers go through `stream_only?(part)`.
module PartSource
TODO_UPDATED = "todo.updated"
STREAM_ONLY = Set[TODO_UPDATED].freeze
module_function
# True iff the part's metadata.source is one of the stream-only
# sources. Tolerates non-Hash input (returns false) so callers don't
# have to guard before asking.
def stream_only?(part)
return false unless part.is_a?(Hash)
STREAM_ONLY.include?(part.dig("metadata", "source"))
end
# Stamps `source:` into part_hash's metadata. Raises ArgumentError on
# an unknown source so typos surface at write time, not at the next
# `stream_only?` check (which would silently return false).
# Mutates and returns the input hash for chaining.
def stamp(part_hash, source:)
raise ArgumentError, "unknown stream-only source #{source.inspect}; " \
"register it in Opencode::PartSource::STREAM_ONLY first" unless STREAM_ONLY.include?(source)
part_hash["metadata"] ||= {}
part_hash["metadata"]["source"] = source
part_hash
end
end
end