samagotchi 0.182.0 → 0.184.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 (197) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +107 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +22 -11
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +4 -2
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +14 -6
  12. data/docs/internals/bundles.md +26 -5
  13. data/docs/internals/engine.md +20 -9
  14. data/docs/internals/participants.md +1 -1
  15. data/docs/internals/prompt-caching.md +8 -1
  16. data/docs/internals/remote-sessions.md +40 -5
  17. data/docs/internals/web-frontend.md +96 -31
  18. data/docs/internals/web-push.md +11 -0
  19. data/docs/internals/working-set.md +239 -7
  20. data/docs/mcp-server.md +84 -0
  21. data/docs/memory.md +2 -1
  22. data/docs/plugins.md +309 -22
  23. data/docs/scheduling.md +14 -0
  24. data/docs/sessions.md +4 -4
  25. data/docs/sub-agent.md +9 -0
  26. data/docs/testing.md +3 -1
  27. data/docs/thin-clients.md +165 -0
  28. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  29. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  30. data/lib/samagotchi/bridge.rb +59 -68
  31. data/lib/samagotchi/bridge_client.rb +12 -4
  32. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  33. data/lib/samagotchi/bundle_command/check.rb +55 -20
  34. data/lib/samagotchi/bundle_command.rb +50 -21
  35. data/lib/samagotchi/bundle_manifest.rb +105 -4
  36. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  37. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  38. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  39. data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
  40. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  41. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  42. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  43. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  44. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  45. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  46. data/lib/samagotchi/bundles/system/self_map.md +7 -2
  47. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  48. data/lib/samagotchi/command_intake.rb +7 -0
  49. data/lib/samagotchi/commands/registry.rb +8 -3
  50. data/lib/samagotchi/continue_offer.rb +24 -15
  51. data/lib/samagotchi/engine/block_fix.rb +4 -4
  52. data/lib/samagotchi/engine/cards.rb +14 -5
  53. data/lib/samagotchi/engine/events.rb +10 -15
  54. data/lib/samagotchi/engine/models.rb +1 -1
  55. data/lib/samagotchi/engine/plugins.rb +3 -0
  56. data/lib/samagotchi/engine/recap.rb +1 -1
  57. data/lib/samagotchi/engine/session.rb +14 -6
  58. data/lib/samagotchi/engine/side_requests.rb +1 -1
  59. data/lib/samagotchi/engine/sign_in.rb +142 -0
  60. data/lib/samagotchi/engine/turn_end.rb +3 -3
  61. data/lib/samagotchi/engine/turn_helpers.rb +4 -3
  62. data/lib/samagotchi/engine.rb +43 -27
  63. data/lib/samagotchi/engine_snapshots.rb +1 -1
  64. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  65. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  66. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  67. data/lib/samagotchi/hold_stop.rb +4 -4
  68. data/lib/samagotchi/idle_recap.rb +19 -11
  69. data/lib/samagotchi/idle_reminders.rb +7 -5
  70. data/lib/samagotchi/idle_scheduler.rb +7 -10
  71. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  72. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  73. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  74. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  75. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  76. data/lib/samagotchi/llm/http.rb +96 -5
  77. data/lib/samagotchi/mcp_command.rb +110 -0
  78. data/lib/samagotchi/mcp_server/http.rb +112 -0
  79. data/lib/samagotchi/mcp_server/protocol.rb +263 -0
  80. data/lib/samagotchi/mcp_server/stdio.rb +93 -0
  81. data/lib/samagotchi/mcp_server/text.rb +155 -0
  82. data/lib/samagotchi/mcp_server/tools.rb +246 -0
  83. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  84. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  85. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  86. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  87. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  88. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  89. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  90. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  91. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  92. data/lib/samagotchi/model_notes.rb +34 -12
  93. data/lib/samagotchi/plugin/api.rb +6 -1
  94. data/lib/samagotchi/plugin/card.rb +36 -11
  95. data/lib/samagotchi/plugin/context.rb +63 -6
  96. data/lib/samagotchi/plugin/http.rb +40 -15
  97. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  98. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  99. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  100. data/lib/samagotchi/plugin/loader.rb +18 -11
  101. data/lib/samagotchi/plugin/secrets.rb +266 -0
  102. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  103. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  104. data/lib/samagotchi/prompt_files.rb +11 -4
  105. data/lib/samagotchi/prompt_layout.rb +88 -0
  106. data/lib/samagotchi/prompt_part.rb +82 -20
  107. data/lib/samagotchi/queued_command.rb +28 -4
  108. data/lib/samagotchi/recap_setup.rb +13 -4
  109. data/lib/samagotchi/ref.rb +3 -2
  110. data/lib/samagotchi/relay_verifier.rb +8 -7
  111. data/lib/samagotchi/relay_watcher.rb +4 -4
  112. data/lib/samagotchi/reply_wait.rb +6 -3
  113. data/lib/samagotchi/run_options.rb +2 -1
  114. data/lib/samagotchi/schedule_command.rb +18 -4
  115. data/lib/samagotchi/schedules.rb +40 -8
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +285 -0
  118. data/lib/samagotchi/session_access/contract.rb +5 -0
  119. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  120. data/lib/samagotchi/session_access/exchange.rb +176 -0
  121. data/lib/samagotchi/session_access/local.rb +34 -6
  122. data/lib/samagotchi/session_access/remote.rb +4 -1
  123. data/lib/samagotchi/session_command_catalog.rb +10 -0
  124. data/lib/samagotchi/session_commands.rb +17 -0
  125. data/lib/samagotchi/session_config.rb +4 -4
  126. data/lib/samagotchi/session_inbox.rb +15 -0
  127. data/lib/samagotchi/session_manager/delivery.rb +8 -4
  128. data/lib/samagotchi/session_observer.rb +27 -0
  129. data/lib/samagotchi/steer_cut.rb +4 -3
  130. data/lib/samagotchi/system_prompt.rb +196 -161
  131. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  132. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  133. data/lib/samagotchi/testing/boundary.rb +4 -0
  134. data/lib/samagotchi/testing/bundle.rb +48 -2
  135. data/lib/samagotchi/testing/fake_http.rb +60 -15
  136. data/lib/samagotchi/testing/host.rb +4 -1
  137. data/lib/samagotchi/testing/recorder.rb +45 -5
  138. data/lib/samagotchi/tools/memory.rb +11 -3
  139. data/lib/samagotchi/tools/tool_index.rb +14 -3
  140. data/lib/samagotchi/turn_stages/warmup.rb +2 -2
  141. data/lib/samagotchi/version.rb +1 -1
  142. data/lib/samagotchi/web/app.rb +9 -8
  143. data/lib/samagotchi/web/ask_routes.rb +362 -0
  144. data/lib/samagotchi/web/mcp_route.rb +91 -0
  145. data/lib/samagotchi/web/public/app.js +2 -3
  146. data/lib/samagotchi/web/public/block_frame.js +72 -11
  147. data/lib/samagotchi/web/public/block_host.js +44 -8
  148. data/lib/samagotchi/web/public/block_regions.js +126 -0
  149. data/lib/samagotchi/web/public/card.js +22 -9
  150. data/lib/samagotchi/web/public/card_actions.js +21 -0
  151. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  152. data/lib/samagotchi/web/public/card_registry.js +3 -2
  153. data/lib/samagotchi/web/public/data.js +15 -12
  154. data/lib/samagotchi/web/public/delete_sheet.js +231 -169
  155. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  156. data/lib/samagotchi/web/public/format.js +3 -0
  157. data/lib/samagotchi/web/public/index.html +52 -7
  158. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  159. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  160. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  161. data/lib/samagotchi/web/public/refs.js +5 -3
  162. data/lib/samagotchi/web/public/region_hit.js +144 -0
  163. data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
  164. data/lib/samagotchi/web/public/running_tasks.js +3 -17
  165. data/lib/samagotchi/web/public/session_actions.js +96 -100
  166. data/lib/samagotchi/web/public/working_set_view.js +167 -21
  167. data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
  168. data/lib/samagotchi/web/public/ws_peek.js +3 -1
  169. data/lib/samagotchi/web/public/ws_preview.css +30 -0
  170. data/lib/samagotchi/web/public/ws_reader.js +7 -3
  171. data/lib/samagotchi/web/public/ws_sections.js +37 -7
  172. data/lib/samagotchi/web/push/notifier.rb +33 -6
  173. data/lib/samagotchi/web/server.rb +1 -1
  174. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  175. data/lib/samagotchi/web/session_control.rb +31 -9
  176. data/lib/samagotchi/web/session_create.rb +2 -2
  177. data/lib/samagotchi/web/session_hub.rb +26 -4
  178. data/lib/samagotchi/web/working_set_routes.rb +93 -5
  179. data/lib/samagotchi/worker/child_side.rb +3 -2
  180. data/lib/samagotchi/worker/command_queue.rb +13 -13
  181. data/lib/samagotchi/worker/leave.rb +3 -3
  182. data/lib/samagotchi/worker/scratch.rb +6 -6
  183. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  184. data/lib/samagotchi/worker/startup.rb +3 -3
  185. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  186. data/lib/samagotchi/worker.rb +32 -21
  187. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  188. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  189. data/lib/samagotchi/worker_inbound.rb +12 -7
  190. data/lib/samagotchi/worker_link.rb +2 -2
  191. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  192. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  193. data/lib/samagotchi/working_set.rb +162 -90
  194. data/lib/samagotchi/working_set_locator.rb +221 -0
  195. data/lib/samagotchi/working_set_own_changes.rb +221 -0
  196. data/lib/samagotchi/working_set_part.rb +281 -0
  197. metadata +36 -1
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "uri"
3
4
  require_relative "../plugin/loader"
