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
@@ -0,0 +1,292 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "delegate"
4
+ require_relative "../client_id"
5
+ require_relative "../reply_wait"
6
+ require_relative "../session"
7
+ require_relative "../session_command_catalog"
8
+ require_relative "../session_inbox"
9
+ require_relative "../turn_flow"
10
+ require_relative "../session_access/ask"
11
+ require_relative "../session_access/exchange"
12
+ require_relative "../session_access/exchange/token"
13
+ require_relative "request_body"
14
+
15
+ module Samagotchi
16
+ module Web
17
+ # The thin-client routes (docs/thin-clients.md): POST …/ask (one
18
+ # message, its answer in one call: SessionAccess::Ask), a wait token for
19
+ # POST …/wait (#handle_token_wait), wait: on POST …/answer
20
+ # (#answer_wait_option, #answered_wait) and a create's token
21
+ # (#create_token). Included in App through SessionAccessRoutes; its
22
+ # helpers (json_response, body_hash, wait_result_json, busy_json,
23
+ # parent_gate, owned_by_tui, refused_delivery, record_history, …) answer.
24
+ module AskRoutes
25
+ # One ask answers within this many seconds from its request's start,
26
+ # whatever it waits for (a continue in flight, the Bridge of a worker
27
+ # starting, the wait's slice): a proxy or a Shortcut with a 60 s limit
28
+ # is safe. Only the post to a live worker isn't drawn from it: it is
29
+ # instant unless the worker hangs (BridgeClient's 25 s deadline).
30
+ ASK_MAX_SECONDS = 35.0
31
+ # A wait route answers within this many seconds (status timeout); the
32
+ # client asks again until its own --timeout. SessionAccessRoutes'
33
+ # (which includes this module) too.
34
+ WAIT_MAX_SECONDS = 30.0
35
+ # GET /api/info's feature: this chi web has the ask route, wait
36
+ # tokens, the answer's wait and the create's token.
37
+ ASK_FEATURE = "ask"
38
+ # The wait body's own fields, which a token replaces.
39
+ TOKEN_EXCLUDES = %w[cursor baseline turn queued ended_before owner_grace].freeze
40
+
41
+ # The ask's backend: chi web's sessions (SessionAccess::Local),
42
+ # delivering through chi web's own manager and Bridge as POST …/turn
43
+ # does (the same Bridge wait and give-ups), and waiting at its poll
44
+ # interval. One per request.
45
+ class AskAccess < SimpleDelegator
46
+ def initialize(access, manager:, bridge:, poll_interval: nil)
47
+ super(access)
48
+ @manager = manager
49
+ @bridge = bridge
50
+ @poll_interval = poll_interval
51
+ end
52
+
53
+ def deliver_turn(id, **)
54
+ __getobj__.deliver_turn(id, **, manager: @manager, bridge: -> { @bridge.call(id) })
55
+ end
56
+
57
+ def wait_reply(id, **options)
58
+ options = { poll_interval: @poll_interval }.merge(options) if @poll_interval
59
+ __getobj__.wait_reply(id, **options)
60
+ end
61
+ end
62
+
63
+ private
64
+
65
+ # POST /api/sessions/:id/ask {prompt, timeout, queue, client_id}: the
66
+ # message delivered (to a chain's newest link; a running session
67
+ # queues it as its own turn unless queue is false) and its answer
68
+ # waited for, all within ASK_MAX_SECONDS. 200 wait_result_json's
69
+ # fields + session_id (+ asked, the id given, when another link ran
70
+ # it; + token when the status is timeout: POST …/wait {token} goes
71
+ # on); 200 {status: command} for a session command. 404 not_found,
72
+ # 400 ambiguous_id, 409 busy / waiting / continuing / owned_by_tui,
73
+ # the turn route's delivery refusals, 503 server_stopping.
74
+ def handle_ask(req, id)
75
+ # One deadline from the request's start: the gate, the continue
76
+ # waits, the Bridge wait and the slice all draw on it.
77
+ deadline = ask_clock + ASK_MAX_SECONDS
78
+ body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
79
+ prompt, client_id, options, error = ask_request(id, body)
80
+ return error if error
81
+
82
+ gated = ask_gate(id, prompt, client_id)
83
+ return gated if gated
84
+
85
+ bridge = ->(sid) { live_bridge_client(sid, within: deadline - ask_clock) }
86
+ access = AskAccess.new(session_access, manager: @manager, bridge: bridge, poll_interval: @wait_poll_interval)
87
+ stopping = -> { !@server_running.call }
88
+ exchange = SessionAccess::Exchange.new(access, continuing_wait: [SessionAccess::Exchange::CONTINUING_WAIT,
89
+ ASK_MAX_SECONDS].min, cancelled: stopping)
90
+ outcome = SessionAccess::Ask.new(access, exchange: exchange)
91
+ .call(id, prompt: prompt, client_id: client_id, cap: deadline - ask_clock,
92
+ cancelled: stopping, **options)
93
+ record_history(body, prompt) unless outcome.is_a?(SessionAccess::Ask::Refused)
94
+ ask_response(id, outcome)
95
+ rescue SessionManager::OwnedByTUI => e
96
+ owned_by_tui(e)
97
+ end
98
+
99
+ # The ask's body read: [prompt, client_id, {queue:, timeout:}, nil] or
100
+ # [.., a 400 response].
101
+ def ask_request(id, body)
102
+ return [nil, nil, nil, error_response(400, "missing_fields", "prompt is required")] unless body["prompt"].is_a?(String)
103
+
104
+ prompt = SessionInbox.checked_text(body["prompt"], noun: "message")
105
+ if (entry = SessionCommandCatalog.ui_only_entry(prompt))
106
+ words = SessionCommandCatalog.ui_only_refusal(entry.name, id, runner: "ask")
107
+ return [nil, nil, nil, error_response(400, "local_command", words)]
108
+ end
109
+
110
+ timeout = body.fetch("timeout", WAIT_MAX_SECONDS)
111
+ unless timeout.is_a?(Numeric) && timeout.positive?
112
+ return [nil, nil, nil, error_response(400, "invalid_ask", "timeout is positive seconds")]
113
+ end
114
+
115
+ queue = body.fetch("queue", true)
116
+ return [nil, nil, nil, error_response(400, "invalid_ask", "queue is true or false")] unless [true, false].include?(queue)
117
+
118
+ client_id = body["client_id"]
119
+ return [nil, nil, nil, error_response(400, "invalid_ask", "client_id is a string")] unless client_id.nil? || client_id.is_a?(String)
120
+
121
+ [prompt, ask_sender(client_id, prompt), { queue: queue, timeout: [timeout, WAIT_MAX_SECONDS].min }, nil]
122
+ rescue SessionInbox::NoteRejected => e
123
+ [nil, nil, nil, error_response(400, "invalid_prompt", e.message)]
124
+ end
125
+
126
+ # Who asks: the owner (WEB_UNNAMED) unless the body names a sender
127
+ # (owner_sender's rule); a parent agent's /continue yes sent as
128
+ # cli:send goes in as cli:answer, as chi send sends it (the worker
129
+ # holds that one to guardrails.parent_answers).
130
+ def ask_sender(client_id, prompt)
131
+ sender = owner_sender({ "client_id" => client_id })
132
+ sender == ClientId::CLI_SEND && TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : sender
133
+ end
134
+
135
+ # A parent agent's line refused before anything is sent, as POST
136
+ # …/turn refuses it (#parent_gate), held to the parent_answers of the
137
+ # session asked and of its chain's newest link (where it goes).
138
+ # @return [Array, nil] the response, or nil to go on
139
+ def ask_gate(id, prompt, client_id)
140
+ return nil unless App::CLI_SEND_IDS.include?(client_id)
141
+
142
+ asked = session_access.resolve(id)
143
+ ids = [asked, session_access.head(asked).id].uniq
144
+ sessions = ids.select { |sid| File.file?(Session.session_file(sid, state_dir: default_state_dir)) }
145
+ values = sessions.map { |sid| session_access.show(sid).parent_answers }
146
+ # No session left to read: config.yml's value alone (fail closed),
147
+ # as SendCommand::ParentGate#target_values falls back.
148
+ values = [nil] if values.empty?
149
+ parent_gate(prompt, client_id: client_id, values: values)
150
+ rescue ArgumentError # degrade-ok: no such session, or a prefix of several: the ask's own answer says which
151
+ nil
152
+ end
153
+
154
+ # The ask's answer for an Ask value.
155
+ def ask_response(id, outcome)
156
+ case outcome
157
+ when SessionAccess::Ask::Ran then json_response(200, { status: "command", session_id: outcome.session_id })
158
+ when SessionAccess::Ask::Refused then ask_refused(id, outcome)
159
+ else
160
+ result = outcome.result
161
+ return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
162
+
163
+ json = wait_result_json(result, session_access.parent_strategy(outcome.session_id)).merge(session_id: outcome.session_id)
164
+ json[:asked] = outcome.asked if outcome.asked && outcome.asked != outcome.session_id
165
+ json[:token] = outcome.token if outcome.token
166
+ json_response(200, json)
167
+ end
168
+ end
169
+
170
+ # Neutral words for a Busy, not chi send's flags.
171
+ ASK_BUSY_WORDS = { "busy" => "a turn is running: ask with queue, or wait for it",
172
+ "waiting" => "a question waits for an answer" }.freeze
173
+
174
+ def ask_refused(id, refused)
175
+ case refused.kind
176
+ when :canceled then error_response(503, "server_stopping", "chi web is stopping; ask again")
177
+ when :unknown
178
+ error = refused.error
179
+ return refusal_response(400, "ambiguous_id", error, ids: error.ids) if error.is_a?(Session::AmbiguousId)
180
+
181
+ session_not_found(id)
182
+ when :continuing then refusal(409, "continuing", refused.message, session_id: refused.session_id)
183
+ when :busy
184
+ words = ASK_BUSY_WORDS.fetch(refused.busy.error)
185
+ json_response(409, busy_json(refused.busy).merge(detail: words, message: words))
186
+ else refused_delivery(refused.result)
187
+ end
188
+ end
189
+
190
+ # POST /api/sessions/:id/wait {token, timeout}: the wait a token holds
191
+ # (an ask's, a create's, an answer's), for at most WAIT_MAX_SECONDS.
192
+ # The URL's id may be a prefix. 200 wait_result_json's fields +
193
+ # session_id (+ token, the same, while the status is timeout); 400 invalid_wait for a token that isn't one,
194
+ # another session's, a token beside the wait's own fields, or a
195
+ # participant's; 503 server_stopping.
196
+ def handle_token_wait(req, id, body)
197
+ return error_response(400, "invalid_wait", "a participant's wait takes a turn, not a token") unless principal(req).owner?
198
+ if TOKEN_EXCLUDES.any? { |key| ![nil, false].include?(body[key]) }
199
+ return error_response(400, "invalid_wait", "token or the wait's fields, not both")
200
+ end
201
+
202
+ timeout = body["timeout"]
203
+ unless timeout.nil? || (timeout.is_a?(Numeric) && timeout.positive?)
204
+ return error_response(400, "invalid_wait", "timeout is positive seconds")
205
+ end
206
+
207
+ session_id, target = SessionAccess::Exchange::Token.load(body["token"])
208
+ # The URL's id may be a prefix (as the ask's): resolved first (no
209
+ # such session, or several: session_route's 404).
210
+ full = session_access.resolve(id)
211
+ return error_response(400, "invalid_wait", "the token is another session's wait") unless session_id == full
212
+
213
+ result = plain_exchange.wait(full, target, timeout: [timeout || WAIT_MAX_SECONDS, WAIT_MAX_SECONDS].min,
214
+ **wait_extras)
215
+ return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
216
+
217
+ json = wait_result_json(result, session_access.parent_strategy(full)).merge(session_id: full)
218
+ json[:token] = body["token"] if result.status == :timeout
219
+ json_response(200, json)
220
+ rescue SessionAccess::Exchange::Token::Invalid => e
221
+ error_response(400, "invalid_wait", e.message)
222
+ end
223
+
224
+ # The answer's wait: [seconds, nil] (nil seconds: none asked), or
225
+ # [nil, a 400 response].
226
+ def answer_wait_option(body)
227
+ wait = body["wait"]
228
+ return [nil, nil] if wait.nil? || wait == false
229
+ return [nil, error_response(400, "invalid_wait", "wait is positive seconds")] unless wait.is_a?(Numeric) && wait.positive?
230
+
231
+ [[wait, WAIT_MAX_SECONDS].min, nil]
232
+ end
233
+
234
+ # What an answer's wait reads before the answer goes in
235
+ # (AnswerCommand's): the answered question is not the next thing.
236
+ # @return [WaitStart, nil] nil: the session is gone
237
+ def answer_wait_start(id, session, question_id)
238
+ session_access.prepare_wait(id, session: session, question_id: question_id.to_s)
239
+ rescue ArgumentError # degrade-ok: deleted meanwhile, the answer's 404
240
+ nil
241
+ end
242
+
243
+ # POST …/answer with wait: the answer relayed (+answered+; false: the
244
+ # question was answered elsewhere first, as chi answer still waits)
245
+ # and what comes next, for up to +seconds+. 200 {status: answered |
246
+ # not_pending, (answered_here: false,) session_id, id, reply:
247
+ # {wait_result_json's fields, token while it is timeout}}. The answer
248
+ # went in before the wait, so a wait that fails (chi web stopping, the
249
+ # session deleted, its files unreadable) is still a 200: wait_error
250
+ # {error: server_stopping | not_found | wait_failed, detail} in place
251
+ # of reply (an answer retried would be 409).
252
+ def answered_wait(id, question_id, start, seconds, answered:)
253
+ head = answered ? { status: "answered" } : { status: "not_pending", answered_here: false }
254
+ head = { **head, session_id: id, id: question_id }
255
+ target = ReplyWait::Target.answer(start)
256
+ result = plain_exchange.wait(id, target, timeout: seconds, **wait_extras)
257
+ if result.status == :canceled
258
+ return answer_wait_error(head, "server_stopping", "chi web is stopping; the answer went in")
259
+ end
260
+
261
+ reply = wait_result_json(result, session_access.parent_strategy(id))
262
+ reply[:token] = SessionAccess::Exchange::Token.dump(id, target) if result.status == :timeout
263
+ json_response(200, { **head, reply: reply })
264
+ rescue ArgumentError => e # deleted while waiting
265
+ answer_wait_error(head, "not_found", e.message)
266
+ rescue SystemCallError, IOError => e
267
+ answer_wait_error(head, "wait_failed", "#{e.class}: #{e.message}")
268
+ end
269
+
270
+ def answer_wait_error(head, error, detail) = json_response(200, { **head, wait_error: { error: error, detail: detail } })
271
+
272
+ # A create's 201 token, for a session started with its first turn
273
+ # (first_turn_id): POST …/wait {token} answers that turn. {} for an
274
+ # idle one.
275
+ def create_token(session)
276
+ turn = session.first_turn_id.to_s
277
+ return {} if turn.empty?
278
+
279
+ start = session_access.prepare_wait(session.id, session: (session if session.is_a?(Session)), created: true)
280
+ target = ReplyWait::Target.first_message(start, nil, direct_turn: turn)
281
+ { token: SessionAccess::Exchange::Token.dump(session.id, target) }
282
+ end
283
+
284
+ def plain_exchange = SessionAccess::Exchange.new(session_access)
285
+
286
+ # The ask's deadline clock (the Exchange's: monotonic seconds).
287
+ def ask_clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
288
+
289
+ def wait_extras = { poll_interval: @wait_poll_interval, cancelled: -> { !@server_running.call } }.compact
290
+ end
291
+ end
292
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../block_fix"
4
+ require_relative "request_body"
5
+
6
+ module Samagotchi
7
+ module Web
8
+ # POST /api/sessions/:id/blocks/fix {turn_id, lang, source, reason},
9
+ # mixed into App: the owner's page asks again, once, for a block it
10
+ # couldn't draw in the newest answer, relayed to the worker's Bridge
11
+ # (Bridge::BlockFixRoute; docs/internals/block-renderers.md, A failed
12
+ # block is asked for again). With web.block_fix off it answers 404, as
13
+ # an unknown route.
14
+ module BlockFixRoutes
15
+ # The worker's answers passed through as they are; any other is 502.
16
+ PASSED = [200, 202].freeze
17
+ REFUSED = [400, 409, 413, 429].freeze
18
+
19
+ private
20
+
21
+ def handle_block_fix(req, id)
22
+ return not_found(path: req.path) unless @block_fix == "auto"
23
+
24
+ body = parse_json(request_body(req, RequestBody::SMALL_BODY_LIMIT))
25
+ return error_response(400, "invalid_json", "invalid JSON body") unless body.is_a?(Hash)
26
+
27
+ fields = body.slice("turn_id", "lang", "source", "reason").transform_keys(&:to_sym)
28
+ request = ->(client) { client.fix_block(turn_id: nil, lang: nil, source: nil, reason: nil, **fields) }
29
+ relay(id, bridge_client(id), request, what: "the fix was not asked for", cant: "fix blocks") do |reply|
30
+ if PASSED.include?(reply.status)
31
+ json_response(reply.status, reply.json || {})
32
+ elsif REFUSED.include?(reply.status)
33
+ error_response(reply.status, reply.json&.dig("error") || "refused", reply_detail(reply, "the fix was refused"))
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -2,8 +2,10 @@
2
2
 
