samagotchi 0.181.0 → 0.183.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 (200) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +4 -1
  4. data/docs/architecture.md +17 -7
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +58 -10
  8. data/docs/configuration.md +3 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +172 -3
  11. data/docs/internals/bridge.md +23 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +29 -8
  14. data/docs/internals/inline-widgets.md +3 -1
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +38 -7
  17. data/docs/internals/web-frontend.md +116 -26
  18. data/docs/internals/working-set.md +1 -1
  19. data/docs/mcp-server.md +80 -0
  20. data/docs/plugins.md +308 -21
  21. data/docs/sessions.md +7 -4
  22. data/docs/sub-agent.md +9 -0
  23. data/docs/testing.md +3 -1
  24. data/docs/thin-clients.md +146 -0
  25. data/lib/samagotchi/answer_display.rb +3 -2
  26. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  27. data/lib/samagotchi/block_fix.rb +220 -0
  28. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  29. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  30. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  31. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  32. data/lib/samagotchi/bridge.rb +69 -69
  33. data/lib/samagotchi/bridge_client.rb +9 -0
  34. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  35. data/lib/samagotchi/bundle_command/check.rb +36 -19
  36. data/lib/samagotchi/bundle_command.rb +50 -21
  37. data/lib/samagotchi/bundle_manifest.rb +101 -4
  38. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  39. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  40. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  41. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  42. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  43. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  44. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  45. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  46. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  47. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  48. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  49. data/lib/samagotchi/command_intake.rb +7 -0
  50. data/lib/samagotchi/commands/registry.rb +8 -3
  51. data/lib/samagotchi/config.rb +3 -0
  52. data/lib/samagotchi/continue_intent.rb +8 -0
  53. data/lib/samagotchi/continue_offer.rb +24 -15
  54. data/lib/samagotchi/engine/block_fix.rb +332 -0
  55. data/lib/samagotchi/engine/cards.rb +14 -5
  56. data/lib/samagotchi/engine/events.rb +10 -15
  57. data/lib/samagotchi/engine/models.rb +1 -1
  58. data/lib/samagotchi/engine/plugins.rb +3 -0
  59. data/lib/samagotchi/engine/recap.rb +1 -1
  60. data/lib/samagotchi/engine/side_requests.rb +8 -6
  61. data/lib/samagotchi/engine/sign_in.rb +142 -0
  62. data/lib/samagotchi/engine/turn_end.rb +3 -3
  63. data/lib/samagotchi/engine.rb +47 -27
  64. data/lib/samagotchi/engine_snapshots.rb +1 -1
  65. data/lib/samagotchi/events.rb +1 -0
  66. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  67. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  68. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  69. data/lib/samagotchi/hold_stop.rb +4 -4
  70. data/lib/samagotchi/idle_client.rb +10 -6
  71. data/lib/samagotchi/idle_recap.rb +19 -11
  72. data/lib/samagotchi/idle_reminders.rb +7 -5
  73. data/lib/samagotchi/idle_scheduler.rb +7 -10
  74. data/lib/samagotchi/inline_widgets.rb +12 -0
  75. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  76. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  77. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  78. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  79. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  80. data/lib/samagotchi/kernel_loop.rb +7 -5
  81. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  82. data/lib/samagotchi/llm/http.rb +96 -5
  83. data/lib/samagotchi/markdown_parser.rb +28 -0
  84. data/lib/samagotchi/mcp_command.rb +110 -0
  85. data/lib/samagotchi/mcp_server/http.rb +112 -0
  86. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  87. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  88. data/lib/samagotchi/mcp_server/text.rb +155 -0
  89. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  90. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  91. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  92. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  93. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  94. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  95. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  96. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  97. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  98. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  99. data/lib/samagotchi/plugin/api.rb +6 -1
  100. data/lib/samagotchi/plugin/card.rb +36 -11
  101. data/lib/samagotchi/plugin/context.rb +63 -6
  102. data/lib/samagotchi/plugin/http.rb +40 -15
  103. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  104. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  105. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  106. data/lib/samagotchi/plugin/loader.rb +18 -11
  107. data/lib/samagotchi/plugin/secrets.rb +266 -0
  108. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  109. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  110. data/lib/samagotchi/queued_command.rb +28 -4
  111. data/lib/samagotchi/recap_setup.rb +13 -4
  112. data/lib/samagotchi/ref.rb +3 -2
  113. data/lib/samagotchi/relay_verifier.rb +8 -7
  114. data/lib/samagotchi/relay_watcher.rb +4 -4
  115. data/lib/samagotchi/run_options.rb +2 -1
  116. data/lib/samagotchi/send_command.rb +54 -41
  117. data/lib/samagotchi/session_access/ask.rb +244 -0
  118. data/lib/samagotchi/session_access/contract.rb +8 -0
  119. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  120. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  121. data/lib/samagotchi/session_access/exchange.rb +173 -0
  122. data/lib/samagotchi/session_access/local.rb +38 -6
  123. data/lib/samagotchi/session_access/remote.rb +23 -2
  124. data/lib/samagotchi/session_access.rb +1 -0
  125. data/lib/samagotchi/session_chain/delete.rb +39 -81
  126. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  127. data/lib/samagotchi/session_command_catalog.rb +10 -0
  128. data/lib/samagotchi/session_commands.rb +17 -0
  129. data/lib/samagotchi/session_config.rb +4 -4
  130. data/lib/samagotchi/session_delete_command.rb +129 -3
  131. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  132. data/lib/samagotchi/session_manager/listing.rb +4 -4
  133. data/lib/samagotchi/session_manager/removal.rb +38 -12
  134. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  135. data/lib/samagotchi/session_manager.rb +1 -0
  136. data/lib/samagotchi/session_observer.rb +27 -0
  137. data/lib/samagotchi/steer_cut.rb +4 -3
  138. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  139. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  140. data/lib/samagotchi/testing/boundary.rb +4 -0
  141. data/lib/samagotchi/testing/bundle.rb +48 -2
  142. data/lib/samagotchi/testing/fake_http.rb +60 -15
  143. data/lib/samagotchi/testing/host.rb +4 -1
  144. data/lib/samagotchi/testing/recorder.rb +45 -5
  145. data/lib/samagotchi/tools/tool_index.rb +14 -3
  146. data/lib/samagotchi/version.rb +1 -1
  147. data/lib/samagotchi/web/app.rb +20 -6
  148. data/lib/samagotchi/web/ask_routes.rb +292 -0
  149. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  150. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  151. data/lib/samagotchi/web/mcp_route.rb +88 -0
  152. data/lib/samagotchi/web/message_display.rb +6 -1
  153. data/lib/samagotchi/web/participant_view.rb +1 -1
  154. data/lib/samagotchi/web/public/app.js +7 -8
  155. data/lib/samagotchi/web/public/block_fix.js +270 -0
  156. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  157. data/lib/samagotchi/web/public/block_frame.js +77 -13
  158. data/lib/samagotchi/web/public/block_host.js +45 -9
  159. data/lib/samagotchi/web/public/block_regions.js +126 -0
  160. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  161. data/lib/samagotchi/web/public/block_watch.js +16 -2
  162. data/lib/samagotchi/web/public/card.js +22 -9
  163. data/lib/samagotchi/web/public/card_actions.js +21 -0
  164. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  165. data/lib/samagotchi/web/public/card_registry.js +3 -2
  166. data/lib/samagotchi/web/public/data.js +15 -12
  167. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  168. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  169. data/lib/samagotchi/web/public/format.js +3 -0
  170. data/lib/samagotchi/web/public/index.html +52 -7
  171. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  172. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  173. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  174. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  175. data/lib/samagotchi/web/public/refs.js +5 -3
  176. data/lib/samagotchi/web/public/region_hit.js +144 -0
  177. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  178. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  179. data/lib/samagotchi/web/public/session_actions.js +105 -100
  180. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  181. data/lib/samagotchi/web/public/turn_block.js +5 -2
  182. data/lib/samagotchi/web/server.rb +6 -4
  183. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  184. data/lib/samagotchi/web/session_control.rb +84 -30
  185. data/lib/samagotchi/web/session_create.rb +2 -2
  186. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  187. data/lib/samagotchi/worker/child_side.rb +3 -2
  188. data/lib/samagotchi/worker/command_queue.rb +13 -13
  189. data/lib/samagotchi/worker/leave.rb +3 -3
  190. data/lib/samagotchi/worker/scratch.rb +6 -6
  191. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  192. data/lib/samagotchi/worker/startup.rb +3 -3
  193. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  194. data/lib/samagotchi/worker.rb +42 -24
  195. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  196. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  197. data/lib/samagotchi/worker_inbound.rb +12 -7
  198. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  199. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  200. metadata +42 -1