4
5
  require_relative "../plugin/tool_spec"
5
6
  require_relative "../hooks"
@@ -177,9 +178,10 @@ module Samagotchi
177
178
  # @api private (Bundle.load)
178
179
  def load!
179
180
  if (plugin = @manifest.plugin)
181
+ parts = part_paths
180
182
  @namespace = Plugin::Loader.fresh_namespace(@name)
181
183
  @api = Plugin::Loader.register_file(@name, File.join(@dir, plugin[:file]), @registries, settings: @settings,
182
- namespace: @namespace,
184
+ namespace: @namespace, parts: parts,
183
185
  api_class: RecordingApi) do |built|
184
186
  @plugin = built
185
187
  end
@@ -190,6 +192,18 @@ module Samagotchi
190
192
  raise
191
193
  end
192
194
 
195
+ # The manifest's plugin parts in the source, in load order.
196
+ # @raise [ArgumentError] one the manifest names that isn't there
197
+ def part_paths
198
+ @manifest.plugin_parts.keys.map do |part|
199
+ path = File.join(@dir, part)
200
+ raise ArgumentError, "#{@name}: #{BundleManifest.missing_part(part)}" unless File.file?(path)
201
+
202
+ path
203
+ end
204
+ end
205
+ private :part_paths
206
+
193
207
  # ── Firing ──────────────────────────────────────────────────────────
