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
@@ -0,0 +1,285 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "exchange"
4
+ require_relative "exchange/token"
5
+ require_relative "../bridge_client"
6
+ require_relative "../bridge_secret"
7
+ require_relative "../client_id"
8
+ require_relative "../parent_answers_command"
9
+ require_relative "../reply_wait/target"
10
+ require_relative "../session"
11
+ require_relative "../session_inbox"
12
+ require_relative "../turn_flow"
13
+ require_relative "../send_command/parent_gate"
14
+
15
+ module Samagotchi
16
+ module SessionAccess
17
+ # One message in, its answer out, for a thin client (chi web's POST
18
+ # …/ask, plan 2's MCP server): the session located (a chain's newest
19
+ # link, a continue in flight waited for), a running turn's busy check,
20
+ # the wait's start read before the message goes in, the delivery (a
21
+ # continue that took the link meanwhile: located again and sent there),
22
+ # then one slice of the wait. Everything draws on one deadline (+cap+),
23
+ # so the call answers in time for a proxy or a Shortcut; a turn still
24
+ # running then is a Reply with status :timeout and a wait token
25
+ # (Exchange::Token). The waits for a continue end MIN_SLICE before the
26
+ # deadline, so the slice fits; a delivery's own time counts (a slow one
27
+ # leaves a shorter slice, and one past the deadline gets no second
28
+ # delivery). One per call, no state kept after it. It answers
29
+ # values, never an HTTP shape; the backend's errors raise
30
+ # (SessionManager::OwnedByTUI, ArgumentError for a session deleted
31
+ # meanwhile).
32
+ class Ask
33
+ # The answer of a delivered message: +session_id+ where it ran (the
34
+ # chain's newest link), +asked+ the full id given, +result+ the
35
+ # ReplyWait::Result, +token+ for a :timeout (the next wait's).
36
+ # #answer's: +answered_here+ false when the question was no longer
37
+ # open (answered elsewhere first, or a newer one waits): what came
38
+ # next is still waited for, as chi answer does. +rebound+: a request_id
39
+ # whose turn was already known, so nothing was sent this time (the
40
+ # first ask's turn waited on again).
41
+ Reply = Data.define(:session_id, :asked, :result, :token, :answered_here, :rebound) do
42
+ def initialize(session_id:, asked:, result:, token:, answered_here: true, rebound: false) = super
43
+ end
44
+
45
+ # The line ran as a session command (/model x): no reply comes. A
46
+ # /continue yes with an offer standing (an idle session's continue
47
+ # question, its worker running) is a Reply instead: it waits on the
48
+ # continued turn (#continue_follows?).
49
+ Ran = Data.define(:session_id)
50
+
51
+ # Nothing went in. +kind+ :unknown (+error+ the resolve's
52
+ # ArgumentError), :continuing (a continue in flight past the wait,
53
+ # +message+ its refusal), :busy (+busy+ the SendCommand::Busy: a turn
54
+ # runs and queue was false, or a question waits) or :undelivered
55
+ # (+result+ the refused DeliverResult) or :canceled (+cancelled+ turned
56
+ # true before anything was sent: chi web stopping). #agent_line's
57
+ # :parent_refused (+message+ why). #answer's (+message+ each):
58
+ # :no_question (none of that id waits and nothing runs), :not_live (no
59
+ # worker runs it), :bridge_secret, :not_dismissable, :invalid_answer
60
+ # (the Bridge refused the selection), :parent_refused (the worker's
61
+ # parent_answers), :late (the worker didn't take it in time),
62
+ # :stale_worker (an older worker without the answer route), :failed.
63
+ Refused = Data.define(:kind, :session_id, :busy, :result, :error, :message) do
64
+ def initialize(kind:, session_id: nil, busy: nil, result: nil, error: nil, message: nil) = super
65
+ end
66
+
67
+ # The shortest wait slice, however little of the cap is left.
68
+ MIN_SLICE = 1.0
69
+
70
+ # @param access [SessionAccess::Local, #deliver_turn] the backend (chi
71
+ # web's wraps Local to deliver through its own manager and Bridge)
72
+ # @param exchange [Exchange] over the same backend
73
+ # @param clock [#call] monotonic seconds (the exchange's own by default)
74
+ def initialize(access, exchange:, clock: nil)
75
+ @access = access
76
+ @exchange = exchange
77
+ @clock = clock || -> { exchange.now }
78
+ end
79
+
80
+ # @param given [String] an id or a prefix
81
+ # @param client_id [String] who sends it (ClientId)
82
+ # @param queue [Boolean] a running session queues it as its own turn;
83
+ # false refuses one (:busy)
84
+ # @param timeout [Numeric] the most seconds for the wait's slice
85
+ # @param cap [Numeric] the most seconds for the whole call
86
+ # @param continuing_wait [Numeric] the most seconds a continue that
87
+ # took the link is waited for (Exchange::CONTINUING_WAIT)
88
+ # @param cancelled [#call, nil] true stops the wait (status :canceled);
89
+ # before the delivery, the call (Refused :canceled). The exchange's
90
+ # own cancelled: (the same) cuts its waits for a continue
91
+ # @param request_id [String, nil] the client's key for this ask (a
92
+ # message, never a command): its turn's enqueued id is
93
+ # SessionInbox.enqueued_id_for("ask:" + it). A turn of that id the
94
+ # session knows (running, queued, ended: ReplyWait.known_turn?) is
95
+ # waited on again, nothing sent (Reply rebound), unless it only waits
96
+ # as an input file with no worker running (#waiting_turn?); else the
97
+ # delivery carries the id, which the Bridge dedupes
98
+ # @return [Reply, Ran, Refused]
99
+ def call(given, prompt:, client_id:, queue:, timeout:, cap:, continuing_wait: Exchange::CONTINUING_WAIT,
100
+ cancelled: nil, request_id: nil)
101
+ enqueued_id = SessionInbox.enqueued_id_for("ask:#{request_id}") if request_id
102
+ deadline = @clock.call + cap
103
+ # Everything before the wait ends by here, so its MIN_SLICE fits.
104
+ ready_by = deadline - MIN_SLICE
105
+ found = @exchange.locate(given, deadline: ready_by)
106
+ at = found.target if found.is_a?(Exchange::Located)
107
+ return Refused.new(kind: :canceled, session_id: at&.id || found.asked) if cancelled&.call
108
+ return unsent(found, nil) if found.is_a?(Exchange::Unsent)
109
+
110
+ follow_until = nil
111
+ loop do
112
+ return Refused.new(kind: :canceled, session_id: at.id) if cancelled&.call
113
+
114
+ session = @access.show(at.id)
115
+ start = (@access.prepare_wait(at.id, session: session, turn: enqueued_id) if enqueued_id)
116
+ # A turn known only as an input file no worker reads is sent again
117
+ # (with E: the worker runs it once), so the delivery wakes one.
118
+ if start&.known_turn && (start.live || !@access.waiting_turn?(at.id, enqueued_id))
119
+ # chi send --wait --turn E's binding, queued as the first copy was
120
+ # sent (a queue never merges: no merge fallback onto another turn).
121
+ target = ReplyWait::Target.wait_only(start, requested: enqueued_id).with(queued: queue)
122
+ return wait(at, target, slice: slice(timeout, deadline), cancelled: cancelled, rebound: true)
123
+ end
124
+
125
+ busy = @access.busy(at.id, queue: queue, session: session)
126
+ return Refused.new(kind: :busy, session_id: at.id, busy: busy) if busy
127
+
128
+ start ||= @access.prepare_wait(at.id, session: session)
129
+ more = enqueued_id ? { enqueued_id: enqueued_id } : {}
130
+ result = @exchange.attempt(at, prompt, client_id: client_id, queue: queue, **more).result
131
+ if result.continued?
132
+ follow_until ||= [@clock.call + continuing_wait, ready_by].min
133
+ again = @exchange.relocate(at, follow_until, bounded: true)
134
+ return Refused.new(kind: :canceled, session_id: at.id) if cancelled&.call
135
+ return Refused.new(kind: :continuing, session_id: at.id, message: result.refusal_text) unless again
136
+ return unsent(again, at.id) if again.is_a?(Exchange::Unsent)
137
+
138
+ at = again.target
139
+ next
140
+ end
141
+ return Refused.new(kind: :undelivered, session_id: at.id, result: result) unless result.accepted?
142
+
143
+ if result.command?
144
+ return Ran.new(session_id: at.id) unless continue_follows?(prompt, start)
145
+
146
+ # The continue turn runs under the offered turn's id (own_turn),
147
+ # as chi answer follows it: the worker's ack is not read.
148
+ return wait(at, ReplyWait::Target.answer(start), slice: slice(timeout, deadline), cancelled: cancelled)
149
+ end
150
+
151
+ target = @exchange.bind(start, result, queue: queue)
152
+ return wait(at, target, slice: slice(timeout, deadline), cancelled: cancelled)
153
+ end
154
+ end
155
+
156
+ # What a parent agent's line (an MCP host's, chi send's over HTTP) is
157
+ # held to, with no read of this process (an ENV marker, a tty): a
158
+ # /continue yes always goes in as chi answer's (the worker holds it
159
+ # to guardrails.parent_answers only then), anything else as chi
160
+ # send's; refused first when the parent policy refuses that continue,
161
+ # or when it is a /parent-answers line loosening a target's own value
162
+ # (Web::SessionCreate#parent_gate's two checks, for those ids).
163
+ # @param session [Session, Array<Session>, nil] the targets (the
164
+ # session asked and its chain's newest link); none: config.yml's
165
+ # value alone (fail closed)
166
+ # @return [String, Refused] the client_id to send as, or why not
167
+ def agent_line(prompt, session:)
168
+ sessions = Array(session).compact
169
+ values = sessions.empty? ? [nil] : sessions.map(&:parent_answers)
170
+ continue = TurnFlow.continue_yes?(prompt)
171
+ refusal = SendCommand::ParentGate.continue_refusal_for(values) if continue
172
+ refusal ||= ParentAnswersCommand::REFUSED if SendCommand::ParentGate.loosens_any?(prompt, values)
173
+ return Refused.new(kind: :parent_refused, session_id: sessions.first&.id, message: refusal) if refusal
174
+
175
+ continue ? ClientId::CLI_ANSWER : ClientId::CLI_SEND
176
+ end
177
+
178
+ # The answer to the question session +id+ waits on, then one slice of
179
+ # the wait for what comes next (AnswerCommand's sequence, as values):
180
+ # a question no longer open is not answered but still waited past
181
+ # (Reply answered_here: false) while the session runs.
182
+ # @param id [String] the session's full id
183
+ # @param selected [Array<String>] the option labels
184
+ # @param freeform [String, nil]
185
+ # @param timeout [Numeric] the wait's slice
186
+ # @param cap [Numeric, nil] the most seconds for the whole call (an
187
+ # MCP host's limit): the post gets what is left but MIN_SLICE, the
188
+ # wait the rest (#slice); nil: the post's own limits, then +timeout+
189
+ # @return [Reply, Refused]
190
+ def answer(id, question_id:, selected:, freeform:, client_id:, timeout:, cap: nil, cancelled: nil)
191
+ deadline = @clock.call + cap if cap
192
+ qid = question_id.to_s
193
+ session = @access.show(id)
194
+ pending = session.pending_question
195
+ open = pending && pending.id.to_s == qid
196
+ if !open && session.status != Session::STATUS_RUNNING
197
+ return Refused.new(kind: :no_question, session_id: id, message: "no question #{qid} waits in #{id[0, 8]}; nothing to answer")
198
+ end
199
+
200
+ start = @access.prepare_wait(id, session: session, question_id: qid)
201
+ answered_here = false
202
+ if open
203
+ within = (deadline - MIN_SLICE - @clock.call).clamp(MIN_SLICE..) if deadline
204
+ posted = post_answer(id, qid, selected, freeform, client_id, within)
205
+ return posted if posted.is_a?(Refused)
206
+
207
+ answered_here = posted
208
+ end
209
+ target = ReplyWait::Target.answer(start)
210
+ more = cancelled ? { cancelled: cancelled } : {}
211
+ result = @exchange.wait(id, target, timeout: deadline ? slice(timeout, deadline) : timeout, **more)
212
+ token = Exchange::Token.dump(id, target) if result.status == :timeout
213
+ Reply.new(session_id: id, asked: id, result: result, token: token, answered_here: answered_here)
214
+ end
215
+
216
+ # The words for an answer the worker didn't take in time
217
+ # (AnswerCommand's own, copied).
218
+ LATE_WORDS = "the worker did not take the answer in time; the question is still open: try again"
219
+
220
+ private
221
+
222
+ # The answer posted, its reply read as AnswerCommand#post reads it.
223
+ # @return [Boolean, Refused] true answered, false no longer open (409)
224
+ def post_answer(id, qid, selected, freeform, client_id, within)
225
+ more = within ? { within: within } : {}
226
+ reply = @access.answer(id, question_id: qid, selected: selected, freeform: freeform, client_id: client_id, **more)
227
+ return not_live(id) unless reply
228
+ return answer_refused(:bridge_secret, id, BridgeSecret.refused(id, via: @access.invocation)) if reply.secret_refused?
229
+
230
+ detail = reply.json&.dig("detail")
231
+ case reply.status
232
+ when 200 then true
233
+ when 409
234
+ return answer_refused(:not_dismissable, id, detail.to_s) if reply.json&.dig("error") == "not_dismissable"
235
+
236
+ false
237
+ when 400 then answer_refused(:invalid_answer, id, detail || "the worker refused the answer")
238
+ when 403 then answer_refused(:parent_refused, id, detail || "the worker refused that option: deny it, and tell your user")
239
+ when 408 then answer_refused(:late, id, LATE_WORDS)
240
+ when 404
241
+ return not_live(id) if reply.json&.dig("error") == "unknown_session"
242
+
243
+ answer_refused(:stale_worker, id, BridgeClient.stale_worker_message(id, cant: "take an answer", via: @access.invocation))
244
+ else answer_refused(:failed, id, "the worker answered #{reply.status}: #{detail || reply.body}")
245
+ end
246
+ rescue Errno::ETIMEDOUT
247
+ answer_refused(:late, id, LATE_WORDS)
248
+ rescue SystemCallError, IOError, SocketError => e
249
+ answer_refused(:failed, id, "#{e.class}: #{e.message}")
250
+ end
251
+
252
+ def not_live(id) = answer_refused(:not_live, id, "no worker runs session #{id[0, 8]}: the question went with it; send the task again")
253
+
254
+ def answer_refused(kind, id, message) = Refused.new(kind: kind, session_id: id, message: message)
255
+
256
+ # A /continue yes the worker ran as a command, on a session idle with
257
+ # its continue offer standing (start's own_turn, ReplyWait.own_turn)
258
+ # and a worker running it: the offer lives only in that worker's
259
+ # memory, so with none (a new one says nothing to continue) a wait
260
+ # would hand out tokens with no end.
261
+ def continue_follows?(prompt, start)
262
+ TurnFlow.continue_yes?(prompt) && !start.running && start.live && !start.own_turn.to_s.empty?
263
+ end
264
+
265
+ def wait(at, target, slice:, cancelled:, rebound: false)
266
+ more = cancelled ? { cancelled: cancelled } : {}
267
+ result = @exchange.wait(at.id, target, timeout: slice, **more)
268
+ token = Exchange::Token.dump(at.id, target) if result.status == :timeout
269
+ Reply.new(session_id: at.id, asked: at.asked, result: result, token: token, rebound: rebound)
270
+ end
271
+
272
+ # The wait's slice: +timeout+, cut to the time the cap leaves, never
273
+ # under MIN_SLICE.
274
+ def slice(timeout, deadline) = [timeout, deadline - @clock.call].min.clamp(MIN_SLICE..)
275
+
276
+ def unsent(found, session_id)
277
+ if found.reason == :continuing
278
+ Refused.new(kind: :continuing, session_id: session_id || found.asked, message: found.message)
279
+ else
280
+ Refused.new(kind: :unknown, session_id: session_id, error: found.error, message: found.message)
281
+ end
282
+ end
283
+ end
284
+ end
285
+ end
@@ -143,6 +143,11 @@ module Samagotchi
143
143
  "share revoke" => SUPPORTED,
