samagotchi 0.182.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  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 +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -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,173 @@
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
+ # @return [Attempted, Stopped]
124
+ def attempt(target, prompt, client_id:, queue: false, cut: false, images: nil, check: nil)
125
+ id = target.id
126
+ session = @access.show(id)
127
+ if check && (refusal = check.call(session))
128
+ return Stopped.new(target: target, refusal: refusal)
129
+ end
130
+
131
+ owner = @access.owner(id)
132
+ running = owner && session.status == Session::STATUS_RUNNING
133
+ refs = images ? images.upload(id) : []
134
+ delivery = if queue then Delivery::QUEUE
135
+ elsif cut && running then Delivery::CUT
136
+ end
137
+ result = @access.deliver_turn(id, prompt: prompt, client_id: client_id, images: refs, delivery: delivery,
138
+ follow: target.via != :pinned)
139
+ Attempted.new(target: target, session: session, owner: owner, running: running, delivery: delivery, refs: refs,
140
+ result: result)
141
+ end
142
+
143
+ # The wait for an accepted message's own turn (ReplyWait::Target.message).
144
+ # @param start [WaitStart] prepare_wait's, read before it went in
145
+ def bind(start, result, queue:) = ReplyWait::Target.message(start, result, queue: queue)
146
+
147
+ # The backend's wait for what +target+ binds: the result's turn_id is
148
+ # the target's report_turn_id whenever that is known (even when the
149
+ # wait took the next reply), its text UTF-8.
150
+ # @param more [Hash] passed on (cancelled: for a Local backend)
151
+ # @return [ReplyWait::Result]
152
+ # @raise [ArgumentError] the session is gone
153
+ def wait(id, target, timeout:, poll_interval: nil, **more)
154
+ options = { timeout: timeout, **more }
155
+ options[:poll_interval] = poll_interval if poll_interval
156
+ result = @access.wait_reply(id, **target.to_h, **options)
157
+ report_turn_id = target.report_turn_id
158
+ result.turn_id = report_turn_id if report_turn_id && !report_turn_id.to_s.empty?
159
+ result.text = result.text&.dup&.force_encoding(Encoding::UTF_8)&.scrub
160
+ result
161
+ end
162
+
163
+ # This exchange's clock, for a caller's deadline (#relocate's).
164
+ def now = @clock.call
165
+
166
+ private
167
+
168
+ # One pause between two looks: continuing_poll, or less when
169
+ # +deadline+ comes first.
170
+ def pause_until(deadline) = @pause.call([@continuing_poll, deadline - @clock.call].min)
171
+ end
172
+ end
173
+ end
@@ -191,9 +191,15 @@ module Samagotchi
191
191
  # @return [SessionManager::DeliverResult]
192
192
  # @raise [SessionManager::OwnedByTUI] a one-turn chi run owns it
193
193
  # @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)
194
+ # @param manager [#resume_session, nil] the manager that starts its
195
+ # worker; nil: SessionManager's own default
196
+ # @param bridge [#call, nil] the worker's Bridge client (chi web's
197
+ # live_bridge_client: POST …/ask delivers as POST …/turn does); nil:
198
+ # SessionManager's own wait
199
+ def deliver_turn(id, prompt:, client_id:, images:, delivery: nil, follow: false, manager: nil, bridge: nil)
200
+ routing = { manager: manager, bridge: bridge }.compact
195
201
  SessionManager.deliver_turn(id, prompt: prompt, client_id: client_id, images: images, delivery: delivery,
196
- follow: follow, **dir)
202
+ follow: follow, **routing, **dir)
197
203
  end
198
204
 
199
205
  # @return [NoteDelivery::Result]
@@ -266,11 +272,16 @@ module Samagotchi
266
272
 
267
273
  # The answer posted to the session's worker (its Bridge), once more
268
274
  # after a 408.
275
+ # @param within [Numeric, nil] the most seconds for it all (an MCP
276
+ # call's, under its host's limit): each try's read timeout is cut
277
+ # to it, and a 408 is tried again only when a whole try still fits
269
278
  # @return [BridgeClient::Response, nil] the Bridge's reply; nil when
270
279
  # no worker runs it
271
280
  # @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) }
281
+ def answer(id, question_id:, selected:, freeform:, client_id:, within: nil)
282
+ on_worker(id, within: within) do |client|
283
+ client.answer(id: question_id, selected: selected, freeform: freeform, client_id: client_id)
284
+ end
274
285
  end
275
286
 