194
208
 
195
209
  # Fire hook +event+ through the registry, as chi's fire sites do: the
@@ -358,6 +372,29 @@ module Samagotchi
358
372
 
359
373
  def notices = @recorder.notices
360
374
  def cards = @recorder.cards
375
+ # What ctx.secrets holds now ({"name" => "value"}); seed it with
376
+ # bundle.set(secrets: {...}).
377
+ def secrets = @recorder.secrets.to_h
378
+
379
+ # Every ctx.sign_in flow, oldest first (Plugin::SignIn: #title,
380
+ # #address the block built, #redirect_uri, #card_id, #outcome). The kit
381
+ # opens no port.
382
+ def sign_ins = @recorder.sign_ins
383
+
384
+ # The newest sign-in's callback arrives with +params+ (the query the
385
+ # browser would bring: {"code" => "c1", "state" => "…"}). A state that
386
+ # isn't the address's is ignored, as chi ignores it.
387
+ # @return [Boolean] whether it settled the flow :done
388
+ def complete_sign_in(params)
389
+ newest_sign_in.offer(URI.encode_www_form(params.to_h { |key, value| [key.to_s, value.to_s] }))
390
+ end
391
+
392
+ # The newest sign-in ends as +outcome+ (:timed_out, :cancelled,
393
+ # :stopped) with no callback: its card is replaced as chi does.
394
+ def fail_sign_in(outcome = :timed_out)
395
+ newest_sign_in.end_as(outcome)
396
+ end
397
+
361
398
  def steers = @recorder.steers
362
399
  # Every stop_turn and stop_generation, in order (Stop#kind).
363
400
  def stops = @recorder.stops
@@ -398,8 +435,17 @@ module Samagotchi
398
435
  self
399
436
  end
400
437
 
401
- # Stop the plugin's services; leave the sandbox it entered.
438
+ def newest_sign_in
439
+ sign_ins.last or raise ArgumentError, "no ctx.sign_in was started"
440
+ end
441
+ private :newest_sign_in
442
+
443
+ # Stop the plugin's services and its waiting sign-ins; leave the
444
+ # sandbox it entered.
402
445
  def shutdown
446
+ # As a worker leaving does: a waiting sign-in ends :stopped (its
447
+ # waiting thread goes on).
448
+ sign_ins.each(&:stop)
403
449
  @registries&.services&.stop_all
404
450
  return unless @own_sandbox
405
451
 
@@ -17,12 +17,17 @@ module Samagotchi
17
17
  # bundle.http.stub(:get, %r{/health\z}, status: 503, body: "down")
18
18
  # bundle.http.stub(:post, "http://127.0.0.1:9000/classify") { |req| { json: { label: req.json["text"] } } }
19
19
  # bundle.http.stub(:get, "http://127.0.0.1:9000/x", error: :refused) # also :timeout
20
+ # bundle.http.stub(:post, "http://127.0.0.1:9000/mcp", events: [{ data: "{}", id: "1" }, "plain data"])
21
+ # bundle.http.stub(:get, "http://127.0.0.1:9000/big", chunks: ["hel", "lo"])
20
22
  # bundle.http.requests # what the plugin sent, in order
21
23
  # bundle.http.unmatched # what no stub answered
22
24
  #
23
25
  # A String matches the full URL exactly (query included), a Regexp is