3
3
  require "nokogiri"
4
4
  require "uri"
5
+ require_relative "../block_fix"
5
6
  require_relative "../block_renderers"
6
7
  require_relative "../inline_widgets"
8
+ require_relative "../markdown_parser"
7
9
 
8
10
  module Samagotchi
9
11
  module Web
@@ -57,7 +59,11 @@ module Samagotchi
57
59
  commonmarker_installed? ? TIP : TIP_GEM
58
60
  end
59
61
 
60
- def render(markdown)
62
+ # @param block_fixes [Array<Hash>, nil] the answer's block fix stamp
63
+ # (BlockFix.stamps): a block that is a fix gets data-block-fixed, one
64
+ # whose fix failed data-block-fix-failed. Only an answer's own render
65
+ # (MessageDisplay) passes it.
66
+ def render(markdown, block_fixes: nil)
61
67
  return nil unless available?
62
68
 
63
69
  html = Commonmarker.to_html(markdown.to_s, options: OPTIONS, plugins: {
@@ -68,7 +74,7 @@ module Samagotchi
68
74
  })
69
75
  return nil unless html
70
76
 
71
- sanitize(html, fences(markdown.to_s))
77
+ sanitize(html, fences(markdown.to_s), Array(block_fixes))
72
78
  end
73
79
 