276
287
  # The question dismissed on the session's worker; as #answer.
@@ -629,15 +640,23 @@ module Samagotchi
629
640
 
630
641
  # The block's post to the session's live worker, again on a 408 (the
631
642
  # 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
643
+ # The shortest read timeout a cut try gets (#on_worker's within:).
644
+ MIN_TRY = 1.0
645
+
646
+ def on_worker(id, within: nil)
647
+ limit = within ? within.to_f.clamp(MIN_TRY, BridgeClient::READ_TIMEOUT.to_f) : BridgeClient::READ_TIMEOUT
648
+ client = WorkerLink.client(id, session_dir: session_dir(id), read_timeout: limit) or return nil
649
+ ends = monotonic + within if within
634
650
  reply = nil
635
651
  2.times do
636
652
  reply = yield client
637
653
  break unless reply.status == 408
654
+ break if ends && monotonic + limit > ends
638
655
  end
639
656
  reply
640
657
  end
658
+
659
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
641
660
  end
642
661
  end
643
662
  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
@@ -39,6 +39,7 @@ module Samagotchi
39
39
  OBJECTIVES_COMMAND = "/objectives"
40
40
  ROLLBACK_COMMAND = "!rollback"
41
41
  CONTINUE_COMMAND = TurnFlow::CONTINUE_COMMAND
42
+ CALLBACK_COMMAND = "/callback"
42
43
  SHELL_BANG_PREFIX = "!"
43
44
  # /exit --delete: delete the session on the way out.
44
45
  EXIT_DELETE_FLAG = "--delete"
@@ -102,6 +103,15 @@ module Samagotchi
102
103
  registry.register(OBJECTIVES_COMMAND, "show or edit what this session is to achieve (set A | B, add TEXT, edit ID TEXT, done ID…, drop ID…, undo ID…, check ID, track)",
103
104
  id: :objectives, anytime: true) { |text| objectives(text) }
104
105
  registry.register(HELP_COMMAND, "list the commands, the bundles' too", anytime: true) { |_text| reply(help_listing) }
106
+ # A sign-in's ending pasted from a browser elsewhere (ctx.sign_in): at
107
+ # once, a turn running or not. Its address holds a one-time code: kept
108
+ # out of every event, log and echo (private_args, QueuedCommand).
109
+ # #run passes who sent it (as_parent:): a parent agent may not. Its
110
+ # match takes any line after the word, more lines too (the handler
111
+ # refuses those), so the address never goes to the model as a message.
112
+ registry.register(CALLBACK_COMMAND, "finish a waiting sign-in with the address the browser ended on (/callback ADDRESS)",
113
+ anytime: true, private_args: true,
114
+ match: ->(text) { text.match?(%r{\A/callback(?:\s|\z)}) }) { |text| callback(text) }
105
115
  registry.register("/stats", "show the session's stats", local: true)
106
116
  # /recap with words (on|off|default, or a slip: the usage) runs here:
107
117
  # it toggles the idle job only, so it doesn't wait for a running turn.
@@ -189,6 +189,7 @@ module Samagotchi
189
189
  # an anytime command runs on another thread against this instance.
190
190
  return continue_command(text, as_parent: as_parent) if entry.id == :continue
191
191
  return parent_answers(text, user_ui: user_ui) if entry.id == :parent_answers
192
+ return callback(text, as_parent: as_parent) if entry.id == :callback
192
193
 
193
194
  instance_exec(text, &entry.handler)
194
195
  end
@@ -545,6 +546,22 @@ module Samagotchi
545
546
  reply(output, status: status, changed: changed ? [:title] : [])
546
547
  end
547
548
 
549
+ # /callback ADDRESS: the waiting sign-in it belongs to takes the
550
+ # address's query (Engine#sign_in_callback). A parent agent's chi answer
551
+ # doesn't finish the owner's sign-in. The answer never repeats the
552
+ # address.
553
+ def callback(text, as_parent: false)
554
+ return reply("a parent agent doesn't finish this session's sign-in", status: :error) if as_parent
555
+
556
+ address = text.delete_prefix(CALLBACK_COMMAND).strip
557
+ if address.empty? || address.match?(/\s/)
558
+ return reply("usage: /callback ADDRESS, on one line (the address the browser ended on)", status: :error)
559
+ end
560
+
561
+ settled, line = @engine.sign_in_callback(address)
562
+ reply(line, status: settled ? :ok : :error)
563
+ end
564
+
548
565
  # /objectives (ObjectivesCommand): nothing to save, an edit is a note file.