24
26
  # matched against it; the method too. Later stubs win. A stub answers
25
- # every matching call: a sequence is a block that counts.
27
+ # every matching call: a sequence is a block that counts. Any stub
28
+ # answers both ctx.http.request and ctx.http.stream: +events:+ (served
29
+ # as text/event-stream) is the SSE text to a request, +body:+ / +json:+
30
+ # one chunk to a stream.
26
31
  class FakeHttp
27
32
  # One request the plugin made (headers as the plugin gave them).
28
33
  # `method` shadows Object#method on purpose: it is the plugin's word (request.method == "POST").
@@ -67,17 +72,23 @@ module Samagotchi
67
72
  # @param json [Object, nil] a JSON body (with its Content-Type)
68
73
  # @param error [Symbol, nil] :refused or :timeout: the request fails
69
74
  # with the HttpError the real transport raises
75
+ # @param events [Array<Hash, String>, nil] Server-Sent Events, each
76
+ # { data:, event: nil, id: nil } or a String (its data), served as
77
+ # text/event-stream
78
+ # @param chunks [Array<String>, nil] the body, in these pieces (a
79
+ # stream reads them one by one)
70
80
  # @yield [Request] to decide per request: returns a Hash with the same
71
- # keywords (status:, headers:, body:, json:, error:) or a
72
- # Plugin::Http::Response
81
+ # keywords (status:, headers:, body:, json:, events:, chunks:,
82
+ # error:) or a Plugin::Http::Response
73
83
  # @return [self]
74
- def stub(method, url, status: 200, headers: {}, body: nil, json: nil, error: nil, &block)
84
+ def stub(method, url, status: 200, headers: {}, body: nil, json: nil, events: nil, chunks: nil, error: nil, &block)
75
85
  verb = method.to_s.upcase
76
86
  raise ArgumentError, "unknown HTTP method #{method.inspect}" unless Plugin::Http::METHODS.include?(verb)
77
87
  raise ArgumentError, "the URL is a String or a Regexp" unless url.is_a?(String) || url.is_a?(Regexp)
78
88
  raise ArgumentError, "unknown error #{error.inspect} (#{ERRORS.keys.join(", ")})" if error && !ERRORS.key?(error)
79
89
 
80
- answer = block || { status: status, headers: headers, body: body, json: json, error: error }
90
+ answer = block || { status: status, headers: headers, body: body, json: json, events: events, chunks: chunks,
91
+ error: error }
81
92
  @mutex.synchronize { @stubs << Stub.new(verb: verb, matcher: url, answer: answer) }
82
93
  self
83
94
  end
@@ -93,6 +104,34 @@ module Samagotchi
93
104
  # the only cancel it checks.
94
105
  # @raise [UnstubbedRequest, Plugin::HttpError, Plugin::HttpCancelled]
95
106
  def call(method:, uri:, headers:, body:, timeout:, cancel:)
107
+ respond(method, uri, headers, body, cancel)
108
+ end
109
+
110
+ # The streamed half of the contract (Plugin::Http#stream): the block
111
+ # gets a Plugin::Http::Stream over the stub's chunks (its events, or
112
+ # its body as one chunk).
113
+ # @return [Object] the block's value
114
+ def stream(method:, uri:, headers:, body:, timeout:, cancel:)
115
+ response, chunks = respond(method, uri, headers, body, cancel, chunked: true)
116
+ yield Plugin::Http::Stream.new(status: response.status, headers: response.headers,
117
+ reader: ->(&on_chunk) { chunks.each { |chunk| on_chunk.call(chunk.b) } })
118
+ end
119
+
120
+ # An event as SSE text: its event: and id: lines, a data: line per line.
121
+ def self.sse_text(event)
122
+ event = { data: event } unless event.is_a?(Hash)
123
+ event = event.transform_keys(&:to_sym)
124
+ lines = []
125
+ lines << "event: #{event[:event]}" if event[:event]
126
+ lines << "id: #{event[:id]}" if event[:id]
127
+ event[:data].to_s.split("\n", -1).each { |line| lines << "data: #{line}" }
128
+ "#{lines.join("\n")}\n\n"
129
+ end
130
+
131
+ private
132
+
133
+ # The stub's answer: a Response, and with +chunked+ the body's pieces.
134
+ def respond(method, uri, headers, body, cancel, chunked: false)
96
135
  raise Plugin::HttpCancelled, "#{method} #{where(uri)}: cancelled" if cancel&.cancelled?
97
136
 
98
137
  request = Request.new(method: method, url: uri.to_s, headers: headers.dup.freeze, body: body)
@@ -102,13 +141,13 @@ module Samagotchi
102
141
  end
103
142
  raise UnstubbedRequest, unstubbed_message(request) unless stub
104
143
 
