silas 0.2.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/README.md +44 -0
  4. data/app/controllers/concerns/silas/api/serialization.rb +63 -0
  5. data/app/controllers/silas/api/base_controller.rb +24 -0
  6. data/app/controllers/silas/api/v1/approvals_controller.rb +35 -0
  7. data/app/controllers/silas/api/v1/sessions_controller.rb +39 -0
  8. data/app/controllers/silas/api/v1/streams_controller.rb +117 -0
  9. data/app/controllers/silas/api/v1/turns_controller.rb +32 -0
  10. data/app/controllers/silas/inbox/sessions_controller.rb +16 -3
  11. data/app/controllers/silas/inbox/turns_controller.rb +19 -0
  12. data/app/helpers/silas/inbox/trace_helper.rb +5 -0
  13. data/app/models/silas/session.rb +6 -0
  14. data/app/models/silas/turn.rb +9 -0
  15. data/app/views/layouts/silas/inbox.html.erb +6 -0
  16. data/app/views/silas/inbox/sessions/index.html.erb +11 -3
  17. data/app/views/silas/inbox/steps/_step.html.erb +3 -0
  18. data/app/views/silas/inbox/turns/_header.html.erb +12 -1
  19. data/config/routes.rb +23 -1
  20. data/db/migrate/20260725000001_add_provider_to_silas_steps.rb +13 -0
  21. data/lib/generators/silas/install/install_generator.rb +1 -0
  22. data/lib/generators/silas/install/templates/agent.yml +10 -1
  23. data/lib/generators/silas/install/templates/initializer.rb +5 -4
  24. data/lib/silas/agent.rb +4 -0
  25. data/lib/silas/chat.rb +2 -0
  26. data/lib/silas/configuration.rb +30 -34
  27. data/lib/silas/doctor.rb +155 -0
  28. data/lib/silas/engines/ruby_llm.rb +13 -2
  29. data/lib/silas/eval/assertions.rb +18 -0
  30. data/lib/silas/eval/transcript.rb +1 -0
  31. data/lib/silas/inbox/cost.rb +37 -13
  32. data/lib/silas/message_builder.rb +9 -2
  33. data/lib/silas/named_agent.rb +1 -0
  34. data/lib/silas/registry.rb +18 -8
  35. data/lib/silas/step_runner.rb +12 -0
  36. data/lib/silas/version.rb +1 -1
  37. data/lib/silas.rb +1 -0
  38. data/lib/tasks/silas_doctor.rake +17 -0
  39. metadata +10 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1f804f46eccb34c27515be306e2697345f3be7e0ad3479aeafb05f3ca9e5e54b
4
- data.tar.gz: 63a99caaeebb60133423d0d73669eff7074232262743764ec0d9d7d38f7b2012
3
+ metadata.gz: 187a0730a1a84463f6207060d446c6960946513c0884d708fc0d16c011493a26
4
+ data.tar.gz: ed9a09b617c7dde80deaf6fe2c460e254cc96487b43eac52f56c6aa7dedecbaa
5
5
  SHA512:
6
- metadata.gz: bb45b5ca774d80cdd2c584851114204eb123dd714a94264a851699ea24955fa8eefba4b1897e1924a91a484f64c9746bc625e007652fdc8a71e096425e7a9882
7
- data.tar.gz: 707d7857de1f2fba1e4e9327e9c32f71e7282c4dd2cfe739cb6aea98904cc805634f0ce70fd4353c5d580ea9f521d79e9581621d8f9b321216e9e00c058ba3b8
6
+ metadata.gz: a38278a7020a9282b1ff9aaac7b18da60bd017a001bcc421c6e316d0033b1a4b468cd86c0d4bcdcd869940f7d9c4b953318e84dd626087bef4fee1ee8ea8b87c
7
+ data.tar.gz: 6f42e1a81bf935ebdbb39c678e46662ab85b9f45bd8293c0e83f4467e7db922e2102087ab62ea7eb8e8b1b3b1d323eba1a5772e997028b3e5838882bda9cfeb3
data/CHANGELOG.md CHANGED
@@ -1,6 +1,66 @@
1
1
  # Changelog
2
2
 