549
566
  def objectives(text)
550
567
  output, status = ObjectivesCommand.new(engine: @engine).run(text.delete_prefix(OBJECTIVES_COMMAND))
@@ -293,7 +293,7 @@ module Samagotchi
293
293
  # The installed bundles a session may set settings of: a record that
294
294
  # doesn't read is left out, and so is one this chi is too old for
295
295
  # (InstalledBundles::Standing: requires_chi, plugin or not) or whose
296
- # plugin doesn't load (Dir#file_refusal(:plugin): the file, its sha256),
296
+ # plugin doesn't load (Dir#plugin_refusal: its files, their sha256),
297
297
  # with a note saying why. A record with no
298
298
  # session_settings whose shipped bundle lists some (installed before
299
299
  # them) gets a note on refreshing it.
@@ -385,13 +385,13 @@ module Samagotchi
385
385
  end
386
386
 
387
387
  # Why a usable +standing+'s plugin doesn't load, as the plugin loader
388
- # would refuse it (Dir#file_refusal(:plugin)), nil when it does or it has
389
- # none.
388
+ # would refuse it (Dir#plugin_refusal: the file, its parts), nil when it
389
+ # does or it has none.
390
390
  def unloadable(dir, standing)
391
391
  plugin = standing.record.plugin
392
392
  return nil unless plugin
393
393
 
394
- InstalledBundles::Dir.new(name: standing.name, dir: dir).file_refusal(:plugin, plugin.file, plugin.sha256)&.text
394
+ InstalledBundles::Dir.new(name: standing.name, dir: dir).plugin_refusal(standing.record)&.text
395
395
  end
396
396
 
397
397
  # Whether chi ships a bundle +name+ whose manifest lists session_settings.
@@ -26,6 +26,15 @@ module Samagotchi
26
26
  # counted (Engine#note_side_usage): `kind:` and `side:`, the session's
27
27
  # whole side block (SessionMetrics#add_side), in fold order.
28
28
  class SessionObserver
29
+ # Event types #announce accepts: facts about the session's input queue,
30
+ # a failed turn's prompt handed back and the continue offer, which live
31
+ # UIs need in the event log, emitted outside any turn's stream; a
32
+ # Verify fresh child's verdict landing on its card (:verdict_recorded).
33
+ ANNOUNCEABLE_EVENTS = %i[turn_enqueued turn_dequeued input_merged prompt_restored continue_offered continue_resolved
34
+ command_queued command_ran context_added card hook_notice guardrail_warning
35
+ plugin_init_started plugin_init_finished working_set_updated participants_changed
36
+ verdict_recorded objectives_updated].freeze
37
+
29
38
  # Handle returned by #subscribe. Holds the observer reference and carries
30
39
  # #unsubscribe so a caller can deregister without keeping the registry.
31
40
  class SubscribedObserver
@@ -106,6 +115,19 @@ module Samagotchi
106
115
  end
107
116
  end
108
117
 
118
+ # Put a transport-level event into the ordered event log (#notify), after
119
+ # checking its type. Unlike turn events it reaches only persistent
120
+ # observers (no turn sink, no memory capture).
121
+ # @param event [Hash] with :type in ANNOUNCEABLE_EVENTS
122
+ # @raise [ArgumentError] for any other type (before #notify, outside the lock)
123
+ def announce(event)
124
+ unless ANNOUNCEABLE_EVENTS.include?(event[:type])
125
+ raise ArgumentError, "cannot announce #{event[:type].inspect} (allowed: #{ANNOUNCEABLE_EVENTS.join(", ")})"
126
+ end
127
+
128
+ notify(event)
129
+ end
130
+
109
131
  # @return [Integer] total events emitted so far (Engine-local sequence)
110
132
  def event_count
111
133
  @mutex.synchronize { @seq }
@@ -117,5 +139,10 @@ module Samagotchi
117
139
  def synchronize(&)
118
140
  @mutex.synchronize(&)
119
141
  end
142
+
143
+ # @return [Boolean] whether the calling thread holds the event lock
144
+ def held?
145
+ @mutex.mon_owned?
146
+ end
120
147
  end
121
148
  end
@@ -11,9 +11,10 @@ module Samagotchi
11
11
  # A message for the running turn cutting the generation it came during:
12
12
  # what the generation streams (GenerationPhase, fed by #observe from the
13
13
  # turn's stream) and a message that came too early to cut (WaitingSteer).