105
- respond(request, uri, stub.answer.respond_to?(:call) ? stub.answer.call(request) : stub.answer)
144
+ answer = stub.answer.respond_to?(:call) ? stub.answer.call(request) : stub.answer
145
+ response, chunks = answer_of(request, uri, answer)
146
+ chunked ? [response, chunks] : response
106
147
  end
107
148
 
108
- private
109
-
110
- def respond(request, uri, answer)
111
- return answer if answer.is_a?(Plugin::Http::Response)
149
+ def answer_of(request, uri, answer)
150
+ return [answer, [answer.body]] if answer.is_a?(Plugin::Http::Response)
112
151
  raise ArgumentError, "a stub's block returns a Hash or a Plugin::Http::Response" unless answer.is_a?(Hash)
113
152
 
114
153
  if (error = answer[:error])
@@ -116,13 +155,19 @@ module Samagotchi
116
155
  end
117
156
 
118
157
  headers = (answer[:headers] || {}).to_h { |name, value| [name.to_s.downcase, value.to_s] }
119
- body = answer[:body].to_s
120
- unless answer[:json].nil?
121
- body = JSON.generate(answer[:json])
158
+ chunks = [answer[:body].to_s]
159
+ if !answer[:json].nil?
160
+ chunks = [JSON.generate(answer[:json])]
122
161
  headers = { "content-type" => "application/json" }.merge(headers)
162
+ elsif answer[:events]
163
+ chunks = Array(answer[:events]).map { |event| self.class.sse_text(event) }
164
+ headers = { "content-type" => "text/event-stream" }.merge(headers)
165
+ elsif answer[:chunks]
166
+ chunks = Array(answer[:chunks]).map(&:to_s)
123
167
  end
124
- body = "" if request.method == "HEAD"
125
- Plugin::Http::Response.new(status: Integer(answer[:status] || 200), headers: headers.freeze, body: body.dup)
168
+ chunks = [] if request.method == "HEAD"
169
+ body = Plugin::Http.text(chunks.join.b)
170
+ [Plugin::Http::Response.new(status: Integer(answer[:status] || 200), headers: headers.freeze, body: body), chunks]
126
171
  end
127
172
 
128
173
  def where(uri) = "#{uri.host}:#{uri.port}"
@@ -61,6 +61,7 @@ module Samagotchi
61
61
  use_toolkit: ->(name) { recorder.use_toolkit(name, toolkits.call) },
62
62
  load_tools: ->(names, bundle) { recorder.load_tools(names, bundle) },
63
63
  cancel_controller: ->(handler: false) { recorder[:cancelled] ? stopped : nil },
64
+ current_cancel: -> { recorder[:cancelled] ? stopped : nil },
64
65
  cost: -> { cost(recorder[:cost]) },
65
66
  usage: -> { usage(recorder[:usage]) },
66
67
  turn_author: -> { recorder[:turn_author] },
@@ -71,7 +72,9 @@ module Samagotchi
71
72
  # The candidate judge isn't the bundle's to test: a late proposal
72
73
  # goes nowhere.
73
74
  candidate_proposed: ->(_candidate) {},
74
- judgments: -> { recorder.judgments.layer }
75
+ judgments: -> { recorder.judgments.layer },
76
+ secrets_store: ->(_bundle) { recorder.secrets },
77
+ sign_in: ->(bundle, **options, &build) { recorder.sign_in(bundle, **options, &build) }
75
78
  )
76
79
  end
77
80
 
@@ -49,10 +49,13 @@ module Samagotchi
49
49
  # to restart), and the context size its confirm names (nil: none).
50
50
  history: false, context_tokens: nil,
51
51
  # ctx.model_names: nil gives model_name and its id without the host.
52
- model_names: nil
52
+ model_names: nil,
53
+ # ctx.secrets: seeds its in-memory store ({"name" => "value"}); a
54
+ # set replaces what it holds. bundle.secrets reads it.
55
+ secrets: nil
53
56
  }.freeze
54
57
 
55
- attr_reader :notices, :cards, :steers, :stops, :questions, :model_requests, :toolkit_uses, :tool_loads, :answers,
58
+ attr_reader :sign_ins, :notices, :cards, :steers, :stops, :questions, :model_requests, :toolkit_uses, :tool_loads, :answers,
56
59
  :model_answers, :values
57
60
 
58
61
  def initialize(**values)
@@ -60,7 +63,10 @@ module Samagotchi
60
63
  raise ArgumentError, "unknown host values: #{unknown.join(", ")}" unless unknown.empty?
61
64
 
62
65
  @values = DEFAULTS.merge(values)
66
+ @secrets = Plugin::Secrets::MemoryStore.new
67
+ @secrets.replace(@values[:secrets] || {})
63
68
  @notices = []
69
+ @sign_ins = []
64
70
  @cards = []
65
71
  @steers = []
66
72
  @stops = []