144
144
  "share revoke --all" => SUPPORTED,
145
145
 
146
+ # chi as an MCP server (docs/mcp-server.md): its tools over the
147
+ # remote's chi web, as chi send and chi answer.
148
+ "mcp" => SUPPORTED,
149
+ "mcp serve" => SUPPORTED,
150
+
146
151
  "broadcast" => LOCAL_ONLY
147
152
  }.freeze
148
153
 
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../../session"
5
+ require_relative "../../reply_wait/target"
6
+
7
+ module Samagotchi
8
+ module SessionAccess
9
+ class Exchange
10
+ # A reply wait as one string a thin client carries between two
11
+ # POST …/wait calls: "w1." and the url-safe base64 (no padding) of
12
+ # {s: session_id, t: turn, r: report_turn_id, q: queued, e:
13
+ # ended_before, c: cursor, b: baseline ({messages, question_id,
14
+ # last_turn}) or nil, g: owner_grace}.
15
+ #
16
+ # Unsigned on purpose: every field is one the owner may already put
17
+ # in a POST …/wait body (only the owner's routes take a token);
18
+ # +cursor+ is only compared as a string and never becomes a path, and
19
+ # +turn+ reaches paths only through the ENQUEUED_ID_NAME-guarded
20
+ # helpers (SessionInbox). A token says nothing a body couldn't.
21
+ module Token
22
+ PREFIX = "w1."
23
+ KEYS = %w[s t r q e c b g].freeze
24
+ STRINGS = %w[t r c].freeze
25
+ FLAGS = %w[q e].freeze
26
+ BASELINE_FIELDS = { "messages" => Integer, "question_id" => String, "last_turn" => String }.freeze
27
+ BASELINE_WORDS = "baseline is {messages, question_id, last_turn}"
28
+
29
+ # Anything that isn't a token this chi made: its message says what.
30
+ class Invalid < StandardError; end
31
+
32
+ module_function
33
+
34
+ # @param target [ReplyWait::Target]
35
+ # @return [String]
36
+ def dump(session_id, target)
37
+ fields = { s: session_id, t: target.turn, r: target.report_turn_id, q: target.queued == true,
38
+ e: target.ended_before == true, c: target.cursor, b: target.baseline&.to_h, g: target.owner_grace }
39
+ PREFIX + [JSON.generate(fields)].pack("m0").tr("+/", "-_").delete("=")
40
+ end
41
+
42
+ # @return [Array(String, ReplyWait::Target)] the session id and the wait
43
+ # @raise [Invalid]
44
+ def load(string)
45
+ raise Invalid, "not a wait token" unless string.is_a?(String) && string.start_with?(PREFIX)
46
+
47
+ fields = decode(string.delete_prefix(PREFIX))
48
+ raise Invalid, "a wait token names unknown fields" unless (fields.keys - KEYS).empty?
49
+
50
+ [session_of(fields["s"]), target_of(fields)]
51
+ end
52
+
53
+ # A wait body's or a token's baseline: nil, or a Baseline from
54
+ # exactly its fields, each of its type or null.
55
+ # @return [ReplyWait::Baseline, nil]
56
+ # @raise [Invalid] BASELINE_WORDS
57
+ def baseline(raw)
58
+ return nil if raw.nil?
59
+ unless raw.is_a?(Hash) && raw.all? { |key, value| BASELINE_FIELDS.key?(key) && (value.nil? || value.is_a?(BASELINE_FIELDS[key])) }
60
+ raise Invalid, BASELINE_WORDS
61
+ end
62
+
63
+ ReplyWait::Baseline.new(**raw.transform_keys(&:to_sym))
64
+ end
65
+
66
+ def decode(text)
67
+ raise Invalid, "a wait token is url-safe base64" unless text.match?(/\A[A-Za-z0-9_-]+\z/)
68
+
69
+ padded = text.tr("-_", "+/") + ("=" * ((4 - (text.length % 4)) % 4))
70
+ fields = JSON.parse(padded.unpack1("m0"))
71
+ raise Invalid, "a wait token holds an object" unless fields.is_a?(Hash)
72
+
73
+ fields
74
+ rescue ArgumentError, JSON::ParserError
75
+ raise Invalid, "not a wait token"
76
+ end
77
+
78
+ def session_of(id)
79
+ raise Invalid, "a wait token names its session" unless id.is_a?(String) && Session.valid_id?(id)
80
+
81
+ id
82
+ end
83
+
84
+ def target_of(fields)
85
+ STRINGS.each do |key|
86
+ raise Invalid, "a wait token's #{key} is a string" unless fields[key].nil? || fields[key].is_a?(String)
87
+ end
88
+ FLAGS.each do |key|
89
+ raise Invalid, "a wait token's #{key} is true or false" unless [nil, true, false].include?(fields[key])
90
+ end
91
+ grace = fields["g"]
92
+ raise Invalid, "a wait token's g is positive seconds" unless grace.nil? || (grace.is_a?(Numeric) && grace.positive?)
93
+
94
+ ReplyWait::Target.new(turn: fields["t"], report_turn_id: fields["r"], queued: fields["q"] == true,
95
+ ended_before: fields["e"] == true, cursor: fields["c"], baseline: baseline(fields["b"]),
96
+ owner_grace: grace)
97
+ end
98
+ end
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../delivery"
4
+ require_relative "../session"
5
+ require_relative "../session_inbox"
6
+ require_relative "../reply_wait/target"
7
+
8
+ module Samagotchi
9
+ module SessionAccess
10
+ # The stateless pieces of "send one message and bind its wait", over a
11
+ # SessionAccess backend (Local or Remote: only their public methods),
12
+ # for every front that sends: chi send (SendCommand, which keeps its
13
+ # retry loop and its lines), chi answer's wait (CLI::ParentWait) and chi
14
+ # web's ask (SessionAccess::Ask). It prints nothing, knows no command
15
+ # name, keeps no state between calls (chi web builds one per request),
16
+ # never retries, and lets the backend's errors raise; it answers values.
17
+ # See docs/internals/remote-sessions.md (Exchange).
18
+ class Exchange
19
+ # How long a send to a link being continued waits for the new link to
20
+ # be saved, and how often it asks again (SendCommand's own constants
21
+ # have the same values, which its specs stub).
22
+ CONTINUING_WAIT = 10.0
23
+ CONTINUING_POLL = 0.2
24
+
25
+ # +given+ named a session: +target+ where input for it goes (a
26
+ # SessionInbox::Resolved), +waited+ whether a continue in flight was
27
+ # waited for on the way.
28
+ Located = Data.define(:target, :waited)
29
+
30
+ # +given+ named no session to send to: +reason+ :continuing (a
31
+ # continue of +asked+, the full id, still in flight past the wait;
32
+ # +message+ its refusal) or :unknown (no such session, or a prefix of
33
+ # several: +error+ the ArgumentError, a Session::AmbiguousId for the
34
+ # latter; +message+ its message).
35
+ Unsent = Data.define(:reason, :message, :asked, :error) do
36
+ def initialize(reason:, message:, asked: nil, error: nil) = super
37
+ end
38
+
39
+ # One delivery made (#attempt): the session as read for it, its
40
+ # +owner+ then, whether it was +running+, the +delivery+ asked for, the
41
+ # image +refs+ copied in and the backend's DeliverResult (+result+:
42
+ # accepted or not, continued or not).
43
+ Attempted = Data.define(:target, :session, :owner, :running, :delivery, :refs, :result)
44
+
45
+ # The caller's check refused the message before anything was sent.
46
+ Stopped = Data.define(:target, :refusal)
47
+
48
+ # @param access [#resolve, #head, #show, #owner, #deliver_turn, #wait_reply] a SessionAccess backend
49
+ # @param pause [#call] sleeps between two looks at a continue in flight
50
+ # @param continuing_wait [Numeric] seconds #locate waits for one
51
+ # @param continuing_poll [Numeric] seconds between two looks
52
+ # @param clock [#call] monotonic seconds
53
+ # @param cancelled [#call] true ends a wait for a continue at the next
54
+ # look (chi web stopping): #locate answers Unsent, #relocate nil
55
+ def initialize(access, pause: ->(seconds) { sleep(seconds) }, continuing_wait: CONTINUING_WAIT,
56
+ continuing_poll: CONTINUING_POLL, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) },
57
+ cancelled: -> { false })
58
+ @access = access
59
+ @pause = pause
60
+ @continuing_wait = continuing_wait
61
+ @continuing_poll = continuing_poll
62
+ @clock = clock
63
+ @cancelled = cancelled
64
+ end
65
+
66
+ # +given+'s session (an id or a prefix), then where input for it goes
67
+ # (the backend's #head): a continued session's chain's newest link. A
68
+ # continue of it in flight (the new link not saved yet) is asked again
69
+ # for up to continuing_wait, then refused; the old link is never
70
+ # named (a send would un-archive it beside the new one).
71
+ # @param deadline [Numeric, nil] this clock's seconds the wait for a
72
+ # continue ends by, if before continuing_wait (an ask's one deadline)
73
+ # @return [Located, Unsent]
74
+ def locate(given, deadline: nil)
75
+ id = @access.resolve(given)
76
+ head = @access.head(id)
77
+ deadline = [@clock.call + @continuing_wait, deadline].compact.min
78
+ waited = head.continuing?
79
+ while head.continuing? && @clock.call < deadline && !@cancelled.call
80
+ pause_until(deadline)
81
+ head = @access.head(id)
82
+ end
83
+ return Unsent.new(reason: :continuing, message: head.continuing_refusal, asked: id) if head.continuing?
84
+
85
+ Located.new(target: head, waited: waited)
86
+ rescue ArgumentError => e
87
+ Unsent.new(reason: :unknown, message: e.message, error: e)
88
+ end
89
+
90
+ # +refused+'s id (its +asked+) located again after a continue took
91
+ # its link (a DeliverResult#continued?), pausing between looks while
92
+ # it still names that link, until +deadline+ (this clock's seconds).
93
+ # @param bounded [Boolean] each look's own wait for a continue ends by
94
+ # +deadline+ too (an ask's one deadline); false, it may wait its
95
+ # continuing_wait past it (chi send's)
96
+ # @yieldparam located [Located] each look that waited on a continue
97
+ # (#locate's waited), whichever link it named
98
+ # @return [Located, Unsent, nil] nil: out of time
99
+ def relocate(refused, deadline, bounded: false)
100
+ while @clock.call < deadline && !@cancelled.call
101
+ pause_until(deadline)
102
+ again = locate(refused.asked, deadline: (deadline if bounded))
103
+ return again unless again.is_a?(Located)
104
+
105
+ yield again if block_given? && again.waited
106
+ next if again.target.id == refused.id
107
+
108
+ return again
109
+ end
110
+ nil
111
+ end
112
+
113
+ # One delivery of +prompt+ to +target+: the session read, +check+
114
+ # (a String refuses: nothing is sent), its owner, the images copied
115
+ # in, then the turn. +queue+ always goes as a queue, idle or not;
116
+ # +cut+ asks a running turn for a cut (an idle session's is an
117
+ # ordinary message). No retry and no discard: a continued result is
118
+ # returned as is, and the caller takes its refs back and relocates.
119
+ # @param images [#upload, nil] answers upload(id) with the refs a turn
120
+ # takes (nil: none)
121
+ # @param check [#call, nil] called with the session read: a refusal
122
+ # String, or nil to go on
123
+ # @param enqueued_id [String, nil] the turn's id, the caller's (an
124
+ # ask's request_id): passed to deliver_turn only when given
125
+ # @return [Attempted, Stopped]
126
+ def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil, enqueued_id: nil)
127
+ id = target.id
128
+ session = @access.show(id)
129
+ if check && (refusal = check.call(session))
130
+ return Stopped.new(target: target, refusal: refusal)
131
+ end
132
+
133
+ owner = @access.owner(id)
134
+ running = owner && session.status == Session::STATUS_RUNNING
135
+ refs = images ? images.upload(id) : []
136
+ delivery = if queue then Delivery::QUEUE
137
+ elsif cut && running then Delivery::CUT
138
+ end
139
+ more = enqueued_id ? { enqueued_id: enqueued_id } : {}
140
+ result = @access.deliver_turn(id, prompt: prompt, client_id: client_id, images: refs, delivery: delivery,
141
+ follow: target.via != :pinned, **more)
142
+ Attempted.new(target: target, session: session, owner: owner, running: running, delivery: delivery, refs: refs,
143
+ result: result)
144
+ end
145
+
146
+ # The wait for an accepted message's own turn (ReplyWait::Target.message).
147
+ # @param start [WaitStart] prepare_wait's, read before it went in
148
+ def bind(start, result, queue:) = ReplyWait::Target.message(start, result, queue: queue)
149
+
150
+ # The backend's wait for what +target+ binds: the result's turn_id is
151
+ # the target's report_turn_id whenever that is known (even when the
152
+ # wait took the next reply), its text UTF-8.
153
+ # @param more [Hash] passed on (cancelled: for a Local backend)
154
+ # @return [ReplyWait::Result]
155
+ # @raise [ArgumentError] the session is gone
156
+ def wait(id, target, timeout:, poll_interval: nil, **more)
157
+ options = { timeout: timeout, **more }
158
+ options[:poll_interval] = poll_interval if poll_interval
159
+ result = @access.wait_reply(id, **target.to_h, **options)
160
+ report_turn_id = target.report_turn_id
161
+ result.turn_id = report_turn_id if report_turn_id && !report_turn_id.to_s.empty?
162
+ result.text = result.text&.dup&.force_encoding(Encoding::UTF_8)&.scrub
163
+ result
164
+ end
165
+
166
+ # This exchange's clock, for a caller's deadline (#relocate's).
167
+ def now = @clock.call
168
+
169
+ private
170
+
171
+ # One pause between two looks: continuing_poll, or less when
172
+ # +deadline+ comes first.
173
+ def pause_until(deadline) = @pause.call([@continuing_poll, deadline - @clock.call].min)
174
+ end
175
+ end
176
+ end
@@ -92,6 +92,12 @@ module Samagotchi
92
92
  # @return [OwnerLock::Owner, nil] the worker or one-turn chi run that owns it