14
- # The Engine's seam: Bridge and TerminalUI call Engine#cut_for_steer and
15
- # #input_epoch, the turn thread feeds #observe and #delivered!, and the
16
- # turn's end calls #finished!. Callable from any thread: GenerationPhase
14
+ # The Engine's one, which the Worker hands the Bridge (Engine#steer_cut):
15
+ # the Bridge calls #cut_for_steer, #input_epoch and #generation_snapshot,
16
+ # the turn thread feeds #observe and #delivered!, and the turn's end calls
17
+ # #finished!. Callable from any thread: GenerationPhase
17
18
  # and WaitingSteer hold their own locks.
18
19
  class SteerCut
19
20
  # A chunk's thinking and text. A chunk without the lanes (no loop of
@@ -131,7 +131,10 @@ module Samagotchi
131
131
 
132
132
  # @param choice [Symbol, nil] :cut or :queue when typed with that word
133
133
  def send_prompt(text, delivery: nil, choice: nil)
134
- persist_recent_history(text)
134
+ # A /cut or /queue of a command that hides its arguments (/callback's
135
+ # one-time code): the worker runs it as that command, and the
136
+ # history keeps none of it.
137
+ persist_recent_history(text) unless command_registry.private_args?(text)
135
138
  images = attach_images(text)
136
139
  return own_prompt_failed if images.nil?
137
140
 
@@ -14,6 +14,8 @@ require_relative "../session_config"
14
14
  require_relative "../message_time"
15
15
  require_relative "../tools/task_record"
16
16
  require_relative "model_segments_text"
17
+ require_relative "../ref"
18
+ require_relative "../plugin/card"
17
19
 
18
20
  module Samagotchi
19
21
  class TerminalUI
@@ -371,6 +373,8 @@ module Samagotchi
371
373
  lines = [head]
372
374
  wrap_plain(strip_markdown(card[:body].to_s), width - 2).each { |line| lines << (line.empty? ? rail : "#{rail} #{line}") }
373
375
  Array(card[:actions]).each do |action|
376
+ next lines.concat(card_url_lines(action, rail)) if action[:url] && !action[:command]
377
+
374
378
  command = action[:command].to_s
375
379
  label = action[:label].to_s
376
380
  line = "#{rail} #{paint("→ #{command}", 36)}"
@@ -381,6 +385,17 @@ module Samagotchi
381
385
  lines.join("\n")
382
386
  end
383
387
 