@@ -79,9 +85,14 @@ module Samagotchi
79
85
  raise ArgumentError, "unknown host values: #{unknown.join(", ")}" unless unknown.empty?
80
86
 
81
87
  @mutex.synchronize { @values.merge!(values) }
88
+ @secrets.replace(values[:secrets] || {}) if values.key?(:secrets)
82
89
  self
83
90
  end
84
91
 
92
+ # ctx.secrets' store: in memory, the one for the bundle under test.
93
+ # @return [Plugin::Secrets::MemoryStore]
94
+ attr_reader :secrets
95
+
85
96
  def [](key) = @mutex.synchronize { @values.fetch(key) }
86
97
 
87
98
  # ctx.judge and ctx.judge_later's System 1 (Testing::Judgments).
@@ -97,13 +108,42 @@ module Samagotchi
97
108
  nil
98
109
  end
99
110
 
100
- # Checked as chi's cards are (Plugin::Card.build); the id it shows.
101
- def card(**fields)
102
- card = Plugin::Card.build(**fields).freeze
111
+ # Checked as chi's cards are (Plugin::Card.build); the id it shows. A
112
+ # card shown with between_turns: true is recorded with it.
113
+ def card(between_turns: false, **fields)
114
+ card = Plugin::Card.build(**fields)
115
+ card = card.merge(between_turns: true) if between_turns
116
+ card.freeze
103
117
  record(@cards, card)
104
118
  card[:id]
105
119
  end
106
120
 
121
+ # The port a kit flow's redirect_uri names: none is opened.
122
+ SIGN_IN_PORT = 53_682
123
+
124
+ # ctx.sign_in, as chi starts one (Engine#start_sign_in) but with no
125
+ # port opened: the card with its button, the flow listed in
126
+ # #sign_ins; Bundle#complete_sign_in / #fail_sign_in settle it. An
127
+ # ending without a callback replaces its card as chi does.
128
+ # @return [Plugin::SignIn]
129
+ def sign_in(bundle, title:, button:, timeout:, port:, path:, cancel: nil, &build)
130
+ redirect_uri = "http://127.0.0.1:#{port || SIGN_IN_PORT}#{path}"
131
+ flow = Plugin::SignIn.new(bundle: bundle, title: title, button: button, timeout: timeout, listener: nil,
132
+ redirect_uri: redirect_uri, cancel: cancel,
133
+ on_settle: lambda { |settled, outcome|
134
+ ended = Plugin::SignIn.ended_card(settled, outcome)
135
+ card(source: bundle, level: :info, **ended) if ended
136
+ })
137
+ address = yield(redirect_uri).to_s.strip
138
+ id = Plugin::Card.build(source: bundle, title: title, body: "", actions: [{ label: button, url: address }],
139
+ level: :info, id: nil)[:id]
140
+ flow.started(address, id)
141
+ card(source: bundle, title: title, body: Plugin::SignIn::PASTE_LINE, actions: [{ label: button, url: address }],
142
+ level: :info, id: id)
143
+ record(@sign_ins, flow)
144
+ flow
145
+ end
146
+
107
147
  def steer(text, hook)
108
148
  return false unless self[:running]
109
149
 
@@ -105,6 +105,16 @@ module Samagotchi
105
105
  end
106
106
  private_class_method :prompt_memory_name
107
107
 
108
+ # The text a Resolved entry reads as: its file, its overlay appended
109
+ # (#append_overlay). memory_read's body of one name and the prompt's
110
+ # identity and preloads (SystemPrompt, through #call); the working
111
+ # set's re-fetch of a prompt part resolves with the saved keys and
112
+ # composes here too, so the two never differ. +read+: the file reader.
113
+ def self.compose(resolved, read: ->(path) { File.read(path, encoding: "UTF-8") })
114
+ body = read.call(resolved.path)
115
+ resolved.overlay_path ? append_overlay(body, read.call(resolved.overlay_path), resolved.overlay_key) : body
116
+ end
117
+
108
118
  def self.overlay_prefix(key) = "#{SEPARATOR}Model-specific guidance (#{key}):\n"
109
119
 
110
120
  def self.append_overlay(body, overlay_text, key) = "#{body}#{overlay_prefix(key)}#{overlay_text}"
@@ -166,9 +176,7 @@ module Samagotchi
166
176
  next
167
177
  end
168
178
 
169
- body = File.read(resolved.path, encoding: "UTF-8")
170
- body = append_overlay(body, File.read(resolved.overlay_path, encoding: "UTF-8"), resolved.overlay_key) if resolved.overlay_path
171
- results << body
179
+ results << compose(resolved)
172
180
  reads[name] = { path: resolved.path, overlay_path: resolved.overlay_path, requested_scope: scope,
173
181
  model_key: model_key, fallback_model_key: fallback_model_key, project_dir: project_dir }
174
182
  end