@@ -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
 
@@ -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
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.181.0"
4
+ VERSION = "0.183.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -81,6 +81,7 @@ require_relative "session_show"
81
81
  require_relative "session_create"
82
82
  require_relative "session_control"
83
83
  require_relative "verify_fresh_routes"
84
+ require_relative "block_fix_routes"
84
85
  require_relative "reload_check_route"
85
86
  require_relative "working_set_routes"
86
87
  require_relative "push_routes"
@@ -121,6 +122,7 @@ module Samagotchi
121
122
  include SessionCreate
122
123
  include SessionControl
123
124
  include VerifyFreshRoutes
125
+ include BlockFixRoutes
124
126
  include ReloadCheckRoute
125
127
  include WorkingSetRoutes
126
128
  include PushRoutes
@@ -166,6 +168,8 @@ module Samagotchi
166
168
  # @param reload_check [Boolean] the page checks each finished turn
167
169
  # against a reload of it and posts the counts (web.reload_check,
168
170
  # opt-in; POST /api/sessions/:id/reload_check logs them)
171
+ # @param block_fix [String] "auto": the owner's page asks again for a
172
+ # block it couldn't draw in the newest answer (web.block_fix); "off": never
169
173
  # @param annotate_presets [String, Array] the quick replies next to
170
174
  # Annotate (web.annotate_presets, "|"-separated); "" shows none. The