74
80
  private
@@ -76,10 +82,7 @@ module Samagotchi
76
82
  def load_bundled_commonmarker!
77
83
  return @commonmarker_available unless @commonmarker_available.nil?
78
84
 
79
- require "commonmarker"
80
- @commonmarker_available = true
81
- rescue LoadError
82
- @commonmarker_available = false
85
+ @commonmarker_available = MarkdownParser.available?
83
86
  end
84
87
 
85
88
  def commonmarker_installed?
@@ -109,7 +112,7 @@ module Samagotchi
109
112
  # After the walk, which drops every attribute it doesn't know. Blocks and
110
113
  # fences pair by position; a count that differs says the two parses
111
114
  # disagree, and then no block gets one (it shows as source).
112
- def mark_languages(fragment, fences)
115
+ def mark_languages(fragment, fences, block_fixes = [])
113
116
  blocks = fragment.css("pre")
114
117
  return unless blocks.size == fences.size
115
118
 
@@ -118,6 +121,18 @@ module Samagotchi
118
121
 
119
122
  pre["data-lang"] = fence.language
120
123
  mark_widget(pre, fence.literal) if fence.language == InlineWidgets::LANG
124
+ mark_fix(pre, fence, block_fixes) unless block_fixes.empty?
125
+ end
126
+ end
127
+
128
+ # The stamp's word on this block: the fix of a failed one, or one
129
+ # whose fix didn't help. One SHA-256 per fenced block of a stamped answer.
130
+ def mark_fix(pre, fence, block_fixes)
131
+ key = BlockFix.key(fence.language, fence.literal)
132
+ if block_fixes.any? { |entry| entry[:fixed_key] == key }
133
+ pre["data-block-fixed"] = ""
134
+ elsif block_fixes.any? { |entry| entry[:key] == key && entry[:state] == "failed" }
135
+ pre["data-block-fix-failed"] = ""
121
136
  end