@@ -130,7 +130,7 @@ module Samagotchi
130
130
  end
131
131
 
132
132
  # A Group's states.
133
- STATES = %i[ready starting failed].freeze
133
+ STATES = %i[ready starting failed needs_user].freeze
134
134
 
135
135
  # A search's answer (#find): its text, and the tools it loads on a host
136
136
  # that loads tools (+loaded+: the wire names of a keyword answer's
@@ -148,7 +148,10 @@ module Samagotchi
148
148
  # One group of a source's tools (an MCP server): +summary+ its line in
149
149
  # the search tool's description (nil: its name and tool count only),
150
150
  # +state+ :ready, :starting (its tools may come: a lookup waits) or
151
- # :failed (+error+ says why). A group exists before its tools do.
151
+ # :failed (+error+ says why), :needs_user (it can't be used until the
152
+ # user does something: +error+ is the source's own line, a sign-in's;
153
+ # a call that names it asks the source's wait first).
154
+ # A group exists before its tools do.
152
155
  # Another state, or a tool of another group, raises ArgumentError (a
153
156
  # lookup would neither wait on it nor find the tool's source).
154
157
  Group = Data.define(:name, :summary, :state, :error, :tools) do
@@ -162,6 +165,7 @@ module Samagotchi
162
165
  end
163
166
 
164
167
  summary = summary.to_s.strip
168
+ error = "#{name} needs the user" if state == :needs_user && error.to_s.strip.empty?
165
169
  super(name: name.to_s, summary: summary.empty? ? nil : summary, state: state, error: error,
166
170
  tools: tools.dup.freeze)
167
171
  end
@@ -174,6 +178,7 @@ module Samagotchi
174
178
  case state
175
179
  when :failed then "(failed: #{error})"
176
180
  when :starting then "(starting, try again)"
181
+ when :needs_user then "(#{error})"
177
182
  end
178
183
  end
179
184
  end
@@ -756,9 +761,12 @@ module Samagotchi
756
761
  end
757
762
 
758
763
  # A name with a group's <group>/ waits for that group only; any
759
- # other name (an acts_as) for every one starting.
764
+ # other name (an acts_as) for every one starting. A group that needs
765
+ # the user, named, is asked too: the user may have done it meanwhile
766
+ # (signed in from another session).
760
767
  named = reached_groups(surface).select { |group| name.start_with?("#{group.name}/") }
761
768
  starting = (named.empty? ? reached_groups(surface) : named).select { |group| group.state == :starting }
769
+ starting += named.select { |group| group.state == :needs_user }
762
770
  unless waited || starting.empty?
763
771
  starting.each { |group| source_of(group.name)&.wait(group.name) }
764
772
  return lookup(name, surface, waited: true)
@@ -767,6 +775,9 @@ module Samagotchi
767
775
  failed = all.find { |group| group.state == :failed && name.start_with?("#{group.name}/") }
768
776
  return "Error: MCP server #{failed.name} didn't start: #{failed.error}" if failed
769
777
 
778
+ blocked = all.find { |group| group.state == :needs_user && name.start_with?("#{group.name}/") }
779
+ return "Error: #{blocked.error}" if blocked
780
+
770
781
  closest = ranked(name, all.flat_map(&:tools)).take(CLOSEST)
771
782
  return "Error: no tool #{name}. Search with #{FIND_NAME}." if closest.empty?
772
783
 
@@ -19,8 +19,8 @@ module Samagotchi
19
19
  # @param turn_state [TurnState] whether steers are carried to the next turn
20
20
  # @param model_settings [SessionModelSettings] the effective model now, the next turn's LLM context strategy
21
21
  # @param reminder_queue [ReminderQueue] whether a reminder is due
22
- # @param system_prompt [#call] (model) the system prompt (Engine#system_prompt): called last, only
23
- # once every check passed, as building it has side effects (the memory index metric, the prompt notes)
22
+ # @param system_prompt [#call] (model) the system prompt (Engine#system_prompt with record: false: a
23
+ # warm-up records no parts, notes or memory index): called last, only once every check passed
24
24
  def initialize(prompt_warmup:, kernel:, turn_state:, model_settings:, reminder_queue:, system_prompt:)
25
25
  @prompt_warmup = prompt_warmup
26
26
  @kernel = kernel
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.182.0"
4
+ VERSION = "0.184.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -303,7 +303,7 @@ module Samagotchi
303
303
  ["POST", %r{\A/api/update\z}, :handle_update, :owner],
304
304
  ["POST", %r{\A/api/update/restart_workers\z}, :handle_restart_workers, :owner],
305
305
  ["POST", %r{\A/api/update/restart_web\z}, :handle_restart_web, :owner],
306
- ["POST", %r{\A/api/render\z}, :handle_render, :owner],
306
+ ["POST", %r{\A/api/render\z}, :handle_render, :owner], *McpRoute::ROUTES,
307
307
  ["GET", %r{\A/api/sessions/([^/]+)/stream\z}, :handle_stream, :participant],
