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,392 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/wait"
4
+ require "socket"
5
+ require "uri"
6
+ require_relative "../log"
7
+
8
+ module Samagotchi
9
+ module Plugin
10
+ # ctx.sign_in's flow (docs/plugins.md, Sign-in): send the session's owner
11
+ # to an address, get back the address the browser was sent to. Core
12
+ # knows nothing of OAuth beyond one check: the address the bundle builds
13
+ # must have a `state` query parameter (#started refuses one without: any
14
+ # local process or web page could finish it), and a callback whose
15
+ # `state` differs is ignored and the wait goes on.
16
+ #
17
+ # The browser comes back to a Listener on 127.0.0.1 (#redirect_uri), or
18
+ # the user pastes the address it ended on with /callback (#offer). The
19
+ # first callback that passes settles it :done; #wait returns its query.
20
+ # It also ends :timed_out (its deadline), :cancelled (#cancel, or the
21
+ # +cancel+ controller the bundle passed: a turn's Stop) or :stopped (the
22
+ # worker leaving, #stop): +on_settle+ hears each, once.
23
+ class SignIn
24
+ OUTCOMES = %i[done timed_out cancelled stopped].freeze
25
+ TIMEOUTS = (60..900)
26
+ DEFAULT_TIMEOUT = 300
27
+ DEFAULT_PATH = "/callback"
28
+ # How often a waiting thread or the listener looks at the deadline
29
+ # with nothing else to wake it, in seconds.
30
+ TICK = 1.0
31
+
32
+ # The card that replaces a flow's when it ends without a callback.
33
+ ENDED_TITLES = { timed_out: "Sign-in timed out", cancelled: "Sign-in cancelled", stopped: "Sign-in cancelled" }.freeze
34
+
35
+ # The card's line for a browser on another device.
36
+ PASTE_LINE = "If the browser ends on a page that doesn't load, copy that page's address and run " \
37
+ "`/callback <address>`."
38
+
39
+ attr_reader :title, :button, :card_id, :redirect_uri, :address, :bundle
40
+
41
+ # A flow that asks no one (a one-shot run, a stream hook's handler):
42
+ # already :stopped, no card, no port.
43
+ def self.stopped(bundle:, title:)
44
+ new(bundle: bundle, title: title, button: nil, timeout: DEFAULT_TIMEOUT, listener: nil).tap do |flow|
45
+ flow.instance_variable_set(:@outcome, :stopped)
46
+ end
47
+ end
48
+
49
+ # @raise [ArgumentError] a timeout outside TIMEOUTS, a bad path, a
50
+ # cancel: that isn't a controller
51
+ def self.check_options!(timeout:, path:, cancel: nil)
52
+ unless cancel.nil? || cancel.respond_to?(:cancelled?)
53
+ raise ArgumentError, "ctx.sign_in's cancel: is a Samagotchi::CancellationController (ctx.cancel_controller) or nil"
54
+ end
55
+ unless timeout.is_a?(Numeric) && TIMEOUTS.cover?(timeout)
56
+ raise ArgumentError, "ctx.sign_in's timeout: is #{TIMEOUTS.min}..#{TIMEOUTS.max} seconds"
57
+ end
58
+ return if path.is_a?(String) && path.match?(%r{\A/[A-Za-z0-9._~/-]*\z})
59
+
60
+ raise ArgumentError, "ctx.sign_in's path: is an absolute path like /callback"
61
+ end
62
+
63
+ # The fields of the card that replaces +flow+'s when it ended as
64
+ # +outcome+ without a callback; nil for :done (the bundle shows its
65
+ # result) or a flow with no card.
66
+ # @return [Hash, nil] Engine#show_card's keywords, the source left out
67
+ def self.ended_card(flow, outcome)
68
+ return nil if outcome == :done || flow.card_id.nil?
69
+
70
+ { id: flow.card_id, title: ENDED_TITLES.fetch(outcome), body: "#{flow.title}: run its command again to try again.",
71
+ actions: [] }
72
+ end
73
+
74
+ # @param listener [Listener, nil] bound already (the redirect_uri's port)
75
+ # @param redirect_uri [String, nil] without a listener (the test kit's)
76
+ # @param clock [#call] monotonic seconds
77
+ # @param on_settle [#call] (flow, outcome), once, off the lock
78
+ # @param cancel [CancellationController, nil] polled (each TICK, by
79
+ # the listener and any #wait): cancelled ends it :cancelled
80
+ def initialize(bundle:, title:, button:, timeout:, listener:, redirect_uri: nil,
81
+ clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }, on_settle: nil, cancel: nil)
82
+ @bundle = bundle
83
+ @title = title
84
+ @button = button
85
+ @listener = listener
86
+ @clock = clock
87
+ @deadline = clock.call + timeout
88
+ @on_settle = on_settle
89
+ @cancel = cancel
90
+ @redirect_uri = listener&.redirect_uri || redirect_uri
91
+ @mutex = Mutex.new
92
+ @settled = ConditionVariable.new
93
+ @outcome = nil
94
+ @result = nil
95
+ end
96
+
97
+ # The flow's address, never its query (an authorize URL can carry a
98
+ # login hint).
99
+ def inspect = "#<#{self.class.name} bundle=#{@bundle} redirect_uri=#{@redirect_uri} outcome=#{outcome.inspect}>"
100
+
101
+ def pretty_print(printer) = printer.text(inspect)
102
+
103
+ # Set once, before the card shows (Engine#start_sign_in).
104
+ # @param address [String] the address the bundle built
105
+ # @param card_id [String]
106
+ # @raise [ArgumentError] the address has no state query parameter
107
+ def started(address, card_id)
108
+ state = state_of(address)
109
+ if state.nil? || state.empty?
110
+ raise ArgumentError, "ctx.sign_in's address needs a state query parameter (a random one per sign-in)"
111
+ end
112
+
113
+ @address = address
114
+ @state = state
115
+ @card_id = card_id
116
+ end
117
+
118
+ # The listener's thread starts: callbacks are taken from now. Should
119
+ # it fail, the flow ends :cancelled (its card says so).
120
+ def listen
121
+ @listener&.start(on_request: ->(query) { offer(query) }, on_tick: -> { expire_if_due },
122
+ on_failed: -> { settle(:cancelled) })
123
+ end
124
+
125
+ # @return [Symbol, nil] OUTCOMES, nil while it waits
126
+ def outcome = @mutex.synchronize { @outcome }
127
+
128
+ # Whether it still waits: past its deadline it ends now, whoever asks
129
+ # (nobody may be in #wait, and the listener may be gone).
130
+ def waiting?
131
+ expire_if_due
132
+ outcome.nil?
133
+ end
134
+
135
+ # Blocks until it settles (or +timeout+ seconds, when given, pass).
136
+ # @return [Hash, nil] the callback's query ({"code"=>…, "state"=>…}),
137
+ # nil for any other outcome
138
+ def wait(timeout = nil)
139
+ until_at = timeout && (@clock.call + timeout)
140
+ loop do
141
+ expire_if_due
142
+ @mutex.synchronize do
143
+ return @result unless @outcome.nil?
144
+
145
+ now = @clock.call
146
+ return nil if until_at && now >= until_at
147
+
148
+ left = [@deadline, until_at].compact.min - now
149
+ @settled.wait(@mutex, left.clamp(0.001, TICK))
150
+ return @result unless @outcome.nil?
151
+ end
152
+ end
153
+ end
154
+
155
+ def cancel = settle(:cancelled)
156
+
157
+ # The worker leaves.
158
+ def stop = settle(:stopped)
159
+
160
+ # Ends it as +outcome+ (:timed_out, :cancelled, :stopped) now: the
161
+ # bundle test kit's fail_sign_in.
162
+ # @return [Boolean] whether this call ended it
163
+ def end_as(outcome)
164
+ raise ArgumentError, "a sign-in ends :done only through a callback" unless (OUTCOMES - [:done]).include?(outcome)
165
+
166
+ settle(outcome)
167
+ end
168
+
169
+ # Whether +address+ (a pasted one) is this flow's: its redirect_uri,
170
+ # with a query or none.
171
+ def redirect_of?(address)
172
+ return false unless @redirect_uri
173
+
174
+ address == @redirect_uri || address.start_with?("#{@redirect_uri}?")
175
+ end
176
+
177
+ # A callback's query (the browser's, or a pasted address's).
178
+ # @param query [String, nil] the part after "?"
179
+ # @return [Boolean] whether it settled the flow :done
180
+ def offer(query)
181
+ params = parse(query)
182
+ return false if params.nil?
183
+ return false if @state.nil? || params["state"] != @state
184
+
185
+ settle(:done, params)
186
+ end
187
+
188
+ # Its cancel: controller was cancelled: :cancelled; the deadline
189
+ # passed: :timed_out.
190
+ # @return [Boolean] whether this call ended it
191
+ def expire_if_due
192
+ return false unless outcome.nil?
193
+ return settle(:cancelled) if @cancel&.cancelled?
194
+ return settle(:timed_out) if @clock.call >= @deadline
195
+
196
+ false
197
+ end
198
+
199
+ private
200
+
201
+ # @return [Boolean] whether this call settled it
202
+ def settle(outcome, result = nil)
203
+ settled = @mutex.synchronize do
204
+ next false unless @outcome.nil?
205
+
206
+ @outcome = outcome
207
+ @result = result
208
+ @settled.broadcast
209
+ true
210
+ end
211
+ return false unless settled
212
+
213
+ @listener&.close
214
+ @on_settle&.call(self, outcome)
215
+ true
216
+ end
217
+
218
+ def parse(query)
219
+ URI.decode_www_form(query.to_s).each_with_object({}) { |(key, value), params| params[key] ||= value }
220
+ rescue ArgumentError
221
+ nil
222
+ end
223
+
224
+ def state_of(address)
225
+ query = URI.parse(address).query
226
+ query && parse(query)&.fetch("state", nil)
227
+ rescue URI::InvalidURIError
228
+ nil
229
+ end
230
+
231
+ # The loopback end of the round trip: a TCPServer on 127.0.0.1 only
232
+ # (never 0.0.0.0 or ::). It answers only `GET <path>?…`: anything
233
+ # else, or a callback the flow refuses (a wrong state), gets a short
234
+ # 404 and the wait goes on. It reads up to MAX_PENDING connections at
235
+ # once, each with its own deadline (READ_TIMEOUT), so a silent one (a
236
+ # browser's preconnect, a stray local process) never holds the real
237
+ # callback up; a request's line and headers are capped (MAX_REQUEST).
238
+ # A connection that breaks (a reset) is dropped alone. The accepted
239
+ # callback gets a small static page (no script, nothing of the
240
+ # request echoed); then it stops listening. Should its loop fail
241
+ # anyway, it closes the port (a browser gets "refused", never a hang)
242
+ # and tells the flow (on_failed).
243
+ class Listener
244
+ HOST = "127.0.0.1"
245
+ MAX_REQUEST = 8 * 1024
246
+ READ_TIMEOUT = 5.0
247
+ # Connections read at once; a newer one drops the oldest.
248
+ MAX_PENDING = 16
249
+ PAGE = <<~HTML
250
+ <!doctype html><html><head><meta charset="utf-8"><title>Signed in</title></head>
251
+ <body style="font-family:system-ui,sans-serif;margin:3em">Signed in. You can close this tab.</body></html>
252
+ HTML
253
+ NOT_FOUND = "That isn't this sign-in's address.\n"
254
+
255
+ # A connection being read: its socket, what came so far, when it is dropped.
256
+ Pending = Struct.new(:socket, :head, :deadline)
257
+
258
+ attr_reader :port
259
+
260
+ # @param port [Integer, nil] nil: any free one
261
+ # @raise [ArgumentError] the port is taken
262
+ def initialize(port: nil, path: SignIn::DEFAULT_PATH, read_timeout: READ_TIMEOUT, tick: SignIn::TICK)
263
+ @path = path
264
+ @read_timeout = read_timeout
265
+ @tick = tick
266
+ @server = TCPServer.new(HOST, port || 0)
267
+ @port = @server.addr[1]
268
+ @closed = false
269
+ @thread = nil
270
+ rescue Errno::EADDRINUSE, Errno::EACCES
271
+ raise ArgumentError, "ctx.sign_in's port #{port} is taken"
272
+ end
273
+
274
+ def redirect_uri = "http://#{HOST}:#{@port}#{@path}"
275
+
276
+ # @param on_request [#call] (query) → whether it settled the flow
277
+ # @param on_tick [#call] called each TICK (and after each wake-up)
278
+ # @param on_failed [#call, nil] its loop failed: the port is closed
279
+ def start(on_request:, on_tick:, on_failed: nil)
280
+ @thread = Thread.new do
281
+ Thread.current.name = "chi-sign-in"
282
+ serve(on_request, on_tick, on_failed)
283
+ end
284
+ end
285
+
286
+ def closed? = @closed
287
+
288
+ def close
289
+ @closed = true
290
+ @server.close unless @server.closed?
291
+ rescue IOError
292
+ nil
293
+ end
294
+
295
+ private
296
+
297
+ def serve(on_request, on_tick, on_failed)
298
+ pending = []
299
+ until @closed
300
+ ready, = IO.select([@server, *pending.map(&:socket)], nil, nil, wait_seconds(pending))
301
+ on_tick.call
302
+ break if @closed
303
+
304
+ Array(ready).each do |io|
305
+ break if @closed
306
+
307
+ io.equal?(@server) ? admit(pending) : read_more(pending, pending.find { |p| p.socket.equal?(io) }, on_request)
308
+ end
309
+ drop_late(pending)
310
+ end
311
+ rescue StandardError => e # IOError, SystemCallError: closed under it, when @closed
312
+ failed(e, on_failed) unless @closed
313
+ ensure
314
+ pending&.each { |p| drop(pending, p) }
315
+ end
316
+
317
+ def failed(error, on_failed)
318
+ Log.warn(:plugins, "sign_in_listener_failed", error: error.class.name)
319
+ close
320
+ on_failed&.call
321
+ end
322
+
323
+ # Until the next tick or the soonest connection's deadline.
324
+ def wait_seconds(pending)
325
+ soonest = pending.map(&:deadline).min
326
+ return @tick unless soonest
327
+
328
+ (soonest - now).clamp(0.0, @tick)
329
+ end
330
+
331
+ def admit(pending)
332
+ client = @server.accept_nonblock
333
+ drop(pending, pending.first) if pending.size >= MAX_PENDING
334
+ pending << Pending.new(client, +"", now + @read_timeout)
335
+ rescue IO::WaitReadable, Errno::EINTR, Errno::ECONNABORTED
336
+ nil
337
+ end
338
+
339
+ # Its next chunk; a whole head is answered. A connection that broke
340
+ # (reset, closed), ran past MAX_REQUEST or was answered is dropped.
341
+ def read_more(pending, conn, on_request)
342
+ return unless conn
343
+
344
+ chunk = conn.socket.read_nonblock(4096, exception: false)
345
+ return if chunk == :wait_readable
346
+ return drop(pending, conn) if chunk.nil?
347
+
348
+ conn.head << chunk
349
+ return drop(pending, conn) if conn.head.bytesize > MAX_REQUEST
350
+ return unless conn.head.include?("\r\n\r\n") || conn.head.include?("\n\n")
351
+
352
+ answer(conn.socket, conn.head, on_request)
353
+ drop(pending, conn)
354
+ rescue IOError, SystemCallError
355
+ drop(pending, conn)
356
+ end
357
+
358
+ def drop_late(pending)
359
+ at = now
360
+ pending.select { |conn| conn.deadline <= at }.each { |conn| drop(pending, conn) }
361
+ end
362
+
363
+ def drop(pending, conn)
364
+ pending.delete(conn)
365
+ conn.socket.close unless conn.socket.closed?
366
+ rescue IOError, SystemCallError
367
+ nil
368
+ end
369
+
370
+ def answer(client, head, on_request)
371
+ method, target = head.lines.first.to_s.split(" ", 3)
372
+ path, query = target.to_s.split("?", 2)
373
+ if method == "GET" && path == @path && on_request.call(query)
374
+ respond(client, "200 OK", "text/html; charset=utf-8", PAGE)
375
+ close
376
+ else
377
+ respond(client, "404 Not Found", "text/plain; charset=utf-8", NOT_FOUND)
378
+ end
379
+ end
380
+
381
+ def respond(client, status, type, body)
382
+ client.write("HTTP/1.1 #{status}\r\nContent-Type: #{type}\r\nContent-Length: #{body.bytesize}\r\n" \
383
+ "Cache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n#{body}")
384
+ rescue IOError, SystemCallError
385
+ nil
386
+ end
387
+
388
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
389
+ end
390
+ end
391
+ end
392
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ module Plugin
5
+ class Http
6
+ # A plain Server-Sent Events reader (ctx.http.stream's Stream#each_event),
7
+ # fed the body's chunks as they arrive:
8
+ #
9
+ # reader = SseReader.new
10
+ # reader.feed(chunk) { |event| … } # each event whose blank line came
11
+ #
12
+ # The fields are `event`, `data` and `id`; several `data:` lines join
13
+ # with "\n"; one space after the colon is dropped; a line starting
14
+ # with ":" is a comment. Lines end in "\n", "\r\n" or "\r", and a
15
+ # chunk may end anywhere (mid-line, between "\r" and "\n", inside a
16
+ # UTF-8 character): bytes are kept until an event is whole, and its
17
+ # text is decoded then. An event is dispatched at its blank line; one
18
+ # the body's end cuts off is dropped; an event without data isn't
19
+ # yielded. The last `id` carries over to later events, as in a
20
+ # browser's EventSource.
21
+ class SseReader
22
+ # One event: +type+ is "message" when the stream named none.
23
+ Event = Data.define(:type, :data, :id)
24
+
25
+ BOM = "\xEF\xBB\xBF".b
26
+
27
+ def initialize
28
+ @buffer = +"".b
29
+ @skip_lf = false
30
+ @started = false
31
+ @id = nil
32
+ reset
33
+ end
34
+
35
+ # @param chunk [String] the next bytes of the body
36
+ # @yield [Event] each event the chunk completes
37
+ # @return [void]
38
+ def feed(chunk, &)
39
+ bytes = chunk.to_s.b
40
+ return if bytes.empty?
41
+
42
+ if @skip_lf
43
+ @skip_lf = false
44
+ bytes = bytes.delete_prefix("\n")
45
+ end
46
+ @buffer << bytes
47
+ unless @started
48
+ return if BOM.start_with?(@buffer) # all of it may still be a BOM
49
+
50
+ @started = true
51
+ @buffer = @buffer.delete_prefix(BOM)
52
+ end
53
+ lines(&)
54
+ end
55
+
56
+ private
57
+
58
+ def lines(&)
59
+ while (at = @buffer.index(/[\r\n]/))
60
+ line = @buffer.byteslice(0, at)
61
+ ending = if @buffer.byteslice(at, 2) == "\r\n" then 2
62
+ else
63
+ @skip_lf = true if @buffer.bytesize == at + 1 && @buffer.byteslice(at) == "\r"
64
+ 1
65
+ end
66
+ @buffer = @buffer.byteslice((at + ending)..)
67
+ line(line, &)
68
+ end
69
+ end
70
+
71
+ def line(line, &)
72
+ return dispatch(&) if line.empty?
73
+ return if line.start_with?(":")
74
+
75
+ field, value = line.split(":", 2)
76
+ value = value.to_s.delete_prefix(" ")
77
+ case field
78
+ when "event" then @type = value
79
+ when "data" then (@data ||= []) << value
80
+ when "id" then @id = text(value) unless value.include?("\0")
81
+ end
82
+ end
83
+
84
+ def dispatch
85
+ data = @data
86
+ type = @type
87
+ reset
88
+ return unless data
89
+
90
+ yield Event.new(type: type.nil? || type.empty? ? "message" : text(type), data: text(data.join("\n")), id: @id)
91
+ end
92
+
93
+ def reset
94
+ @data = nil
95
+ @type = nil
96
+ end
97
+
98
+ # The event's bytes as UTF-8, a broken sequence replaced.
99
+ def text(bytes) = bytes.dup.force_encoding(Encoding::UTF_8).scrub
100
+ end
101
+ end
102
+ end
103
+ end
@@ -117,11 +117,18 @@ module Samagotchi
117
117
  # the file is empty or can't be read.