93
93
  def owner(id) = SessionManager.session_owner(id, **dir)
94
94
 
95
+ # Whether +turn+ (an enqueued id) waits as an unclaimed input file of
96
+ # session +id+ (Ask's request_id check: such a turn with no worker
97
+ # running is delivered again, which wakes one; the worker runs the id
98
+ # once). This machine's only: Remote never takes a request_id.
99
+ def waiting_turn?(id, turn) = !SessionInbox.waiting_input(session_dir(id), turn).nil?
100
+
95
101
  # SessionManager.session_rows: the SessionRows chi sessions list
96
102
  # prints and chi note --all reaches (chi web's summaries route answers
97
103
  # their #to_summary_h).
@@ -191,9 +197,18 @@ module Samagotchi
191
197
  # @return [SessionManager::DeliverResult]
192
198
  # @raise [SessionManager::OwnedByTUI] a one-turn chi run owns it
193
199
  # @param follow [Boolean] +id+ is the head #head resolved (SessionManager.deliver_turn's follow:)
194
- def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false)
200
+ # @param manager [#resume_session, nil] the manager that starts its
201
+ # worker; nil: SessionManager's own default
202
+ # @param bridge [#call, nil] the worker's Bridge client (chi web's
203
+ # live_bridge_client: POST …/ask delivers as POST …/turn does); nil:
204
+ # SessionManager's own wait
205
+ # @param enqueued_id [String, nil] the turn's id (an ask's request_id's);
206
+ # nil: SessionManager mints one
207
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil,
208
+ enqueued_id: nil)
209
+ routing = { manager: manager, bridge: bridge, enqueued_id: enqueued_id }.compact
195
210
  SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