3
- ## 0.2.0 (unreleased)
3
+ ## 0.3.0
4
+
5
+ - **`bin/rails silas:doctor`** — every known first-run failure mode as one
6
+ command: provider key, queue adapter (async = red), model resolution with
7
+ prices, migrations, tool validation, the rescuer recurring entry, the cable
8
+ adapter for live streaming (async cable can't carry worker deltas), and
9
+ whether the deny-by-default inbox/API auth has been wired. Exits non-zero
10
+ on failures, so it slots into CI.
11
+ - **Hard-removed the 0.2 `:agent_sdk` config shims** — `config.auth` and
12
+ `config.agent_sdk_*` now raise `NoMethodError` (they were warning no-ops
13
+ for the 0.2 cycle). `config.engine = :agent_sdk` still raises the
14
+ explanatory `BootGuardError`. Workflows now use `actions/checkout@v5`
15
+ (Node 20 deprecation).
16
+ - **Inbox at scale + the promised top-up card.** Budget-parked turns now
17
+ render a **"Budget reached — raise & resume"** card (the UI the 0.1.5
18
+ changelog promised): one field, one click, `raise_budget!`, completed work
19
+ replays from rows. The session list pages by keyset (`?before=<id>`, 50 per
20
+ page — the old hard `limit(100)` made session 101 unreachable forever), and
21
+ the index renders in **2 queries** instead of ~4 per card.
22
+ - **Cost accounting prices itself from RubyLLM's model registry** (1,100+
23
+ models, refreshed upstream from models.dev) instead of a five-entry
24
+ hand-maintained map. Steps stamp the **provider** RubyLLM resolves at
25
+ persist time, and lookups use the two-arg `find(model, provider)` — 85/1081
26
+ registry ids exist under multiple providers at different prices, so the
27
+ bare lookup could silently price the wrong one. `config.model_prices` is
28
+ now an **override map** (default `{}`) for fine-tunes, custom deployments,
29
+ and models newer than the installed registry; unknown models stay
30
+ `unpriced`, never a lying $0.00. Dropped the write-only
31
+ `silas_turns.cost_microcents` column (declared since 0.1.0, never
32
+ populated). Default model is now `claude-sonnet-4-5` — in every supported
33
+ registry, unlike `claude-sonnet-5` (absent from ruby_llm 1.16's shipped
34
+ registry, which would have broken first runs), and never the priciest
35
+ model. New migration: `bin/rails silas:install:migrations db:migrate`.
36
+ - **Structured final answers.** Declare a JSON schema under `final_answer:` in
37
+ agent.yml and the turn's answer comes back as a parsed Hash —
38
+ `Turn#answer_data` (alongside `answer_text` for prose agents), in the API
39
+ (`answer_data` on turns, `structured` on steps), the inbox trace, the REPL,
40
+ and a new `assert_answer_data` eval assertion. Implemented on RubyLLM's
41
+ `with_schema` (each provider's native structured-output dialect). The schema
42
+ is model-visible state: it folds into the definitions digest **only when
43
+ present** — schema-less agents keep a byte-identical digest, so turns parked
44
+ across the upgrade never trip `NondeterminismError` (pinned by spec); a
45
+ mid-turn schema change fails loudly by design. Structured answers replay
46
+ into later turns' history as their JSON text (deterministic).
47
+
48
+ - **A public HTTP + SSE session API** at `/silas/api/v1` — sessions
49
+ (create/show, `?trace=1` for the full transcript), turns (create — **409**
50
+ while one is active — and cancel), and approvals (list / approve / decline,
51
+ the exact same `approve!`/`decline!` as every other surface, stamped with
52
+ `config.api_actor`). Deny-by-default via `config.api_auth`, the inbox's
53
+ contract. `GET .../sessions/:id/stream` is server-sent events at row
54
+ granularity (turn / completed-step / invocation changes) with
55
+ `Last-Event-ID` resume — at-least-once, epoch-ms watermark ids, `?poll=1`
56
+ for a curl-friendly backlog-and-close, self-closing after
57
+ `api_stream_max_duration` with a `timeout` reconnect event. The AR
58
+ connection is released between polls; per-token streaming remains the
59
+ Turbo/browser feature (deltas live in the worker process; the gem takes no
60
+ cross-process bus dependency). `Session` gains `parent_session` /
61
+ `child_sessions` associations, and session JSON carries the lineage.
62
+
63
+ ## 0.2.0
4
64
 
5
65
  - **Token streaming, end to end.** The engine seam's `&on_event` block — dead
6
66
  code since 0.1.0 — is live: the `:ruby_llm` engine streams the model
data/README.md CHANGED
@@ -33,6 +33,7 @@ app/agent/
33
33
  bundle add silas
34
34
  bin/rails generate silas:install
35
35
  bin/rails db:migrate
36
+ bin/rails silas:doctor # key · queue adapter · model · migrations · tools · rescuer · cable · auth
36
37
  ```
37
38
 
38
39
  ```ruby
@@ -209,6 +210,49 @@ zero risk to the durability contract. Custom sinks subscribe to the
209
210
  text: }`, where `text` is the accumulated string so far — filter by ids;
210
211
  notifications are process-global).
211
212
 
213
+ ## Structured answers
214
+
215
+ Give the turn's final answer a schema in agent.yml and read it back as a Hash:
216
+
217
+ ```yaml
218
+ final_answer:
219
+ type: object
220
+ properties:
221
+ verdict: { type: string }
222
+ amount_pence: { type: integer }
223
+ required: [verdict]
224
+ ```
225
+
226
+ `Turn#answer_data` returns the parsed payload (`answer_text` stays for prose
227
+ agents); the HTTP API carries it as `answer_data`, evals get
228
+ `assert_answer_data(key: :verdict, value: "approve")`. Rendered through
229
+ RubyLLM's `with_schema`, so each provider's native structured-output mode is
230
+ used. The schema is model-visible state — changing it mid-turn fails the turn
231
+ loudly rather than resuming into a different contract.
232
+
233
+ ## The HTTP API
234
+
235
+ Everything the operator surface can do, over JSON — mounted with the engine at
236
+ `/silas/api/v1`, **deny-by-default** like the inbox (wire `config.api_auth`;
237
+ `config.api_actor` names the identity recorded on approvals):
238
+
239
+ ```sh
240
+ curl -X POST .../silas/api/v1/sessions -d "input=Refund order 42, £12.50"
241
+ curl .../silas/api/v1/sessions/1?trace=1 # turns + steps + tool calls
242
+ curl .../silas/api/v1/sessions/1/approvals # what's parked
243
+ curl -X POST .../silas/api/v1/approvals/7/approve # the same approve! as the inbox
244
+ curl -X POST .../silas/api/v1/sessions/1/turns -d "input=Now email them" # 409 if busy
245
+ curl -X POST .../silas/api/v1/turns/9/cancel
246
+ curl -N .../silas/api/v1/sessions/1/stream # server-sent events
247
+ ```
248
+
249
+ The stream is SSE at **row granularity** — turn / completed-step / invocation
250
+ changes, at-least-once with `Last-Event-ID` resume (ids are epoch-ms
251
+ watermarks; `?poll=1` returns the backlog and closes, curl-friendly; streams
252
+ close themselves after `api_stream_max_duration` and clients reconnect).
253
+ Per-token streaming is deliberately the browser/Turbo feature — deltas live in
254
+ the worker process, and the gem requires no cross-process bus.
255
+
212
256
  ## The inbox