122
137
  end
123
138
 
@@ -134,7 +149,7 @@ module Samagotchi
134
149
  pre["data-widget-lenient"] = "" if widget.lenient?
135
150
  end
136
151
 
137
- def sanitize(html, fences)
152
+ def sanitize(html, fences, block_fixes = [])
138
153
  fragment = Nokogiri::HTML5.fragment(html)
139
154
  fragment.traverse do |node|
140
155
  next unless node.element?
@@ -147,7 +162,7 @@ module Samagotchi
147
162
  sanitize_attributes(node)
148
163
  end
149
164
  end
150
- mark_languages(fragment, fences)
165
+ mark_languages(fragment, fences, block_fixes)
151
166
  fragment.to_html
152
167
  end
153
168
 
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../mcp_server/protocol"
4
+ require_relative "../mcp_server/http"
5
+ require_relative "../mcp_server/tools"
6
+ require_relative "../mcp_server/text"
7
+ require_relative "../session_inbox"
8
+ require_relative "ask_routes"
9
+ require_relative "request_body"
10
+
11
+ module Samagotchi
12
+ module Web
13
+ # POST /api/mcp: chi as an MCP server on chi web (McpServer::Http, one
14
+ # JSON answer a POST, each call within McpServer::Tools::SLICE), for an
15
+ # MCP host that speaks HTTP. Behind the gates every owner route has
16
+ # (the Host check, a foreign Origin's 403, the token: none on loopback
17
+ # without web.public_url, Bearer on the LAN or a public URL; a
18
+ # participant's token is refused), with chi web's own {error, detail}
19
+ # bodies there; a tokenless request's 401 adds WWW-Authenticate:
20
+ # Bearer, so a host says it needs a token rather than look for OAuth.
21
+ # GET 405 (no stream), DELETE 200 (a legacy host closing its session).
22
+ # Included in App through SessionAccessRoutes; its helpers
23
+ # (request_body, session_access, live_bridge_client, error_response)
24
+ # and ivars (@manager, @hub, @wait_poll_interval, @server_running)
25
+ # answer. See docs/mcp-server.md.
26
+ module McpRoute
27
+ # GET /api/info's feature: this chi web serves POST /api/mcp.
28
+ FEATURE = "mcp"
29
+ PATH = %r{\A/api/mcp\z}
30
+ # A POST's body cap: a chi_ask prompt at its 16 KiB limit, every byte
31
+ # JSON-escaped (a control character's \u0000 is 6 bytes), plus the
32
+ # envelope, so a host gets the tool's "the message is N bytes" over
33
+ # the limit, not chi web's 413.
34
+ BODY_LIMIT = (6 * SessionInbox::NOTE_MAX_BYTES) + (16 * 1024)
35
+ # App::ROUTES' rows for the path (all :owner).
36
+ ROUTES = [["POST", PATH, :handle_mcp, :owner], ["GET", PATH, :handle_mcp_get, :owner],
37
+ ["DELETE", PATH, :handle_mcp_delete, :owner]].freeze
38
+
39
+ # The tools' backend on chi web: the ask's (its manager and Bridge),
40
+ # whose answer also closes the page's card once the worker took it,
41
+ # as POST …/answer does.
42
+ class McpAccess < AskRoutes::AskAccess
43
+ def initialize(access, hub:, **)
44
+ super(access, **)
45
+ @hub = hub
46
+ end
47
+
48
+ def answer(id, question_id:, **)
49
+ reply = __getobj__.answer(id, question_id: question_id, **)
50
+ @hub&.resolve_question(id, question_id: question_id) if reply&.status == 200
51
+ reply
52
+ end
53
+ end
54
+
55
+ private
56
+
57
+ def handle_mcp(req)
58
+ body = request_body(req, BODY_LIMIT, what: "an MCP request")
59
+ McpServer::Http.new(mcp_protocol).call(req.env, body)
60
+ end
61
+
62
+ def handle_mcp_get(_req)
63
+ text = JSON.generate({ error: "method_not_allowed", detail: "POST an MCP request; this server opens no stream" })
64
+ [405, { "Content-Type" => "application/json", "Allow" => "POST, DELETE", "Content-Length" => text.bytesize.to_s }, [text]]
65
+ end
66
+
67
+ # Nothing is kept for a legacy session id: nothing to end.
68
+ def handle_mcp_delete(_req) = [200, { "Content-Length" => "0" }, []]
69
+
70
+ def mcp_protocol
71
+ bridge = ->(sid) { live_bridge_client(sid, within: McpServer::Tools::CAP) }
72
+ access = McpAccess.new(session_access, hub: @hub, manager: @manager, bridge: bridge, poll_interval: @wait_poll_interval)
73
+ stopping = -> { !@server_running.call }
74
+ exchange = ->(backend) { SessionAccess::Exchange.new(backend, cancelled: stopping) }
75
+ tools = McpServer::Tools.new(access, exchange: exchange, cancelled: stopping)
76
+ McpServer::Protocol.new(tools: tools, instructions: McpServer::Text::INSTRUCTIONS)
77
+ end
78
+
79
+ # The /api/ 401 (App#unauthorized's), with WWW-Authenticate: Bearer
80
+ # on this path.
81
+ def api_unauthorized(req, detail)
82
+ status, headers, body = error_response(401, "unauthorized", detail)
83
+ headers = headers.merge("WWW-Authenticate" => "Bearer") if PATH.match?(req.path_info)
84
+ [status, headers, body]
85
+ end
86
+ end
87
+ end
88
+ end
@@ -3,6 +3,7 @@
3
3
  require_relative "../session"