171
175
  # page parses them (annotate_presets.js).
@@ -205,6 +209,7 @@ module Samagotchi
205
209
  registry: nil, models_wait_timeout: MODELS_WAIT_TIMEOUT, lan: nil,
206
210
  working_set: Config::BY_KEY["web.working_set"].default, wait_poll_interval: ReplyWait::POLL_INTERVAL,
207
211
  reload_check: Config::BY_KEY["web.reload_check"].default,
212
+ block_fix: Config::BY_KEY["web.block_fix"].default,
208
213
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
209
214
  grants: nil, public_url: nil, public_token: nil, push: nil, start_dir: nil, update_runner: nil,
210
215
  update_blocked: nil, update_ops: nil)
@@ -222,6 +227,7 @@ module Samagotchi
222
227
  @markdown_renderer = MarkdownRenderer.new(enabled: markdown)
223
228
  @working_set = working_set
224
229
  @reload_check = reload_check
230
+ @block_fix = block_fix.to_s
225
231
  @stage_collapsed = stage_collapsed
226
232
  @reload_checks = ReloadCheckRoute::Seen.new
227
233
  @annotate_presets = annotate_presets.is_a?(Array) ? annotate_presets.join("|") : annotate_presets.to_s
@@ -297,7 +303,7 @@ module Samagotchi
297
303
  ["POST", %r{\A/api/update\z}, :handle_update, :owner],
298
304
  ["POST", %r{\A/api/update/restart_workers\z}, :handle_restart_workers, :owner],
299
305
  ["POST", %r{\A/api/update/restart_web\z}, :handle_restart_web, :owner],
300
- ["POST", %r{\A/api/render\z}, :handle_render, :owner],
306
+ ["POST", %r{\A/api/render\z}, :handle_render, :owner], *McpRoute::ROUTES,
301
307
  ["GET", %r{\A/api/sessions/([^/]+)/stream\z}, :handle_stream, :participant],
302
308
  ["GET", %r{\A/api/sessions/([^/]+)/output\z}, :handle_output, :owner, :session],
303
309
  ["POST", %r{\A/api/sessions/([^/]+)/cancel\z}, :handle_cancel, :participant, :session],
@@ -312,7 +318,9 @@ module Samagotchi
312
318
  ["POST", %r{\A/api/sessions/([^/]+)/turn\z}, :handle_turn, :participant, :session],
313
319
  ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :participant, :session],
314
320
  ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :participant, :session],