213
257
 
214
258
  Mount the engine (the generator does this) and a live inbox appears at
@@ -0,0 +1,63 @@
1
+ module Silas
2
+ module Api
3
+ # Minimal, dependency-free JSON shapes. Deliberately explicit allowlists —
4
+ # never as_json a whole row (instruction snapshots and internal columns
5
+ # don't belong on the wire).
6
+ module Serialization
7
+ def session_json(session, include_turns: true, trace: false)
8
+ base = {
9
+ id: session.id, agent_name: session.agent_name,
10
+ channel: session.channel, status: session.status,
11
+ parent_session_id: session.parent_session_id,
12
+ child_session_ids: session.child_sessions.ids,
13
+ cost: Silas::Inbox::Cost.for_session(session),
14
+ created_at: session.created_at, updated_at: session.updated_at
15
+ }
16
+ return base unless include_turns
17
+
18
+ base.merge(turns: session.turns.map { |t| turn_json(t, trace: trace) })
19
+ end
20
+
21
+ def turn_json(turn, trace: false)
22
+ base = {
23
+ id: turn.id, session_id: turn.session_id, index: turn.index,
24
+ status: turn.status, input: turn.input,
25
+ failure_reason: turn.failure_reason,
26
+ answer_text: (turn.answer_text if turn.completed?),
27
+ answer_data: (turn.answer_data if turn.completed?),
28
+ created_at: turn.created_at, updated_at: turn.updated_at
29
+ }
30
+ return base unless trace
31
+
32
+ base.merge(steps: turn.steps.map do |step|
33
+ step_json(step).merge(invocations: step.tool_invocations.map { |i| invocation_json(i) })
34
+ end)
35
+ end
36
+
37
+ def step_json(step)
38
+ {
39
+ id: step.id, turn_id: step.turn_id, index: step.index,
40
+ status: step.status, terminal: step.terminal,
41
+ model: step.model, provider: step.provider,
42
+ text: Array(step.response_blocks).select { |b| b["type"] == "text" }
43
+ .map { |b| b["text"] }.join.presence,
44
+ structured: Array(step.response_blocks).reverse
45
+ .find { |b| b["type"] == "structured" }&.dig("data"),
46
+ updated_at: step.updated_at
47
+ }
48
+ end
49
+
50
+ def invocation_json(invocation)
51
+ {
52
+ id: invocation.id, turn_id: invocation.turn_id,
53
+ tool_name: invocation.tool_name, status: invocation.status,
54
+ approval_state: invocation.approval_state,
55
+ arguments: invocation.arguments, result: invocation.result,
56
+ error: invocation.error, approved_by: invocation.approved_by,
57
+ decline_reason: invocation.decline_reason,
58
+ updated_at: invocation.updated_at
59
+ }
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,24 @@
1
+ module Silas
2
+ module Api
3
+ # JSON API base: ActionController::API (no CSRF, no layouts, no cookies),
4
+ # deny-by-default auth with the inbox's contract — the host lambda DENIES
5
+ # by rendering (or head-ing) and PASSES by not rendering.
6
+ class BaseController < ActionController::API
7
+ before_action :authenticate!
8
+
9
+ rescue_from ActiveRecord::RecordNotFound do
10
+ render json: { error: "not found" }, status: :not_found
11
+ end
12
+
13
+ private
14
+
15
+ def authenticate!
16
+ Silas.config.api_auth.call(self)
17
+ end
18
+
19
+ def current_actor
20
+ Silas.config.api_actor.call(self)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,35 @@
1
+ module Silas
2
+ module Api
3
+ module V1
4
+ # The headline feature over HTTP: list what's parked, approve or decline
5
+ # it — the exact same approve!/decline! as the inbox, Slack, and email.
6
+ class ApprovalsController < Silas::Api::BaseController
7
+ include Silas::Api::Serialization
8
+
9
+ # GET /silas/api/v1/sessions/:session_id/approvals
10
+ def index
11
+ session = Silas::Session.find(params[:session_id])
12
+ render json: { approvals: session.pending_approvals.order(:id).map { |i| invocation_json(i) } }
13
+ end
14
+
15
+ # POST /silas/api/v1/approvals/:id/approve
16
+ def approve
17
+ invocation = Silas::ToolInvocation.find(params[:id])
18
+ invocation.approve!(by: current_actor)
19
+ render json: invocation_json(invocation.reload)
20
+ rescue Silas::Error => e
21
+ render json: { error: e.message }, status: :conflict
22
+ end
23
+
24
+ # POST /silas/api/v1/approvals/:id/decline { reason: (optional) }
25
+ def decline
26
+ invocation = Silas::ToolInvocation.find(params[:id])
27
+ invocation.decline!(reason: params[:reason].presence || "declined via api", by: current_actor)
28
+ render json: invocation_json(invocation.reload)
29
+ rescue Silas::Error => e
30
+ render json: { error: e.message }, status: :conflict
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,39 @@
1
+ module Silas
2
+ module Api
3
+ module V1
4
+ class SessionsController < Silas::Api::BaseController
5
+ include Silas::Api::Serialization
6
+
7
+ # POST /silas/api/v1/sessions { input:, agent: (optional), metadata: (optional) }
8
+ # channel stays nil ("direct") — API consumers read state via GET/stream;
9
+ # a non-nil channel would enqueue pointless outbound delivery jobs.
10
+ def create
11
+ input = params[:input].to_s.strip
12
+ return render json: { error: "input is required" }, status: :unprocessable_entity if input.empty?
13
+
14
+ handle = params[:agent].present? ? Silas.agent(params[:agent]) : Silas.agent
15
+ session = handle.start(input: input, metadata: metadata_param)
16
+ render json: session_json(session.reload), status: :created
17
+ rescue Silas::TurnInProgressError => e
18
+ render json: { error: e.message }, status: :conflict
19
+ rescue Silas::Error => e
20
+ render json: { error: e.message }, status: :unprocessable_entity
21
+ end
22
+
23
+ # GET /silas/api/v1/sessions/:id — session + turns
24
+ # GET /silas/api/v1/sessions/:id?trace=1 — plus steps + invocations
25
+ def show
26
+ session = Silas::Session.includes(turns: { steps: :tool_invocations }).find(params[:id])
27
+ render json: session_json(session, trace: params[:trace].present?)
28
+ end
29
+
30
+ private
31
+
32
+ def metadata_param
33
+ raw = params[:metadata]
34
+ raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h : (raw.presence || {})
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,117 @@
1
+ require "json"
2
+
3
+ module Silas
4
+ module Api
5
+ module V1
6
+ # Server-sent events at ROW granularity: turn / completed-step /
7
+ # invocation changes polled from the durable rows — the same source of
8
+ # truth as everything else. Deliberately NOT per-token: deltas are
9
+ # emitted in the worker process and the gem requires no cross-process
10
+ # bus; per-token streaming is the Turbo/browser feature.
11
+ #
12
+ # Delivery is at-least-once with Last-Event-ID resume: event ids are
13
+ # epoch-millisecond watermarks, each poll re-reads a 1ms overlap, and
14
+ # clients dedup by (event type, id, status). `?poll=1` emits the backlog
15
+ # since Last-Event-ID and closes — curl-able, and how the request specs
16
+ # exercise the cursor without holding a live stream.
17
+ #
18
+ # Live actions run on their own thread and hold a Puma thread for the
19
+ # stream's lifetime — inherent to SSE. The AR connection is NOT held:
20
+ # each poll checks one out and returns it before sleeping, and the
21
+ # stream closes itself after api_stream_max_duration (clients reconnect
22
+ # with Last-Event-ID).
23
+ class StreamsController < Silas::Api::BaseController
24
+ include ActionController::Live
25
+ include Silas::Api::Serialization
26
+
27
+ HEARTBEAT_EVERY = 15 # seconds; comment-frames keep proxies alive
28
+
29
+ def show
30
+ session_id = with_connection { Silas::Session.find(params[:id]).id }
31
+
32
+ response.headers["Content-Type"] = "text/event-stream"
33
+ response.headers["Cache-Control"] = "no-cache"
34
+ response.headers["X-Accel-Buffering"] = "no" # nginx: never buffer SSE
35
+ # Whatever the router/auth checked out must not stay pinned for the
36
+ # stream's lifetime.
37
+ ActiveRecord::Base.connection_handler.clear_active_connections!
38
+
39
+ watermark = initial_watermark
40
+ deadline = clock + Silas.config.api_stream_max_duration
41
+ last_beat = clock
42
+
43
+ loop do
44
+ events = with_connection { collect_changes(session_id, watermark) }
45
+ events.each do |type, at, payload|
46
+ write_event(type, payload, watermark_ms(at))
47
+ watermark = at if at > watermark
48
+ end
49
+
50
+ break if params[:poll].present? # backlog served; close
51
+
52
+ if clock >= deadline
53
+ write_event("timeout", { reconnect: true }, watermark_ms(watermark))
54
+ break
55
+ end
56
+
57
+ if clock - last_beat >= HEARTBEAT_EVERY
58
+ response.stream.write(": hb\n\n")
59
+ last_beat = clock
60
+ end
61
+
62
+ sleep Silas.config.api_stream_poll_interval
63
+ end
64
+ rescue IOError, ActionController::Live::ClientDisconnected
65
+ # client went away — the normal end of an SSE stream
66
+ ensure
67
+ response.stream.close rescue nil
68
+ end
69
+
70
+ private
71
+
72
+ # Everything with updated_at at-or-after the watermark (1ms overlap —
73
+ # at-least-once beats a gap). Steps only when completed: their text is
74
+ # the payload, and incomplete steps have none.
75
+ def collect_changes(session_id, watermark)
76
+ overlap = watermark - 0.001
77
+ events = []
78
+
79
+ Silas::Turn.where(session_id: session_id).where(updated_at: overlap..)
80
+ .order(:updated_at, :id).each do |turn|
81
+ events << [ "turn", turn.updated_at, turn_json(turn) ]
82
+ end
83
+ Silas::Step.joins(:turn).where(silas_turns: { session_id: session_id })
84
+ .where(status: "completed").where(updated_at: overlap..)
85
+ .order(:updated_at, :id).each do |step|
86
+ events << [ "step", step.updated_at, step_json(step) ]
87
+ end
88
+ Silas::ToolInvocation.joins(:turn).where(silas_turns: { session_id: session_id })
89
+ .where(updated_at: overlap..)
90
+ .order(:updated_at, :id).each do |invocation|
91
+ events << [ "invocation", invocation.updated_at, invocation_json(invocation) ]
92
+ end
93
+
94
+ events.sort_by { |(_type, at, _payload)| at }
95
+ end
96
+
97
+ def write_event(type, payload, id_ms)
98
+ response.stream.write("id: #{id_ms}\nevent: #{type}\ndata: #{JSON.generate(payload)}\n\n")
99
+ end
100
+
101
+ # Last-Event-ID (header or param) in epoch ms; absent -> "from now"
102
+ # (GET /sessions/:id carries current state; the stream carries what
103
+ # changes next). Last-Event-ID: 0 replays the whole session.
104
+ def initial_watermark
105
+ raw = request.headers["Last-Event-ID"].presence || params[:last_event_id].presence
106
+ raw ? Time.zone.at(raw.to_i / 1000.0) : Time.zone.now
107
+ end
108
+
109
+ def watermark_ms(time) = (time.to_f * 1000).round
110
+
111
+ def with_connection(&) = ActiveRecord::Base.connection_pool.with_connection(&)
112
+
113
+ def clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,32 @@
1
+ module Silas
2
+ module Api
3
+ module V1
4
+ class TurnsController < Silas::Api::BaseController
5
+ include Silas::Api::Serialization
6
+
7
+ # POST /silas/api/v1/sessions/:session_id/turns { input: }
8
+ # 409 when a turn is already active — an API must surface it, not
9
+ # swallow it the way the webhook channels do.
10
+ def create
11
+ session = Silas::Session.find(params[:session_id])
12
+ input = params[:input].to_s.strip
13
+ return render json: { error: "input is required" }, status: :unprocessable_entity if input.empty?
14
+
15
+ turn = session.continue(input: input)
16
+ render json: turn_json(turn), status: :created
17
+ rescue Silas::TurnInProgressError => e
18
+ render json: { error: e.message }, status: :conflict
19
+ end
20
+
21
+ # POST /silas/api/v1/turns/:id/cancel
22
+ # Running turns are flagged (honored at the next step boundary);
23
+ # queued/parked turns cancel immediately — cancel: reflects which.
24
+ def cancel
25
+ turn = Silas::Turn.find(params[:id])
26
+ outcome = turn.cancel!(reason: "canceled via api by #{current_actor}")
27
+ render json: turn_json(turn.reload).merge(cancel: outcome)
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -3,18 +3,31 @@ module Silas
3
3
  class SessionsController < BaseController