4
4
  require_relative "../answer_refs"
5
5
  require_relative "../answer_tail"
6
+ require_relative "../block_fix/stamp"
6
7
  require_relative "../context_note"
7
8
  require_relative "../image_store"
8
9
  require_relative "../message_parts"
@@ -223,7 +224,11 @@ module Samagotchi
223
224
  shown = display.is_a?(String) ? Samagotchi::OutputFormatter.strip_markup(display) : ""
224
225
  message[:display] = shown unless shown.strip.empty?
225
226
  rendered = message[:display] || stripped
226
- message[:html] = @markdown_renderer.render(rendered) if markdown && !rendered.empty? && @markdown_renderer.available?
227
+ fixes = Samagotchi::BlockFix.stamps(m)
228
+ message[:html] = @markdown_renderer.render(rendered, block_fixes: fixes) if markdown && !rendered.empty? && @markdown_renderer.available?
229
+ # A block was fixed in it: a reload's drawn turn takes this answer
230
+ # even though what streamed differs (turn_block.js savedAnswer).
231
+ message[:block_fixed] = true if fixes.any? { |entry| entry[:state] == "fixed" }
227
232
  # The refs after_turn hooks attached (AnswerRefs), checked again:
228
233
  # a stored file is never trusted. Never raises.
229
234
  refs = Samagotchi::AnswerRefs.for_display(m[:display_refs] || m["display_refs"], cwd: cwd)