308
308
  ["GET", %r{\A/api/sessions/([^/]+)/output\z}, :handle_output, :owner, :session],
309
309
  ["POST", %r{\A/api/sessions/([^/]+)/cancel\z}, :handle_cancel, :participant, :session],
@@ -318,6 +318,7 @@ module Samagotchi
318
318
  ["POST", %r{\A/api/sessions/([^/]+)/turn\z}, :handle_turn, :participant, :session],
319
319
  ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :participant, :session],
320
320
  ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :participant, :session],
321
+ ["POST", %r{\A/api/sessions/([^/]+)/ask\z}, :handle_ask, :owner, :session],
321
322
  ["POST", %r{\A/api/sessions/([^/]+)/verdicts/([^/]+)/fresh\z}, :handle_verify_fresh, :participant, :session],
322
323
  ["POST", %r{\A/api/sessions/([^/]+)/blocks/fix\z}, :handle_block_fix, :owner, :session],
323
324
  ["POST", %r{\A/api/sessions/([^/]+)/notes\z}, :handle_notes, :owner, :session],
@@ -341,9 +342,8 @@ module Samagotchi
341
342
  ["POST", %r{\A/api/sessions/([^/]+)/context\z}, :handle_context_add, :owner, :session],
342
343
  ["POST", %r{\A/api/sessions/([^/]+)/context/([^/]+)/push\z}, :handle_context_push, :owner, :session],
343
344
  ["DELETE", %r{\A/api/sessions/([^/]+)/context/([^/]+)\z}, :handle_context_delete, :owner, :session],
344
- ["GET", %r{\A/api/sessions/([^/]+)/working_set\z}, :handle_working_set, :participant, :session],
345
+ *WorkingSetRoutes::ROUTES,
345
346
  ["GET", %r{\A/api/sessions/([^/]+)/prompt_history\z}, :handle_prompt_history, :participant, :session],
346
- ["GET", %r{\A/api/sessions/([^/]+)/working_set/item\z}, :handle_working_set_item, :owner, :session],
347
347
  ["GET", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_list, :owner, :session],
348
348
  ["POST", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_invite, :owner, :session],
349
349
  ["DELETE", %r{\A/api/sessions/([^/]+)/participants\z}, :handle_participants_revoke, :owner, :session],
@@ -833,7 +833,7 @@ module Samagotchi
833
833
  def unauthorized(req)
834
834
  reason = req.env[REFUSED_ENV]
835
835
  log_refused(refused_peer(req), req.path_info, reason)
836
- return error_response(401, "unauthorized", unauthorized_detail(req, reason)) if req.path_info.start_with?("/api/")
836
+ return api_unauthorized(req, unauthorized_detail(req, reason)) if req.path_info.start_with?("/api/")
837
837
 
838
838
  body = unauthorized_page(req)
839
839
  [401, { "Content-Type" => "text/html; charset=utf-8", "Content-Length" => body.bytesize.to_s, "Cache-Control" => "no-store" },
@@ -1126,7 +1126,7 @@ module Samagotchi
1126
1126
  # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
1127
  DELETE_PLAN_FEATURE = "delete_plan_all"
1128
1128
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1129
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE].freeze
1129
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE].freeze
1130
1130
 
1131
1131
  # The models a new session can start on, spelled as chi spells them
1132
1132
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1149,6 +1149,7 @@ module Samagotchi
1149
1149
  # (SessionManager::ScratchSession, an OwnedByTUI: 409).
1150
1150
  def record_history(body, line)
1151
1151
  return if body["history"] == false
1152
+ return if SessionCommandCatalog.builtin_registry.private_args?(line.to_s) # /callback's argument stays out
1152
1153
 
1153
1154
  PromptHistory.append(line.to_s)
1154
1155
  rescue StandardError => e
@@ -1416,11 +1417,11 @@ module Samagotchi
1416
1417
  error_response(504, "worker_timeout", "the session's worker did not answer, so #{what}")
1417
1418
  end
1418
1419
 
1419
- # The session's Bridge, waiting briefly for one a resume just spawned.
1420
+ # The session's Bridge, waiting briefly (5 s, or +within+ an ask's left) for one a resume just spawned.
1420
1421
  # @return [BridgeClient, nil]
1421
- def live_bridge_client(id)
1422
+ def live_bridge_client(id, within: 5.0)
1422
1423
  link = worker_link(id)
1423
- link = await_worker_link(id, timeout: [@bridge_wait_timeout.to_f, 5.0].min) unless link.live?
1424
+ link = await_worker_link(id, timeout: [@bridge_wait_timeout.to_f, within].min.clamp(0.0..)) unless link.live?
1424
1425
  link_client(id, link)
1425
1426
  end
1426
1427