4
4
  before_action :authenticate_write!, only: :create
5
5
 
6
+ PER_PAGE = 50
7
+
6
8
  def index
7
- @sessions = Silas::Session.order(created_at: :desc).limit(100)
8
- @sessions = @sessions.where(agent_name: params[:agent]) if params[:agent].present?
9
+ # Keyset pagination on id (?before=<id> pages older), newest first.
10
+ scope = Silas::Session.order(id: :desc)
11
+ scope = scope.where(agent_name: params[:agent]) if params[:agent].present?
9
12
  if params[:pending].present? # the "N awaiting approval" badge drills into this
10
13
  # Subquery, not joins+distinct: DISTINCT over silas_sessions.* trips
11
14
  # on the json metadata column (PG json has no equality operator).
12
- @sessions = @sessions.where(
15
+ scope = scope.where(
13
16
  id: Silas::Turn.joins(:tool_invocations)
14
17
  .where(silas_tool_invocations: { approval_state: "required" })
15
18
  .select(:session_id)
16
19
  )
17
20
  end
21
+ scope = scope.where(id: ...params[:before].to_i) if params[:before].present?
22
+
23
+ # One query for the rows + turns, one for the pending counts — the
24
+ # per-row active_turn/turns.last/counts pattern was ~4 queries a card.
25
+ @sessions = scope.limit(PER_PAGE).includes(:turns).to_a
26
+ @next_before = @sessions.last&.id if @sessions.size == PER_PAGE
27
+ @pending_counts = Silas::ToolInvocation.joins(:turn)
28
+ .where(approval_state: "required",
29
+ silas_turns: { session_id: @sessions.map(&:id) })
30
+ .group("silas_turns.session_id").count
18
31
  @agent_names = Silas::Session.distinct.pluck(:agent_name).sort
19
32
  @pending_total = Silas::ToolInvocation.where(approval_state: "required").count
20
33
  end
@@ -27,6 +27,25 @@ module Silas
27
27
  notice = outcome == :cancel_requested ? "Cancel requested — honored at the next step boundary." : "Turn canceled."
28
28
  redirect_to inbox_session_path(turn.session_id), notice: notice
29
29
  end
30
+
31
+ # Top up a budget-parked turn and resume it — the CHANGELOG promised
32
+ # this card in 0.1.5; completed steps replay from rows, same as approvals.
33
+ def raise_budget
34
+ turn = Silas::Turn.find(params[:id])
35
+ unless turn.budget_parked?
36
+ return redirect_to inbox_session_path(turn.session_id),
37
+ alert: "Turn ##{turn.index} is not budget-parked."
38
+ end
39
+
40
+ reason = turn.failure_reason.to_s
41
+ value = params[:value].to_s
42
+ numeric = reason == "max_cost" ? value.to_f : value.to_i
43
+
44
+ turn.raise_budget!(**{ reason.to_sym => numeric })
45
+ redirect_to inbox_session_path(turn.session_id), notice: "#{reason} raised — resuming."
46
+ rescue Silas::Error, ArgumentError => e
47
+ redirect_to inbox_session_path(turn.session_id), alert: e.message
48
+ end
30
49
  end
31
50
  end
32
51
  end
@@ -18,6 +18,11 @@ module Silas
18
18
  Array(step.response_blocks).select { |b| b["type"] == "text" }.map { |b| b["text"] }.join.presence
19
19
  end
20
20
 
21
+ # The final_answer payload, when the agent declared a schema.
22
+ def step_structured(step)
23
+ Array(step.response_blocks).reverse.find { |b| b["type"] == "structured" }&.dig("data")
24
+ end
25
+
21
26
  def pretty_args(hash)
22
27
  JSON.pretty_generate(hash || {})
23
28
  end
@@ -5,6 +5,12 @@ module Silas
5
5
  has_many :turns, -> { order(:index) }, class_name: "Silas::Turn", foreign_key: :session_id,
6
6
  inverse_of: :session, dependent: :destroy
7
7
 
8
+ # Delegations and handoffs stamp parent_session_id; without associations
9
+ # they surfaced as unexplained orphans.
10
+ belongs_to :parent_session, class_name: "Silas::Session", optional: true
11
+ has_many :child_sessions, class_name: "Silas::Session",
12
+ foreign_key: :parent_session_id, inverse_of: :parent_session
13
+
8
14
  validates :status, inclusion: { in: STATUSES }
9
15
  validates :agent_name, presence: true
10
16
 
@@ -84,6 +84,15 @@ module Silas
84
84
  Array(step.response_blocks).select { |b| b["type"] == "text" }.map { |b| b["text"] }.join
85
85
  end
86
86
 
87
+ # The structured payload when the agent declares a final_answer schema in
88
+ # agent.yml (nil otherwise) — the parsed Hash, not a string to re-parse.
89
+ def answer_data
90
+ step = steps.where(status: "completed").order(:index).last
91
+ return nil unless step
92
+
93
+ Array(step.response_blocks).reverse.find { |b| b["type"] == "structured" }&.dig("data")
94
+ end
95
+
87
96
  # Outbound: when a channel-bound turn reaches an answer, deliver it off-loop.
88
97
  after_update_commit :notify_channel_answer, if: :should_notify_answer?
89
98
 
@@ -92,6 +92,12 @@
92
92
  .agent-filter .chip { font-size: 12px; padding: 3px 10px; border: 1px solid #d9dce1;
93
93
  border-radius: 999px; text-decoration: none; color: inherit; }
94
94
  .agent-filter .chip-on { background: #16181d; color: #fff; border-color: #16181d; }
95
+ .pager { text-align: center; margin: 16px 0; }
96
+ .pager .chip { font-size: 13px; padding: 6px 14px; border: 1px solid var(--line);
97
+ border-radius: 999px; text-decoration: none; color: inherit; }
98
+ .topup-form { display: flex; gap: 8px; margin-top: 8px; }
99
+ .topup-input { flex: 1; border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px;
100
+ font: inherit; background: var(--panel); color: var(--ink); }
95
101
  </style>
96
102
  </head>
97
103
  <body>
@@ -37,15 +37,23 @@
37
37
  <%= link_to inbox_session_path(session), class: "card session-row" do %>
38
38
  <div class="row-top">
39
39
  <span class="name"><%= session.agent_name %></span>
40
- <% if (turn = session.active_turn || session.turns.last) %><%= status_pill(turn.status) %><% end %>
41
- <% pending = session.pending_approvals.count %>
40
+ <%# Loaded association no per-row queries. %>
41
+ <% if (turn = session.turns.detect(&:active?) || session.turns.last) %><%= status_pill(turn.status) %><% end %>
42
+ <% pending = @pending_counts.fetch(session.id, 0) %>
42
43
  <% if pending.positive? %><span class="badge"><%= pending %> to approve</span><% end %>
43
44
  </div>
44
45
  <div class="muted">
45
- <%= pluralize(session.turns.count, "turn") %> ·
46
+ <%= pluralize(session.turns.size, "turn") %> ·
46
47
  <%= session.channel.presence || "direct" %> ·
47
48
  <%= relative_time(session.updated_at) %>
48
49
  </div>
49
50
  <% end %>
50
51
  <% end %>
52
+ <% if @next_before %>
53
+ <div class="pager">
54
+ <%= link_to "Older sessions →",
55
+ inbox_sessions_path(before: @next_before, agent: params[:agent].presence, pending: params[:pending].presence),
56
+ class: "chip" %>
57
+ </div>
58
+ <% end %>
51
59
  <% end %>
@@ -7,6 +7,9 @@
7
7
  <% else %>
8
8
  <div class="step-text step-live" id="silas-step-<%= step.id %>-text"></div>
9
9
  <% end %>
10
+ <% if (data = step_structured(step)) %>
11
+ <pre class="args"><%= pretty_args(data) %></pre>
12
+ <% end %>
10
13
  <div id="silas-step-<%= step.id %>-tools">
11
14
  <%= render partial: "silas/inbox/invocations/invocation", collection: step.tool_invocations, as: :invocation %>
12
15
  </div>
@@ -9,6 +9,17 @@
9
9
  <span class="muted">cancel requested…</span>
10
10
  <% end %>
11
11
  </div>
12
- <% if turn.failure_reason.present? %>
12
+ <% if turn.budget_parked? %>
13
+ <div class="approval">
14
+ <h3>Budget reached — <%= turn.failure_reason %></h3>
15
+ <div class="muted">Parked at zero compute. Raise the limit and the turn resumes
16
+ by replaying completed work from rows — no re-calls, no re-effects.</div>
17
+ <%= form_with url: raise_budget_inbox_turn_path(turn), method: :post, class: "topup-form" do %>
18
+ <input name="value" type="number" step="any" min="0" required class="topup-input"
19
+ placeholder="<%= turn.failure_reason == "max_cost" ? "new limit in dollars, e.g. 2.50" : "new limit, e.g. 200000" %>">
20
+ <button class="btn approve">Raise &amp; resume</button>
21
+ <% end %>
22
+ </div>
23
+ <% elsif turn.failure_reason.present? %>
13
24
  <div class="muted">failed: <%= turn.failure_reason %></div>
14
25
  <% end %>