118
118
  # @return [String, nil]
119
119
  def section(path, header)
120
- content = File.read(path, encoding: "UTF-8").strip
121
- return nil if content.empty?
120
+ content = content(path)
121
+ content && "#{header}\n#{content}"
122
+ end
122
123
 
123
- "#{header}\n#{content}"
124
- rescue StandardError
124
+ # +path+'s text as the prompt carries it under its header: stripped;
125
+ # nil when empty or unreadable. The prompt's build (#section) and the
126
+ # working set's re-fetch of an AGENTS.md part.
127
+ # @return [String, nil]
128
+ def content(path)
129
+ content = File.read(path, encoding: "UTF-8").strip
130
+ content.empty? ? nil : content
131
+ rescue StandardError # degrade-ok: an unreadable file is left out of the prompt, as before
125
132
  nil
126
133
  end
127
134
  end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "prompt_part"
4
+
5
+ module Samagotchi
6
+ # Where each SystemPrompt::Item of a build sits in the prompt the build
7
+ # made, worked out once beside it (SystemPrompt#prompt_parts_for): the
8
+ # place fields of its PromptPart (at, len, lead, digest, head). The
9
+ # sections are joined by "\n" (the stable ones, then the volatile ones),
10
+ # each section's items by its join; joins and the scope headings that
11
+ # belong to no item fall outside every span (a note's heading is the
12
+ # first note's lead). See docs/internals/working-set.md (Prompt parts as
13
+ # sent).
14
+ #
15
+ # The tool declarations: on a chat host they are not in the prompt (no
16
+ # place); native, inside the base text ("You have access to the following
17
+ # tools:"), whose own slice leaves them out, or, on Gemma, after the last
18
+ # section, where the prompt was rstripped before them: an item running
19
+ # into that strip is cut at it.
20
+ class PromptLayout
21
+ # What the base text says before the declarations: SystemPrompt#assist_system_prompt
22
+ # writes it from here, so the two can't drift.
23
+ TOOLS_LEAD = "You have access to the following tools:\n\n"
24
+
25
+ # @param prompt [String] the built prompt
26
+ # @param sections [Array<SystemPrompt::Section>] in prompt order
27
+ # @param declarations [String, nil] the native declarations text (nil: chat)
28
+ # @param tail [Boolean] Gemma's: the declarations follow the rstripped prompt
29
+ def initialize(prompt, sections, declarations:, tail:)
30
+ @head = PromptPart.digest_of(prompt, 16)
31
+ @spans = {}.compare_by_identity
32
+ @end = tail && declarations ? prompt.length - declarations.length : prompt.length
33
+ at = 0
34
+ sections.each do |section|
35
+ offset = at
36
+ section.items.each do |item|
37
+ @spans[item] = [offset, item.sent.length.clamp(0, [@end - offset, 0].max)]
38
+ offset += item.sent.length + section.join.length
39
+ end
40
+ at += section.text.length + 1
41
+ end
42
+ @tools = tools_span(sections, declarations, tail)
43
+ end
44
+
45
+ # Whether the declarations sit inside the base text (their chars move
46
+ # out of the base part, SystemPrompt#prompt_parts_for).
47
+ def tools_in_base? = !@tools.nil? && !@tools_tail
48
+
49
+ # The place fields of +item+'s part.
50
+ # @return [Hash]
51
+ def place(item)
52
+ at, len = @spans.fetch(item)
53
+ body = item.text
54
+ if item.kind == :base && tools_in_base?
55
+ from = @tools[0] - at - item.lead.length
56
+ body = body[0, from].to_s + body[(from + @tools[1])..].to_s
57
+ end
58
+ { at: at, len: len, lead: item.lead.length, digest: PromptPart.digest_of(body), head: @head }
59
+ end
60
+
61
+ # The tools part's place fields: none on a chat host.
62
+ # @return [Hash]
63
+ def tools_place
64
+ return {} unless @tools
65
+
66
+ { at: @tools[0], len: @tools[1], lead: 0, head: @head }
67
+ end
68
+
69
+ private
70
+
71
+ # [at, len] of the declarations in the prompt, nil when they aren't in
72
+ # it (chat) or can't be found.
73
+ def tools_span(sections, declarations, tail)
74
+ return nil unless declarations
75
+
76
+ if tail
77
+ @tools_tail = true
78
+ return [@end, declarations.length]
79
+ end
80
+
81
+ base = sections.first&.items&.first
82
+ return nil unless base&.kind == :base
83
+
84
+ index = base.text.index("#{TOOLS_LEAD}#{declarations}")
85
+ index && [@spans.fetch(base)[0] + base.lead.length + index + TOOLS_LEAD.length, declarations.length]
86
+ end
87
+ end
88
+ end