196
- follow: follow, **dir)
211
+ follow: follow, **routing, **dir)
197
212
  end
198
213
 
199
214
  # @return [NoteDelivery::Result]
@@ -266,11 +281,16 @@ module Samagotchi
266
281
 
267
282
  # The answer posted to the session's worker (its Bridge), once more
268
283
  # after a 408.
284
+ # @param within [Numeric, nil] the most seconds for it all (an MCP
285
+ # call's, under its host's limit): each try's read timeout is cut
286
+ # to it, and a 408 is tried again only when a whole try still fits
269
287
  # @return [BridgeClient::Response, nil] the Bridge's reply; nil when
270
288
  # no worker runs it
271
289
  # @raise [SystemCallError, IOError, SocketError] the worker went away
272
- def answer(id, question_id:, selected:, freeform:, client_id:)
273
- on_worker(id) { |client| client.answer(id: question_id, selected: selected, freeform: freeform, client_id: client_id) }
290
+ def answer(id, question_id:, selected:, freeform:, client_id:, within: nil)
291
+ on_worker(id, within: within) do |client|
292
+ client.answer(id: question_id, selected: selected, freeform: freeform, client_id: client_id)
293
+ end
274
294
  end
275
295
 
276
296
  # The question dismissed on the session's worker; as #answer.