@@ -83,7 +83,7 @@ module Samagotchi
83
83
  # fails for a new one until it is decided here or in EVENTS. Not
84
84
  # named is dropped all the same.
85
85
  DROPPED = %w[
86
- after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn
86
+ after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn block_fix
87
87
  card command_output command_queued command_ran context_added empty_answer_retry
88
88
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
89
89
  llm_context_edited merged_input objectives_updated part_settled participants_changed pending_input_merged plugin_init_finished
@@ -2,14 +2,11 @@ import {
2
2
  listSessions,
3
3
  getSession,
4
4
  sendTurn,
5
- stopTurn,
6
- stopSession,
5
+ stopTurn, stopSession,
7
6
  sessionHolds,
8
7
  stopSessionHolds,
9
8
  restartSession,
10
- deleteSession,
11
- deleteChain,
12
- deletePlan,
9
+ deleteSession, deleteChain, deletePlan,
13
10
  archiveSession,
14
11
  unarchiveSession,
15
12
  sendCommand,
@@ -71,7 +68,8 @@ import { parsePresets } from "./annotate_presets.js";
71
68
  import { createAnnotateBar } from "./annotate_bar.js";
72
69
  import { VERIFY_PRESET, VERIFY_UNAVAILABLE, verifyWorkerUnavailable, withVerify } from "./verify_preset.js";
73
70
  import { actionLine, annotationActions, composerWithAction } from "./annotate_actions.js";
74
- import { createBlockHost } from "./block_host.js";
71
+ import { wireDiagrams } from "./diagram_wiring.js";
72
+ import { wireBlockFix } from "./block_fix.js";
75
73
  import { createWidgetDrawer } from "./inline_widgets.js";
76
74
  import { copyText, installCopy } from "./copy.js";
77
75
  import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
@@ -1224,6 +1222,7 @@ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wra
1224
1222
  syncModelPick: startPage.commandRan,
1225
1223
  objectivesUpdated: (data) => objectives.update(data),
1226
1224
  cardActionFailed: cards.actionFailed,
1225
+ blockFix: (data) => blockFix?.onEvent(data),
1227
1226
  })));
1228
1227
 
1229
1228
  async function refreshTimingFromSession() {
@@ -1543,8 +1542,8 @@ turnRoots().forEach((root) => installCopy(root));
1543
1542
  // chi-ui blocks (inline_widgets.js) are a core drawer, ahead of the bundles'
1544
1543
  // renderers; a picks' Fill reply only fills the composer.
1545
1544
  const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
1546
- createBlockHost({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), openPicture: (p, o) => pictures.open(p, o) });
1547
- window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close()); // a redrawn diagram's old picture
1545
+ wireDiagrams({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), pictures });
1546
+ const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText: () => promptEl.value, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
1548
1547
  // A steps block, a thinking block and the recap open and close by hand
1549
1548
  // with their height animated (details_motion.js), in the history and on
1550
1549
  // the stage.