388
+ # A url action: "→ <label>" on the rail, then the address on its own
389
+ # line with no rail, no paint and no wrapping by chi, so a terminal's
390
+ # own click or a copy gets the whole address. One that isn't http(s)
391
+ # (Plugin::Card checks it; a saved card isn't rebuilt) prints nothing.
392
+ def card_url_lines(action, rail)
393
+ url = action[:url].to_s.strip
394
+ return [] unless RefAction.http_url?(url, max: Plugin::Card::MAX_URL)
395
+
396
+ ["#{rail} #{paint("→ #{action[:label]}", 36)}", url]
397
+ end
398
+
384
399
  # A card body's markdown made plain, cheaply (there is no terminal
385
400
  # markdown): **x** and __x__ are x, backticks and code fences go, and
386
401
  # so do headings' #s. Lists stay as they are.
@@ -24,10 +24,14 @@ module Samagotchi
24
24
  Allowed.new(name: "Samagotchi::Plugin::HttpError", file: "samagotchi/plugin/http"),
25
25
  Allowed.new(name: "Samagotchi::Plugin::HttpCancelled", file: "samagotchi/plugin/http"),
26
26
  Allowed.new(name: "Samagotchi::Plugin::Http::Response", file: "samagotchi/plugin/http"),
27
+ Allowed.new(name: "Samagotchi::Plugin::Http::Stream", file: "samagotchi/plugin/http"),
28
+ Allowed.new(name: "Samagotchi::Plugin::Http::SseReader", file: "samagotchi/plugin/http"),
27
29
  Allowed.new(name: "Samagotchi::Plugin::Service::Stopped", file: "samagotchi/plugin/service"),
28
30
  Allowed.new(name: "Samagotchi::Plugin::Sessions::Error", file: "samagotchi/plugin/sessions"),
29
31
  Allowed.new(name: "Samagotchi::Plugin::AttachedContext::Error", file: "samagotchi/plugin/attached_context"),
30
32
  Allowed.new(name: "Samagotchi::Plugin::Peer", file: "samagotchi/plugin/peer"),
33
+ Allowed.new(name: "Samagotchi::Plugin::Secrets::Unavailable", file: "samagotchi/plugin/secrets"),
34
+ Allowed.new(name: "Samagotchi::Plugin::Secrets::Busy", file: "samagotchi/plugin/secrets"),
31
35
  Allowed.new(name: "Samagotchi::Tools::ToolIndex::Tool", file: "samagotchi/tools/tool_index"),
32
36
  Allowed.new(name: "Samagotchi::Tools::ToolIndex::Group", file: "samagotchi/tools/tool_index"),
33
37
  Allowed.new(name: "Samagotchi::Tools::ToolIndex.schema_note", file: "samagotchi/tools/tool_index"),
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "uri"
3
4
  require_relative "../plugin/loader"
4
5
  require_relative "../plugin/tool_spec"
5
6
  require_relative "../hooks"
@@ -177,9 +178,10 @@ module Samagotchi
177
178
  # @api private (Bundle.load)
178
179
  def load!
179
180
  if (plugin = @manifest.plugin)
181
+ parts = part_paths
180
182
  @namespace = Plugin::Loader.fresh_namespace(@name)
181
183
  @api = Plugin::Loader.register_file(@name, File.join(@dir, plugin[:file]), @registries, settings: @settings,
182
- namespace: @namespace,
184
+ namespace: @namespace, parts: parts,
183
185
  api_class: RecordingApi) do |built|
184
186
  @plugin = built
185
187
  end
@@ -190,6 +192,18 @@ module Samagotchi
190
192
  raise
191
193
  end
192
194
 
195
+ # The manifest's plugin parts in the source, in load order.
196
+ # @raise [ArgumentError] one the manifest names that isn't there
197
+ def part_paths
198
+ @manifest.plugin_parts.keys.map do |part|
199
+ path = File.join(@dir, part)
200
+ raise ArgumentError, "#{@name}: #{BundleManifest.missing_part(part)}" unless File.file?(path)
201
+
202
+ path
203
+ end
204
+ end
205
+ private :part_paths
206
+
193
207
  # ── Firing ──────────────────────────────────────────────────────────
194
208
 
195
209
  # Fire hook +event+ through the registry, as chi's fire sites do: the
@@ -358,6 +372,29 @@ module Samagotchi
358
372
 
359
373
  def notices = @recorder.notices
360
374
  def cards = @recorder.cards
375
+ # What ctx.secrets holds now ({"name" => "value"}); seed it with
376
+ # bundle.set(secrets: {...}).
377
+ def secrets = @recorder.secrets.to_h
378
+
379
+ # Every ctx.sign_in flow, oldest first (Plugin::SignIn: #title,
380
+ # #address the block built, #redirect_uri, #card_id, #outcome). The kit
381
+ # opens no port.
382
+ def sign_ins = @recorder.sign_ins
383
+
384
+ # The newest sign-in's callback arrives with +params+ (the query the
385
+ # browser would bring: {"code" => "c1", "state" => "…"}). A state that
386
+ # isn't the address's is ignored, as chi ignores it.
387
+ # @return [Boolean] whether it settled the flow :done
388
+ def complete_sign_in(params)
389
+ newest_sign_in.offer(URI.encode_www_form(params.to_h { |key, value| [key.to_s, value.to_s] }))
390
+ end
391
+
392
+ # The newest sign-in ends as +outcome+ (:timed_out, :cancelled,
393
+ # :stopped) with no callback: its card is replaced as chi does.
394
+ def fail_sign_in(outcome = :timed_out)
395
+ newest_sign_in.end_as(outcome)
396
+ end
397
+
361
398
  def steers = @recorder.steers
362
399
  # Every stop_turn and stop_generation, in order (Stop#kind).
363
400
  def stops = @recorder.stops
@@ -398,8 +435,17 @@ module Samagotchi
398
435
  self
399
436
  end
400
437
 
401
- # Stop the plugin's services; leave the sandbox it entered.
438
+ def newest_sign_in
439
+ sign_ins.last or raise ArgumentError, "no ctx.sign_in was started"
440
+ end
441
+ private :newest_sign_in
442
+
443
+ # Stop the plugin's services and its waiting sign-ins; leave the
444
+ # sandbox it entered.
402
445
  def shutdown
446
+ # As a worker leaving does: a waiting sign-in ends :stopped (its
447
+ # waiting thread goes on).
448
+ sign_ins.each(&:stop)
403
449
  @registries&.services&.stop_all
404
450
  return unless @own_sandbox
405
451