321
+ ["POST", %r{\A/api/sessions/([^/]+)/ask\z}, :handle_ask, :owner, :session],
315
322
  ["POST", %r{\A/api/sessions/([^/]+)/verdicts/([^/]+)/fresh\z}, :handle_verify_fresh, :participant, :session],
323
+ ["POST", %r{\A/api/sessions/([^/]+)/blocks/fix\z}, :handle_block_fix, :owner, :session],
316
324
  ["POST", %r{\A/api/sessions/([^/]+)/notes\z}, :handle_notes, :owner, :session],
317
325
  ["POST", %r{\A/api/sessions/([^/]+)/wake\z}, :handle_wake, :owner, :session],
318
326
  ["GET", %r{\A/api/sessions/([^/]+)/worker\z}, :handle_worker, :owner, :session],
@@ -826,7 +834,7 @@ module Samagotchi
826
834
  def unauthorized(req)
827
835
  reason = req.env[REFUSED_ENV]
828
836
  log_refused(refused_peer(req), req.path_info, reason)
829
- return error_response(401, "unauthorized", unauthorized_detail(req, reason)) if req.path_info.start_with?("/api/")
837
+ return api_unauthorized(req, unauthorized_detail(req, reason)) if req.path_info.start_with?("/api/")
830
838
 
831
839
  body = unauthorized_page(req)
832
840
  [401, { "Content-Type" => "text/html; charset=utf-8", "Content-Length" => body.bytesize.to_s, "Cache-Control" => "no-store" },
@@ -1114,8 +1122,12 @@ module Samagotchi
1114
1122
  # tasks_running) and take stop_tasks: chi --remote sessions
1115
1123
  # delete|archive --stop-tasks asks for this first.
1116
1124
  STOP_TASKS_FEATURE = "stop_tasks"
1125
+ # GET …/delete_plan answers for every session (a session in no chain:
1126
+ # {chained: false, link}), and a delete takes a plain session's stopped
1127
+ # delegates: chi --remote sessions delete --dry-run asks for this first.
1128
+ DELETE_PLAN_FEATURE = "delete_plan_all"
1117
1129
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1118
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE].freeze
1130
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE, ASK_FEATURE, McpRoute::FEATURE].freeze
1119
1131
 
1120
1132
  # The models a new session can start on, spelled as chi spells them
1121
1133
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1138,6 +1150,7 @@ module Samagotchi
1138
1150
  # (SessionManager::ScratchSession, an OwnedByTUI: 409).
1139
1151
  def record_history(body, line)
1140
1152
  return if body["history"] == false
1153
+ return if SessionCommandCatalog.builtin_registry.private_args?(line.to_s) # /callback's argument stays out
1141
1154
 
1142
1155
  PromptHistory.append(line.to_s)
1143
1156
  rescue StandardError => e
@@ -1405,11 +1418,11 @@ module Samagotchi
1405
1418
  error_response(504, "worker_timeout", "the session's worker did not answer, so #{what}")
1406
1419
  end
1407
1420
 
1408
- # The session's Bridge, waiting briefly for one a resume just spawned.
1421
+ # The session's Bridge, waiting briefly (5 s, or +within+ an ask's left) for one a resume just spawned.
1409
1422
  # @return [BridgeClient, nil]
1410
- def live_bridge_client(id)
1423
+ def live_bridge_client(id, within: 5.0)
1411
1424
  link = worker_link(id)
1412
- link = await_worker_link(id, timeout: [@bridge_wait_timeout.to_f, 5.0].min) unless link.live?
1425
+ link = await_worker_link(id, timeout: [@bridge_wait_timeout.to_f, within].min.clamp(0.0..)) unless link.live?
1413
1426
  link_client(id, link)
1414
1427
  end
1415
1428
 
@@ -1947,6 +1960,7 @@ module Samagotchi
1947
1960
  attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1948
1961
  # The opt-in reload check (reload_check.js): only when on.
1949
1962
  attrs["reload-check"] = "1" if @reload_check
1963
+ attrs["block-fix"] = @block_fix
1950
1964
  attrs.merge!(stage_collapsed_data)
1951
1965
  attrs.merge!(annotate_presets_data)
1952
1966
  # Who looks and what they may do (Viewer; viewer.js reads it at boot).