@@ -629,15 +649,23 @@ module Samagotchi
629
649
 
630
650
  # The block's post to the session's live worker, again on a 408 (the
631
651
  # worker didn't take it in time).
632
- def on_worker(id)
633
- client = WorkerLink.client(id, session_dir: session_dir(id)) or return nil
652
+ # The shortest read timeout a cut try gets (#on_worker's within:).
653
+ MIN_TRY = 1.0
654
+
655
+ def on_worker(id, within: nil)
656
+ limit = within ? within.to_f.clamp(MIN_TRY, BridgeClient::READ_TIMEOUT.to_f) : BridgeClient::READ_TIMEOUT
657
+ client = WorkerLink.client(id, session_dir: session_dir(id), read_timeout: limit) or return nil
658
+ ends = monotonic + within if within
634
659
  reply = nil
635
660
  2.times do
636
661
  reply = yield client
637
662
  break unless reply.status == 408
663
+ break if ends && monotonic + limit > ends
638
664
  end
639
665
  reply
640
666
  end
667
+
668
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
641
669
  end
642
670
  end
643
671
  end
@@ -449,8 +449,11 @@ module Samagotchi
449
449
 
450
450
  # The answer, through chi web to the session's worker. chi web's
451
451
  # answers mapped back to the Bridge's own (AnswerCommand reads those).
452
+ # @param within [nil, Numeric] not cut here: chi web's route bounds its
453
+ # own tries, and a request cut short might still have answered (Local's
454
+ # cut is for an MCP host's 60 s limit on HTTP; this runs under stdio)
452
455
  # @return [BridgeClient::Response, nil] nil when no worker runs it
453
- def answer(id, question_id:, selected:, freeform:, client_id:)
456
+ def answer(id, question_id:, selected:, freeform:, client_id:, within: nil)
454
457
  bridge_reply(request(:post, "#{session_path(id)}/answer",
455
458
  body: { id: question_id, selected: selected, freeform: freeform, client_id: client_id }))
456
459
  end